Test-Connection question

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

  • Author
    Posts
  • #22436
    Profile photo of Daniel Brooks
    Daniel Brooks
    Participant

    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.

    `
    —-
    ####ENTER COMPUTERNAME SCRIPT#####

    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"

    }

    or

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

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

    }

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

    `

  • #22438
    Profile photo of Don Jones
    Don Jones
    Keymaster

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

    [CmdletBinding(DefaultParameterSetName='ComputerName')]
    Param(
      [Parameter(ParameterSetName='IPAddress')][string]$IPAddress,
      [Parameter(ParameterSetName='ComputerName')][string]$ComputerName
    )
    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 192.168.3.2 # 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.