Enter-PSSession is not working in my Powershell script

房东的猫 提交于 2020-01-31 06:07:29

问题


When I run the lines below from a script the file ends up being created on my local machine.

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

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

exit-pssession

When I run each line individually from the powershell console the remote session is created correctly and the file is created on the remote machine. Any thoughts on why? Is it a timing issue is the script perhaps?


回答1:


Not sure if it is a timing issue. I suspect it's more like Enter-PSSession is invoking something like a nested prompt and your subsequent commands are not executing within it. Anyway, I believe Enter/Exit-PSSession is meant for interactive use - not scripting use. For scripts use New-PSSession and pass that session instance into Invoke-Command e.g.:

$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


来源:https://stackoverflow.com/questions/3705321/enter-pssession-is-not-working-in-my-powershell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!