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

Dan*_*ell 36 powershell powershell-remoting

当我从脚本运行下面的行时,文件最终会在我的本地计算机上创建.

$cred = Get-Credential domain\DanTest
Enter-PSSession -computerName xsappb01 -credential $cred

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

exit-pssession
Run Code Online (Sandbox Code Playgroud)

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

Kei*_*ill 66

不确定是否是时间问题.我怀疑它更像是Enter-PSSession正在调用类似嵌套提示的东西而后续命令没有在其中执行.无论如何,我相信Enter/Exit-PSSession是用于交互式使用 - 而不是脚本使用.对于脚本,使用New-PSSession并将该会话实例传递给Invoke-Command,例如:

$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
Run Code Online (Sandbox Code Playgroud)

  • 值得添加:为了访问在`Invoke-Command`之前声明的变量,你需要使用`-ArgumentList`参数 (3认同)