我写了几行代码来检查端口是否打开:
$ports = @(5353,5672,8080,4443,15672,9200)
foreach ($port in $ports)
{
TNC -ComputerName localhost -Port $port -InformationLevel Quiet -WarningAction SilentlyContinue | Tee-Object -Variable CheckPortStatus > $null
if ($CheckPortStatus -eq "True")
{$status = Write-Host "Open" -ForegroundColor GREEN}
else
{$status = Write-Host "close" -ForegroundColor RED}
echo "the port is $status"
我不明白为什么输出是这样的:
脚本实际上有效,但它在声明时执行变量,然后在if/else
答案 0 :(得分:3)
Write-Host
cmdlet 打印某些内容到控制台,不会返回任何内容,因此您无法将其分配给$status
。相反,你应该做这样的事情:
$ports = @(5353,5672,8080,4443,15672,9200)
foreach ($port in $ports)
{
TNC -ComputerName localhost -Port $port -InformationLevel Quiet -WarningAction SilentlyContinue | Tee-Object -Variable CheckPortStatus > $null
if ($CheckPortStatus -eq "True")
{
$status = "Open"
Write-Host $status -ForegroundColor GREEN
}
else
{
$status = "Closed"
Write-Host $status -ForegroundColor RED
}
Write-Host "the port is $status"
}
当您编写或查看PowerShell脚本时,我希望您这样做 请记住以下经验法则:
使用Write-Host几乎总是错误的。