tags:

views:

24

answers:

1

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  A: 

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
Keith Hill
Thanks Keith - I will give this a look tomorrow when I get back to the office.
Dan Snell
That appears to do the trick. One thing is the last line needs to be Remove-PSSession $s
Dan Snell
Thanks, I updated the answer.
Keith Hill