我有一个要执行的脚本。如果我分别运行每条线,则效果很好。但是,如果我将其放在函数中,或者与PowerGUI或Powershell ISE一起运行,则会出错。问题在于脚本没有更改工作目录,因此找不到Invoke-Command正在调用的文件。

$DLUpdate = New-PSSession -ComputerName msmsgex10wprd03 -Credential $DLUpdateCred -Name DLUpdate

Enter-PSSession -Session $DLUpdate

$UpdateDLPath = 'c:\users\mascott2\Desktop\Distrolist\Updates\'

Set-Location $UpdateDLPath

Invoke-Command -ScriptBlock {cmd.exe "/c updatedls.bat"}

Exit-PSSession

Remove-PSSession -Name DLUpdate

最佳答案

您不应该在这样的脚本中使用Enter-PSSession。将所需的所有命令放入与Invoke-Command一起使用的脚本块中,并在 session 中运行它:

$DLUpdate = New-PSSession -ComputerName msmsgex10wprd03 -Credential $DLUpdateCred -Name DLUpdate

Invoke-Command -Session $DLUPdate -ScriptBlock {
    $UpdateDLPath = 'c:\users\mascott2\Desktop\Distrolist\Updates\'
    Set-Location $UpdateDLPath
    cmd.exe "/c updatedls.bat"
}

Remove-PSSession -Name DLUpdate

关于powershell - PSSession不会更改工作目录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32743836/

10-12 05:52