2016-09-28 69 views
0

這項工作的預期結果是運行一個簡單的.bat腳本作爲PowerShell作業。除了輸出結束處的錯誤消息之外,它似乎正常工作。如何指定啓動作業將運行的目錄?

PowerShell從哪裏獲取啓動作業的目錄?它使用的位置是我的默認Windows「文檔」目錄。我的組織不允許使用本地磁盤上的「我的文檔」目錄。

我可以指定Start-Job應該運行的初始目錄嗎?如果是這樣,怎麼樣?

PS C:\src\powershell> Get-Content .\sayhi.bat 
SET EXITCODE=0 
ECHO hi 
EXIT /B %EXITCODE% 

PS C:\src\powershell> Start-Job -ScriptBlock {& "C:\Windows\System32\cmd.exe" "/C", "C:\src\powershell\sayhi.bat"} 

Id  Name   PSJobTypeName State   HasMoreData  Location    Command 
--  ----   ------------- -----   -----------  --------    ------- 
1  Job1   BackgroundJob Running  True   localhost   & "C:\Windows\System32... 


PS C:\src\powershell> Get-Job 

Id  Name   PSJobTypeName State   HasMoreData  Location    Command 
--  ----   ------------- -----   -----------  --------    ------- 
1  Job1   BackgroundJob Completed  True   localhost   & "C:\Windows\System32... 

PS C:\src\powershell> Receive-Job -Id 1 -Keep 

20:15:27.33 C:\Windows 
C:>SET EXITCODE=0 

20:15:27.33 C:\Windows 
C:>ECHO hi 
hi 

20:15:27.35 C:\Windows 
C:>EXIT /B 0 
'\\AHOST\USERS\pwatson\My Documents' 
    + CategoryInfo   : NotSpecified: ('\\AHOST\USERS\pwatson\My Documents':String) [], RemoteException 
    + FullyQualifiedErrorId : NativeCommandError 
    + PSComputerName  : localhost 

CMD.EXE was started with the above path as the current directory. 
UNC paths are not supported. Defaulting to Windows directory. 

回答

0

您可以更改初始目錄中傳遞給-InitializationScript參數ScriptBlock ...

Start-Job ` 
    -InitializationScript { Set-Location $Env:TEMP } ` 
    -ScriptBlock { & "C:\Windows\System32\cmd.exe" "/C", "C:\src\powershell\sayhi.bat" } 

...或者你打電話給你的批處理文件中只是前ScriptBlock你已經使用...

Start-Job -ScriptBlock { 
    Set-Location $Env:TEMP; 
    & "C:\Windows\System32\cmd.exe" "/C", "C:\src\powershell\sayhi.bat" 
} 
相關問題