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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With