Ping Script help

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Don Jones Don Jones 1 year, 6 months ago.

  • Author
  • #24246
    Profile photo of Robbie Boland
    Robbie Boland

    Good morning, I was trying to write a script that will get computer names and then would ping them to check if they are online.

    #This script will get a list of names for all the computers in that room
    $comps=Get-ADComputer -filter 'name -like "Building*roomnumber*"' | Select-Object -property name
    foreach ($comp in $comps){
    ping $comp}

    When I run the above, I get:
    Ping request could not find host @{name=COMPNAME} Please check the name and try again. I thought it might just be ping, so i tried the Test-Connection cmdlet, but I get the same sort of problem.

    How do I get a list of the computer names that will pipe into ping or test-connection so that I can see if the computers are online?

  • #24247
    Profile photo of Don Jones
    Don Jones

    First of all, you've got a logic error. Get-ADComputer produces objects of the type ADComputer; Select-Object is therefore producing "Selected" objects of that type. Those objects have a Name property, which contains a string. Ping.exe has no clue what to do with that, and PowerShell is likely producing a string representation like "@{name=COMPNAME}" which is why you're seeing what you are.

    In Select-Object, use -ExpandProperty instead of -Property. That will "extract" the string computer name value from the property, producing a simple string. "The Big Book of PowerShell Gotchas" has a bit on this, I think, and I go into it pretty well in [i]Learn PowerShell in a Month of Lunches[/i]. Understanding the difference between [i]an object that has a property which contains a string[/i], and [i]a string by itself[/i], is a massively important concept in PowerShell.

    Ping is probably not as easy to use as Test-Connection. But, look at the -Quiet parameter of Test-Connection, which makes it return just a True/False rather than a status.

    if ((Test-Connection $comp -quiet)) { 
      # comp is pingable
    } else {
      # comp is not pingable

You must be logged in to reply to this topic.