Powershell code to get IP address from a URL

Welcome Forums General PowerShell Q&A Powershell code to get IP address from a URL

This topic contains 4 replies, has 2 voices, and was last updated by

 
Participant
1 year, 11 months ago.

  • Author
    Posts
  • #61234

    Participant
    Points: 1
    Rank: Member

    Hello All,

    My objective is to run a script of a bunch of URL's to get the IP address to export to a spreadsheet. I am new to powershell. If I hardcode the powershell below it works fine:

    $url="www.yahoo.com"
    $Addresses = [System.Net.Dns]::GetHostAddresses("$url")[0].IPAddressToString
    write-host $Addresses

    However, when I try to call the code from a foreach loop

    $testcsv= Get-Content c:\scripts\URLS2.txt

    foreach($url in $testcsv)

    {

    $Addresses = [System.Net.Dns]::GetHostAddresses("$url")[0].IPAddressToString
    write-host $Addresses

    }

    It throws an error as follows:

    Exception calling "GetHostAddresses" with "1" argument(s): "No such host is known"
    At line:8 char:1
    + $Addresses = [System.Net.Dns]::GetHostAddresses("$url")[0].IPAddressToString
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SocketException

    I'm sure the logic I am doing is wrong, any help would be greatly appreciated!

    Happy New Year everyone!

  • #61245

    Keymaster
    Points: 1,673
    Helping HandTeam Member
    Rank: Community Hero

    And what does that .TXT file look like?

    (also, please consider formatting your code – instructions are listed above the posting textbox)

  • #61249

    Keymaster
    Points: 1,673
    Helping HandTeam Member
    Rank: Community Hero

    So, "http://" is not a valid part of a host name. You didn't use that in your first example.

    • #61257

      Participant
      Points: 1
      Rank: Member

      Thanks works appreciate help!

The topic ‘Powershell code to get IP address from a URL’ is closed to new replies.