One of the really powerful features of PowerShell is the ability to run commands remotely. I used this when I wanted to loop through my test servers from the build machine and run my MSI installs.
The following script loops through an array of machines and returns a list of .log files under the C:\Windows folder. One thing to note. The remote session doesn't have access to any of the local script variables, so we pass them as parameters using the -Args argument of the Invoke-Command cmdlet, receiving them using the param statement inside the remote script block.
$AgentServers = @("MYSERVER1", "MYSERVER2");
ForEach ($AgentServer in $AgentServers) {
$Session = New-PSSession -ComputerName $AgentServer;
$FilePattern = "*.log";
$Arguments = $FilePattern
Invoke-Command -Session $Session -Args $Arguments -Script {
param($FilePattern)
Set-Location "C:\Windows"
Get-ChildItem -Include $FilePattern -Recurse
}
Remove-PSSession -Session $Session
}
Now the first time you run the remote script above, it may well fail. Why? Because you forgot to enable remoting on the target machine. On each machine you want to run remote sessions on you’ll have to run:
Enable-PSRemoting
Note that you’ll have to start PowerShell as administrator to perform this.
Also take note that we’re killing each session using Remove-PSSession when we’re done with it as there is a 5 session limit on each remote server and it’s pretty easy to hit that if you forget to close out prior ones.
On that note, there’s a quick trick on clearing out all those orphaned sessions:
Get-PSSession | Remove-PSSession
Get-PSSession will return a list of all open session objects, piping them to Remove-PSSession which subsequently closes them out.