Test-Connection question

This topic contains 1 reply, has 2 voices, and was last updated by  Don Jones 3 years, 1 month ago.

  • Author
  • #22436

    Daniel Brooks

    I have this script that allows you to enter a ComputerName into the field, and it pings it and tells you if it's online or offline and if it's online, what the IP Address is. I would also like the option where I can enter an IP address and it'll return the Computer name. I've got all the parts created, I just need help on only returning the Computername if the IP is entered, and vice versa. I know "OR" isn't a valid statement here, but I just added it to show what I'm trying to accomplish.

    Basically, I want it to do this:

    If an IP address is entered for $IPorComputerName, return the computername.
    If Computername is entered for $IPorComputerName, return the IP address.
    If no connection of either can be made, write that it's offline.


    Start-Process powershell -Verb runAs background

    $EnterComputerName = Read-Host 'Enter ComputerName or IP Address'

    $IPaddress = (Resolve-DnsName $EnterComputerName A )[0].IPAddress
    $PCName = (Resolve-DnsName $EnterComputerName )[0].namehost

    If ((Test-Connection -ComputerName $EnterComputerName -quiet -Count 1))

    Write-Host -foregroundcolor Green "It's online! Computer Name: $PCName"



    If ((Test-Connection -ComputerName $EnterComputerName -quiet -Count 1))

    Write-Host -foregroundcolor Green "It's online! IP Address: $IPAddress"


    write-host -foregroundcolor -quiet Red "$EnterComputerName is offline 🙁 "


  • #22438

    Don Jones

    So, the right way to do this is with a parameter block.

    if ($PSBoundParameters.ContainsKey('IPAddress')) {
      # specified IP address
    } else {
      # specified Computer Name

    PowerShell will only allow one or the other this way, and you can respond differently based on what was specified.

    ./myscript.txt SERVER # Assumes computer name since it's default
    ./myscript.txt -ComputerName SERVER # computer name also
    ./myscript.txt -IPAddress # IP Address

    I won't get into how awful it is to be using Write-Host as your output. I'm going to give you the benefit of the doubt and assume that the colored output is 100% mission-critical and that you hate puppies.

You must be logged in to reply to this topic.