Sometimes you need a quick and easy way to run powershell commands on multiple remote machines. This script will read a text file or a list of machines, ping them to ensure they are responding so you don’t waste time on offline machines, then run a remote command.
It times out the ping test at 5ms, which is good for local networks. You may need to increase for slow networks. It also does not establish a profile on the remote machine, which speeds up command processing.
$ScriptBlock = {
#Enter code here
Write-Output $env:computername
}
$computers = @('computer1','computer2')
#$computers = Get-Content c:\temp\computers.txt
$computercount = $computers.Count
foreach($computer in $computers){
#First check if its even worth it
$online = Test-Connection $computer -Count 1 -Quiet -TimeToLive 5
if($online){Write-Output "$computer online with $($computercount) remaining to check"}
else{Write-Warning "$computer offline with $($computercount) remaining to check"}
$computercount = $computercount - 1
if($online){
#Uncomment if input is IP addresses
#$ComputerName = $computer | ForEach-Object {([system.net.dns]::GetHostByAddress($_)).hostname}
Write-Output "Found DNS entry $ComputerName for IP $computer"
$session = New-PSSession -ComputerName $ComputerName -SessionOption (New-PSSessionOption -NoMachineProfile)
$result = Invoke-Command -session $session -ScriptBlock $ScriptBlock
Write-Output $result
Remove-PSSession $session
}
else #not online
{
}
}
You can comment out the list of names and uncomment the text file to have it read a text file with a list of machine names.
You can uncomment the line that converts an IP address into a name if the input is IP addresses, since powershell won’t let you run against an IP address remotely.
This is also easy to convert into a function, which I’ll add when I have some more time later.