如何在指定目录中运行PowerShell中的命令并等待它继续运行?

时间:2017-10-18 21:42:13

标签: powershell

我有一个脚本可以运行可执行文件并等到PS完成,但我需要修改它以使用脚本中较早的变量中定义的路径。

工作:

$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 个答案:

答案 0 :(得分:2)

Start-Job文档中的信息与About_Scopes文章相结合,我确信您需要使用-InputObject参数:

  

指定命令的输入。输入包含的变量   对象,或键入生成的对象或表达式   对象。
ScriptBlock 参数的值中,使用   $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

BTW,运行命令存储在变量中并由字符串表示,使用& Call operator。看到差异:

$ExePath        ### output only
& $ExePath      ### invocation

答案 1 :(得分:0)

我认为您希望Start-Process使用-Wait参数。您还可以指定-WorkingDirectory参数以指定新进程的工作目录。例如:

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

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