在 PowerShell 中如何将 Invoke-WebRequest 内容与字符串进行比较

Dan*_*iKR 3 string powershell compare webrequest invoke

在我的网页中,我创建了简单的 php 脚本,该脚本在浏览器上仅将我的 IP 地址显示为网页中的简单文本。

因此,如果我在 PowerShell 中使用此命令:

$ip = Invoke-WebRequest https://www.mypage.com
$ip
Run Code Online (Sandbox Code Playgroud)

我得到这个结果:

PS C:\Users\user> $ip
193.60.50.55
Run Code Online (Sandbox Code Playgroud)

如果我检查变量类型: GetType().FullName 我得到:

PS C:\Users\user> $ip.GetType().FullName
System.String
Run Code Online (Sandbox Code Playgroud)

如果我尝试将它与相同的字符串进行比较

PS C:\Users\user> $ip = Invoke-WebRequest https://www.mypage.com
$ip2 = "193.60.50.55"
$ip -eq $ip2
Run Code Online (Sandbox Code Playgroud)

我得到结果“False”,我也尝试使用 -match 和 -like 但结果总是 false

任何想法出了什么问题

bea*_*ker 5

由于 Mike Garuccio Invoke-WebRequest返回对象。您看到字符串是因为您可能以某种方式触发了静默类型转换(使用引号,或$ip像以前一样声明[string])。

例子:

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

1.2.3.4
Run Code Online (Sandbox Code Playgroud)

- 或者 -

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

1.2.3.4
Run Code Online (Sandbox Code Playgroud)

这是你应该做的:

# 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'
Run Code Online (Sandbox Code Playgroud)

单线:

(Invoke-WebRequest -Uri http://icanhazip.com/ -UseBasicParsing).Content.Trim() -eq '1.2.3.4'
Run Code Online (Sandbox Code Playgroud)