Enter-PSSession在我的Powershell脚本中不起作用

Enter-PSSession is not working in my Powershell script

当我从脚本中运行以下行时,文件最终在本地计算机上创建。

1
2
3
4
5
6
$cred = Get-Credential domain\\DanTest
Enter-PSSession -computerName xsappb01 -credential $cred

New-Item -type file c:\\temp\\blahxsappk02.txt

exit-pssession

当我从Powershell控制台单独运行每一行时,将正确创建远程会话,并在远程计算机上创建文件。有什么想法吗?脚本可能是时间问题吗?


不确定是否是计时问题。我怀疑这更像是Enter-PSSession正在调用诸如嵌套提示之类的东西,而您的后续命令未在其中执行。无论如何,我相信Enter / Exit-PSSession是供交互使用的,而不是脚本使用的。对于脚本,请使用New-PSSession并将该会话实例传递到Invoke-Command中,例如:

1
2
3
4
$cred = Get-Credential domain\\DanTest
$s = New-PSSession -computerName xsappb01 -credential $cred
Invoke-Command -Session $s -Scriptblock {New-Item -type file c:\\temp\\blah.txt}
Remove-PSSession $s