stringpowershellcompareinvokewebrequest

In PowerShell how to compare Invoke-WebRequest content to a string


In my web page I create simple php script that on browser displays only my IP address as simple text in web page.

So if I use this command in PowerShell:

$ip = Invoke-WebRequest https://www.mypage.com
$ip

I get this result:

PS C:\Users\user> $ip
193.60.50.55

If I check what kind of variable is with: GetType().FullName I get:

PS C:\Users\user> $ip.GetType().FullName
System.String

And If I try to compare it with same string

PS C:\Users\user> $ip = Invoke-WebRequest https://www.mypage.com
$ip2 = "193.60.50.55"
$ip -eq $ip2

I get result "False", I also try with -match and -like but result is always false

Any Idea what is wrong


Solution

  • As Mike Garuccio points Invoke-WebRequest returns object. You're seeing string because you've probably somehow triggered silent type conversion (using quotes, or having $ip declared as [string] before).

    Example:

    $ip = Invoke-WebRequest -Uri http://icanhazip.com/ -UseBasicParsing
    "$ip"
    
    1.2.3.4
    

    -- or --

    [string]$ip = ''
    $ip = Invoke-WebRequest -Uri http://icanhazip.com/ -UseBasicParsing
    $ip
    
    1.2.3.4
    

    This is what you should do:

    # Get responce content as string
    $ip = (Invoke-WebRequest -Uri http://icanhazip.com/ -UseBasicParsing).Content
    
    # Trim newlines and compare
    $ip.Trim() -eq '1.2.3.4'
    

    One-liner:

    (Invoke-WebRequest -Uri http://icanhazip.com/ -UseBasicParsing).Content.Trim() -eq '1.2.3.4'