我试图从30多行原始代码中压缩PS脚本,使用数组缩小到少数。我的原始脚本有大约30多个(功能)代码行来检查各种网站的状态,如下所示:
$icelb = Invoke-WebRequest -Uri https://interchange.ctdssmap.com/Connecticut/
后面是报告给控制台的状态:
if ($icelb.StatusDescription -ne "OK") {
Write-Host -BackgroundColor Black -ForegroundColor Red "Interchange Load Balancer Results: FAILED"
}
}
正如你可以想象的那样,经过30多行后,剧本的运作速度相当缓慢,至少可以说。所以我正在使用URL的数组,就像这样($websites
变量包含要测试的所有URL的数组):
$websites | ForEach-Object {
Invoke-WebRequest -Uri $_ | select $_.StatusDescription
if ($_.StatusDescription -ne "OK") {
Write-Host -BackgroundColor Black -ForegroundColor Red "'$_': FAILED"
} else {
Write-Host -BackgroundColor Black -ForegroundColor Green "'$_': " $_.StatusDescription
}
}
我的问题出在脚本的报告阶段。我无法获得if
声明以正确识别并报告正确的状态。我反复获得的唯一一件事是"' $ _':FAILED",即使状态描述是"好的"。
我刚刚注意到变量$_.StatusDescription
为空,这可能会导致问题,但我无法获得正确的语法,让if
语句正确评估它。< / p>
答案 0 :(得分:-1)
&#34;当前对象&#34;变量并不像你期望的那样工作。在一份声明中
Invoke-WebRequest -Uri $_ | select $_.StatusDescription
$_
的两个次出现都在解析时扩展,因此在执行时,该语句实际上如下所示:
Invoke-WebRequest -Uri 'https://example.com/foo/bar' | select 'https://example.com/foo/bar'.StatusDescription
要使代码正常工作,只需展开属性StatusDescription
,将值赋给变量,并在if
语句中使用该变量:
$websites | ForEach-Object {
$status = Invoke-WebRequest -Uri $_ |
Select-Object -Expand StatusDescription
if ($status -ne "OK") {
Write-Host -BackgroundColor Black -ForegroundColor Red "'$_': FAILED"
} else {
Write-Host -BackgroundColor Black -ForegroundColor Green "'$_': $status"
}
}