我試圖查詢從一臺服務器到多臺遠程服務器的埠,但我無法弄清楚。
查詢到一臺服務器 wordks 很好,但我想在 $destination 變數中添加多個遠程服務器,讓腳本回圈遍歷它們,一次性給我所有結果。
我發現的腳本:
$Servers = "127.0.0.1"
$Ports = "80",
"445",
"443"
$Destination = "Computer_1"
$Results = @()
$Results = Invoke-Command $Servers {param($Destination,$Ports)
$Object = New-Object PSCustomObject
$Object | Add-Member -MemberType NoteProperty -Name "ServerName" -Value
$env:COMPUTERNAME
$Object | Add-Member -MemberType NoteProperty -Name "Destination" -Value $Destination
Foreach ($P in $Ports){
$PortCheck = (Test-NetConnection -Port $p -ComputerName $Destination ).TcpTestSucceeded
If($PortCheck -notmatch "True|False"){$PortCheck = "ERROR"}
$Object | Add-Member Noteproperty "$("Port " "$p")" -Value "$($PortCheck)"
}
$Object
} -ArgumentList $Destination,$Ports | select * -ExcludeProperty runspaceid, pscomputername
$Results | Out-GridView -Title "Testing Ports"
$Results | Format-Table -AutoSize
我得到結果:
ServerName Destination Port 80 Port 445 Port 443
---------- ----------- -------- -------- --------
<local host> Computer_1 True True True
我需要在 $destination 塊中添加多個遙控器。我嘗試了以下方法:
$Destination = "Computer_1","Computer_2"
但這不是正確的方法,因為我明白了:
ServerName Destination Port 80 Port 445 Port 443
---------- ----------- -------- -------- --------
<local host> "Computer_1","Computer_2" False False False
我需要得到這個結果:
ServerName Destination Port 80 Port 445 Port 443
---------- ----------- -------- -------- --------
<local host> Computer_1 True True True
<local host> Computer_2 True True True
任何幫助,將不勝感激。
uj5u.com熱心網友回復:
問題是您正在運行 a ForEach()for the $portsbut not $destination。你想做更多這樣的事情:
$Servers = "127.0.0.1"
$Ports = "80",
"445",
"443"
$Destinations = "Computer_1","Computer_2"
$Results = @()
$Results = Invoke-Command $Servers {param($Destinations,$Ports)
ForEach($Destination in Destinations){
$Object = New-Object PSCustomObject
$Object | Add-Member -MemberType NoteProperty -Name "ServerName" -Value $env:COMPUTERNAME
$Object | Add-Member -MemberType NoteProperty -Name "Destination" -Value $Destination
Foreach ($P in $Ports){
$PortCheck = (Test-NetConnection -Port $p -ComputerName $Destination ).TcpTestSucceeded
If($PortCheck -notmatch "True|False"){$PortCheck = "ERROR"}
$Object | Add-Member Noteproperty "$("Port " "$p")" -Value "$($PortCheck)"
}
$Object
}
} -ArgumentList $Destinations,$Ports | select * -ExcludeProperty runspaceid, pscomputername
$Results | Out-GridView -Title "Testing Ports"
$Results | Format-Table -AutoSize
但是,如果您更熟悉 Powershell,那么使用 Pipeline 將結果直接傳遞給 Out-GridView,而不是先將它們全部收集到一個陣列中,會有稍微更整潔的格式化方法。
uj5u.com熱心網友回復:
您在 $Destination 中傳遞多個服務器,因此您需要遍歷它們。相反,您只需將整個 $Destination 添加到 $Object
在偽代碼中,您需要類似的東西
$Results = foreach ($destServer in $ destination) {
Invoke-Command {
{same code you use currently}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/362434.html
