Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 251
Dan Snell Avatar asked Sep 14 '10 00:09

Dan Snell


People also ask

How do you use PSSession in PowerShell?

Use a PSSession to run multiple commands that share data, such as a function or the value of a variable. To run commands in a PSSession, use the Invoke-Command cmdlet. To use the PSSession to interact directly with a remote computer, use the Enter-PSSession cmdlet. For more information, see about_PSSessions.

How do I enable PSSession?

PowerShell remoting is enabled by default on Windows Server platforms. You can use Enable-PSRemoting to enable PowerShell remoting on other supported versions of Windows and to re-enable remoting if it becomes disabled.

What is the difference between what you can do with the commands enter-PSSession and invoke-Command?

The New-PSSession cmdlet creates a persistent session on the computer Server02 and saves the session in the $s variable. The Invoke-Command lines that follow use the Session parameter to run both of the commands in the same session.


1 Answers

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 
like image 113
Keith Hill Avatar answered Sep 27 '22 18:09

Keith Hill