The Invoke-Command is a very powerful way to run commands remotely.
When running commands remotely, you are essentially opening a new session on the target computer and outputting the results back to the local console.
In order to run commands remotely, we need to have a list of computers, in a string form. For our examples we'll save that list on a variable $ServerList To populate the variable we can do this:
$ServerList = "Server1", "Server2", "Server3", "Server4"
If the servers are listed on a notepad (one server per line), and saved as "c:\Temp\inventory.txt", we do this:
$ServerList= Get-Content -Path "c:\Temp\inventory.txt"
We will explore four very basic techniques.
- Run a command remotely.
- Run a saved file (script or function) remotely
- Run a locally defined function remotely
- Run successive commands remotely.
If we need to display the Event Viewer and see the last 10 event for system
invoke-command -ComputerName $ServerList -ScriptBlock {Get-EventLog -LogName System -Newest 10}
If we have a file, let's say C:\PS\Get-SQLParam.ps1, and we need to run it remotely, even if the remote servers can't access your local C:\ drive (in other words, you don't need to save it on a share) we do the following:
invoke-command -ComputerName $ServerList -FilePath c:\PS\Get-SQLParam.ps1
If we have a function, Get-WhoInstalledSQL, already dot-sourced on our console, and we need to run it remotely:
invoke-command -ComputerName $ServerList -ScriptBlock ${Function:\Get-SQLParam}
If we have a series of commands to run remotely, you can get crafty with "one liners" or put them on a file… or you can open a new session, a persisted one, like this:
$s = New-PSSession -ComputerName Server01, Server02, Server03 Invoke-Command -Session $s -ScriptBlock {$p = Get-Process PowerShell} Invoke-Command -Session $s -ScriptBlock {$p.VirtualMemorySize}