【问题标题】:In PowerShell how to compare Invoke-WebRequest content to a string在 PowerShell 中如何将 Invoke-WebRequest 内容与字符串进行比较
【发布时间】:2017-03-28 16:44:06
【问题描述】:

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

所以如果我在 PowerShell 中使用这个命令:

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

我得到这个结果:

PS C:\Users\user> $ip
193.60.50.55

如果我检查使用哪种变量:GetType().FullName 我得到:

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

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

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

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

知道什么是错的

【问题讨论】:

  • 我有点困惑$ip = Invoke-WebRequest https://www.mypage.com 只返回一个字符串,它应该返回一个具有大量属性的对象,你能发布$ip | Get-Member 的结果吗?

标签: string powershell compare invoke webrequest


【解决方案1】:

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

例子:

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

1.2.3.4

-- 或--

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

1.2.3.4

这是你应该做的:

# 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'

单线:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    相关资源
    最近更新 更多