代码之家  ›  专栏  ›  技术社区  ›  VenerableAgents

如何在PowerShell中从指定目录运行命令并等待其完成后再继续?

  •  1
  • VenerableAgents  · 技术社区  · 8 年前

    工作:

    $job = Start-Job `
        -InitializationScript { Set-Location C:\MyDirectory\ }  `
        -ScriptBlock { C:\MyDirectory\MyCmdLineExecutable.exe }
    Wait-Job $job
    Receive-Job $job
    

    $Path = "C:\MyDirectory\"
    $ExePath = $path+"MyCmdLineExecutable.exe"
    $job = Start-Job `
        -InitializationScript { Set-Location $Path }  `
        -ScriptBlock { $ExePath }
    Wait-Job $job
    Receive-Job $job
    

    以下是错误:

    Set-Location : Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value.
    At line:1 char:2
    +  Set-Location $Path
    +  ~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [Set-Location], PSArgumentNullException
        + FullyQualifiedErrorId : ArgumentNull,Microsoft.PowerShell.Commands.SetLocationCommand
    
    
    Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
    --     ----            -------------   -----         -----------     --------             -------                  
    49     Job49           BackgroundJob   Failed        False           localhost             $ExePath                
    Running startup script threw an error: Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value..
        + CategoryInfo          : OpenError: (localhost:String) [], RemoteException
        + FullyQualifiedErrorId : PSSessionStateBroken
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   JosefZ    8 年前

    组合来自的信息 Start-Job 带有的文档 About_Scopes 文章,我确信你需要使用 -InputObject 参数:

    指定命令的输入。输入包含 物体。
    脚本块 参数,使用 $Input automatic variable 表示输入对象。

    $Path = "C:\MyDirectory\"
    $ExePath = $path+"MyCmdLineExecutable.exe"
    
    $job = Start-Job -InputObject @( $Path, $ExePath) `
        -InitializationScript { <# $Input variable isn't defined here #> }  `
        -ScriptBlock { 
            $aux = $Input.GetEnumerator()
            Set-Location $aux[0]
            & $aux[1] }
    Wait-Job $job
    Receive-Job $job
    

    顺便说一句,收件人 存储在变量中并由字符串表示的命令,使用 & Call operator

    $ExePath        ### output only
    & $ExePath      ### invocation
    
        2
  •  0
  •   Bill_Stewart    8 年前

    我想你想要 Start-Process -Wait -WorkingDirectory 参数指定新进程的工作目录。例子:

    Start-Process notepad -WorkingDirectory "C:\Program Files" -Wait
    Write-Host "Finished"
    

    运行此脚本时,记事本将打开,但脚本在关闭之前不会继续。当您关闭记事本时 Write-Host 线路运行。

    推荐文章