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.

Advertisements

4 Responses to “Ping an Array of Computers”

  1. Ping an Array of Computers Says:

    […] Premini wrote an interesting post today onHere’s a quick excerptI 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 … […]

  2. LunaticExperimentalist Says:

    ‘powershell-dev1’, ‘powershell-dev2’, ‘powershell-dev3’ | foreach {ping -n 1 “$_”}

  3. Andy Says:

    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,

    Andy

  4. LunaticExperimentalist Says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: