2017-10-18 27 views
1

我有一個腳本可以運行一個可執行文件,並等到PS完成,但我需要修改它以使用在腳本中的變量中定義的路徑。如何在PowerShell中從指定的目錄運行命令並在繼續之前等待它完成?

工作:

$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 
+0

如果你想等待一個程序來完成,那麼你爲什麼將它作爲後臺工作來運行? –

+0

'Start-Process -Wait -WindowStyle Hidden'是正常的方法。 –

+0

在繼續之前,這是我唯一能夠在比賽中競爭的唯一途徑。我在這個新法案 – VenerableAgents

回答

2

組合來自Start-Job文檔信息與About_Scopes文章中,我敢肯定,你需要使用-InputObject參數:

Specifies input to the command. Enter a variable that contains the objects, or type a command or expression that generates the objects.
In the value of the ScriptBlock parameter, use the $Input automatic variable to represent the input objects.

$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 
0

我想你想Start-Process-Wait參數。您也可以指定-WorkingDirectory參數來指定新進程的工作目錄。例如:

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

當您運行此腳本,記事本打開,但該腳本將無法繼續,直至關閉。當您關閉記事本時,Write-Host行會運行。

+0

這並沒有解決如何處理它與一個可變的執行文件夾。 – VenerableAgents

+0

如果需要,您可以使用'-WorkingDirectory'參數的變量。 –

相關問題