Reputation: 31
I created a simple PowerShell script to log into a remote computer and then execute a command but the command does not execute. The command is "cd C:". Here is the script:
#Script to do an RDP to a remote server
Enable-PSRemoting -Force
$password = ConvertTo-SecureString "xxxxxxxxx" -AsPlainText -Force $username = "NE\a_chermes2" $Cred = New-Object System.Management.Automation.PSCredential ($username, $password)
Enter-PSSession -ComputerName NESCH11 -Credential $cred
Invoke-Command -ScriptBlock {cd C:}
Upvotes: 0
Views: 83
Reputation: 1190
You enter into a remote session, you have no need to use Invoke-Command
here, and this do not execute because of the double hop restriction. Despite you can add more code to allow it, this is not useful here.
Moreover, Enter-PSSession -ComputerName NESCH11 -Credential $cred
will be running separately than the rest of the script. This mean that cd C:\
will be executed on your local machine - just like all other commands after it.
Use Invoke-Command
instead:
Enable-PSRemoting -Force
$password = ConvertTo-SecureString "xxxxxxxxx" -AsPlainText -Force $username = "NE\a_chermes2" $Cred = New-Object System.Management.Automation.PSCredential ($username, $password)
Invoke-Command -ComputerName NESCH11 -Credential $cred -ScriptBlock {cd C:}
Of course, this will not do anything noticeable since all is done remotely and you only change the directory location. Try Get-ChildItem C:
instead of cd C:
. This syntax allow you to collect data remotely :
$dirList = Invoke-Command -ComputerName NESCH11 -Credential $cred -ScriptBlock {gci C:}
Upvotes: 1