44

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 Answer 1

84

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
4
  • Thanks Keith - I will give this a look tomorrow when I get back to the office.
    – Dan Snell
    Sep 14, 2010 at 3:30
  • 1
    That appears to do the trick. One thing is the last line needs to be Remove-PSSession $s
    – Dan Snell
    Sep 14, 2010 at 15:47
  • @DanSnell Remove-PSSession always is required when I use New-PSSession and Invoke-Command -Session ?
    – Kiquenet
    May 29, 2013 at 12:36
  • 8
    Worth adding: in order to access variables declared before the Invoke-Command, you need to use the -ArgumentList parameter Jul 31, 2018 at 16:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.