Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

Enter-PSSession is not working in my Powershell script

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

$cred = Get-Credential domainDanTest
Enter-PSSession -computerName xsappb01 -credential $cred

New-Item -type file c:emplahxsappk02.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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 domainDanTest 
$s = New-PSSession -computerName xsappb01 -credential $cred
Invoke-Command -Session $s -Scriptblock {New-Item -type file c:emplah.txt}
Remove-PSSession $s

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...