如何指定Start-Job将运行的目录?

时间:2016-09-28 01:27:55

标签: powershell

这项工作的理想结果是将一个简单的.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.

1 个答案:

答案 0 :(得分:0)

您可以更改ScriptBlock传递给-InitializationScript参数的初始目录...

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"
}