Run-Command.ps1 : Run External Commands with Power!
I was working late tonight and we had to run a bunch of third party EXEs and such. We do this a good bit so I can’t always avoid calling external executables and I also find psexec.exe much easier than any powershell way to run remote commands. That said I find myself constantly writing this.
foreach($server in $servers)
{
Do Something Here Like
psexec \\$server mycmd.exe param1
}
I decided to write a script call Run-Command.ps1.
This will take three parameters
- File (list of servers to process)
- Cmd (Command to run with %S% where you want the server name to be replaced)
- Check (just shows what command would run)
- Will also take Piped Input
Example:
PS> .\Run-Command.ps1 -file c:\serverlist.txt -cmd “psexec \\%S% mycmd.exe Hello World” -check
Run-Command.ps1
Begin{
function Ping-Server {
Param([string]$srv)
$pingresult = Get-WmiObject win32_pingstatus -f "address=’$srv’"
if($pingresult.statuscode -eq 0) {$true} else {$false}
}
$servers = @()
}
Process{
if($_)
{
if($_.ServerName){$servers += $_.ServerName}
else{$servers += $_}
}
}
End{
if($file){Get-Content $file | %{$servers += $_}}
foreach($server in $servers)
{
if(ping-server $server)
{
if($verbose){Write-Host "+ Processing Server $Server"}
$mycmd = $cmd -replace "\%S\%",$Server
if($whatif){Write-Host " - WOULD RUN $mycmd"}
else{if($verbose){Write-Host " - Running $mycmd"};invoke-Expression $mycmd}
}
else
{
Write-Host "+ $Server FAILED PING" -foregroundcolor RED
}
}
}
tshell :: Sep.14.2007 :: HowTo, Powershell, Scripting, functions :: No Comments »

[...] Re: File in use - part 2 You’ll want to try to perhaps ping the computer first before going into your function. Brandon provides some good code here: [link] That should get you going, otherwise let us know. Marco Published Wednesday, October 17, 2007 4:26 AM by microsoft.public.windows.powershell Google Group [...]