Bootstrap FreeKB - PowerShell - Run Commands on Remote Server using Invoke-Command
PowerShell - Run Commands on Remote Server using Invoke-Command

Updated:   |  PowerShell articles

Invoke-Command can be used to run one or more commands on a remote system. In this example, the Test-Path command will be run on server1.example.com.

Invoke-Command -computername server1.example.com -credential JohnDoe -command { Test-Path -Path 'C:\Temp' }

 

When running the command, there should be a pop-up that asks for your password.

 

If you are ok with storing username and password in the PowerShell script, you could do something like this, and then you won't be prompted for your password.

$password = ConvertTo-SecureString "SuperSecretPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("JohnDoe", $password )

Invoke-Command -computername server1.example.com -credential $cred -command {the-command}

 

And you can issue more than one command.

$password = ConvertTo-SecureString "SuperSecretPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("JohnDoe", $password )

Invoke-Command -computername server1.example.com -credential $cred -command {
    Test-Path -Path 'C:\Temp'
    Test-Path -Path 'C:\Temp\foo.txt'
    Test-Path -Path 'C:\Temp\bar.txt'
}

 

Sometimes it makes sense to first use New-PSSession to establish the connection to the remote server, then use -Session in the Invoke-Command, and end with Remove-Session.

try {
    $pssession = New-PSSession -ComputerName server1.example.com -Credential JohnDoe -ErrorAction Stop
}
catch {
    Write-Warning "Failed to connect to $server with ID $xid - Got the following Exception:"
    Write-Warning $Error[0]
    exit
}

Invoke-Command -Session $pssession -command {
    Test-Path -Path 'C:\Temp'
    Test-Path -Path 'C:\Temp\foo.txt'
    Test-Path -Path 'C:\Temp\bar.txt'
}

Remove-PSSession -InstanceId $pssession.InstanceId

 

If you create a variable before entering Invoke-Command, and you want to use the variable inside of Invoke-Command, you'll preceded the variable with $Using.

$files = @( 'foo.txt', 'bar.txt' )

Invoke-Command -computername server1.example.com -credential $cred -command {
    foreach ($file in $Using:files) {
        New-Item -Path 'C:\Temp\$file'
        New-Item -Path 'C:\Temp\$file'
    }
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 8492b1 in the box below so that we can be sure you are a human.