Ping an Array of Computers

I have found on occasion the need to ping a list of computers, whether they be in a text file, an array in Powershell, or a CSV file. It turns out building commands as a string and then executing that string as a command in Powershell is not exactly intuitive.

You need to use invoke-expression -command $cmd where $cmd is the string you want to execute.

So, we can do the following, using my New-Array Function

   1: function new-array {$args}
   2: $servers = new-array powershell-dev1 powershell-dev2 powershell-dev3
   3: $servers | foreach-object {invoke-expression -command "ping -n 1 $_"} 

Using invoke-expression -command you can have an executable and arguments and everything just works. There are situations where you will need to use the back tick character " `" to escape characters.

You can use this technique to execute just about any string that you build using Powershell and variables.

Comments (3) -

'powershell-dev1', 'powershell-dev2', 'powershell-dev3' | foreach {ping -n 1 "$_"}

Lunatic Experimentalist,

That's a great tip. I had tried to do | % {"ping -n 1 $_"} and that woudl simply echo out the command for each item in the pipleline. So I tried the following:

“powershell-dev1", "powershell-dev2", "powershell-dev3" | foreach {& "ping -n 1 $_"}

which gives me

The term 'ping -n 1 powershell-dev1' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.

If all you need for your command  is the current object in the pipleline, then this is great.

Thanks again,


For {& "ping -n 1 $_"} to not work is actually a glitch. The ampersand is pseudo aliased to Invoke-Expression, but they behave differently. The ampersand(&) takes its first string argument as a command name, and the rest as parameters for that command. Invoke-Expression, on the other hand, turns its first string argument into a new script block and executes it.

Comments are closed