2017-08-10 84 views
0

我想从30多行原始代码中压缩一个PS脚本,使用数组缩减到少数。我原来的剧本有代码约30+(功能)线,检查各种网站中像这样的状况:后面是被报告给主机的状态PowerShell如果语句没有返回使用数组值的预期结果

$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多行,脚本运行起来相当缓慢,至少可以说。所以我玩弄使用数组的网址,而不是像这样(的$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“,尽管status描述是”OK“。

我刚刚注意到变量$_.StatusDescription是空的,这很可能会导致问题,但我无法获得正确的语法以使if语句正确评估它。

回答

-1

“当前对象”变量不符合您的期望。在一份声明中

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" 
    } 
} 
+0

好吧,当Angsar回答(谢谢!!!!!)我设法让我的代码下降到一行如下: $ websites | ForEach-Object {(write-host“$ _:”(Invoke-WebRequest -Uri $ _ | Select-Object -Expand StatusDescription))} 但是结果仍然给我:https://modellg2.ctdssmap.com/state/lg2 /:@ {StatusDescription = OK} Ansgar关于-Expand开关的提示做到了! https://modellg2.ctdssmap.com/state/lg2/:好吧 谢谢! :) :) – JPM

+0

@downvoter:谨慎解释你认为这个答案错了​​什么? –

+0

嘿Ansgar :)我没有投票呢?据我所知,它接受了答案并批准了它。这很好,完全满足了这个要求。我感谢帮助!完全。也许是别人?检查出来,我立即给它做了绿色检查... (呃,我不能在这里粘贴截图) - 但它仍然标记为绿色检查在我身边? – JPM

相关问题