I'm getting an error while using New-PSSesion and Enter-PSSesion together, but they are working seperately. My aim is to copy a file from local server to remote server and afterwards run some commands in remote server
Below is my script:
$Session = New-PSSession -ComputerName "IP_Address" -Credential "domainname\username"
Copy-Item "C:\Users\username\test1.txt" -Destination "C:\Users\username\" -ToSession $Session
Enter-PSSession $Session
Copy-Item "C:\Users\username\" -Destination "C:\Users\username\targetdir\"
...
Exit-PSSession
When I run above script with PowerShellISE, it results in an error:
Copy-Item : Cannot find path 'C:\Users\username\test1.txt' because it does not exist.
At line:4 char:1
+ Copy-Item "C:\Users\username\test1.txt" -Dest ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Users\username\test1.txt:String) [Copy-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
The strange thing is, when I run these from the powershell CLI (not ISE), it works.
What is the reason behind this?
Enter-PSSessionis for interactive use only, for a script you'd useInvoke-CommandinsteadCopy-Itemcommand that causes the problem, which - unlike what you expect - also runs locally.