Reputation: 2448
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
Upvotes: 3
Views: 6631
Reputation: 3356
This is an alternative from PowerShell 7.4.4
$ip = Invoke-WebRequest "https://checkip.amazonaws.com/" | Select-Object -ExpandProperty Content
Example
Note there is a new-line
at the tail of the content.
PS C:\Users\tong> $ip = Invoke-WebRequest "https://checkip.amazonaws.com/" | Select-Object -ExpandProperty Content
PS C:\Users\tong> $ip.StartsWith("11.11.11.11")
True
PS C:\Users\tong> """$ip"""
"11.11.11.11
"
Upvotes: 0
Reputation: 6920
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'
Upvotes: 5