希望添加netstat功能以获取ADComputer powershell脚本

希望添加netstat功能以获取ADComputer powershell脚本,powershell,networking,active-directory,netstat,Powershell,Networking,Active Directory,Netstat,我使用这个Get-ADComputer脚本来查找特定OU中的机器。现在,我需要在脚本的输出中捕获机器的入站和出站端口。我知道这可以用netstat完成,但我不确定如何在下面的脚本中包含它。如有任何反馈,将不胜感激 # Enter CSV file location $csv = "C:\MyLocation" # Add the target OU in the SearchBase parameter $Computers = Get-ADComputer -Filter * -SearchB

我使用这个Get-ADComputer脚本来查找特定OU中的机器。现在,我需要在脚本的输出中捕获机器的入站和出站端口。我知道这可以用netstat完成,但我不确定如何在下面的脚本中包含它。如有任何反馈,将不胜感激

# Enter CSV file location
$csv = "C:\MyLocation"
# Add the target OU in the SearchBase parameter
$Computers = Get-ADComputer -Filter * -SearchBase "OU=xxx,OU=xx,OU=xx,OU=_xx,DC=xx,DC=xxx,DC=com" | Select Name | Sort-Object Name
$Computers = $Computers.Name
$Headers = "ComputerName,IP Address"
$Headers | Out-File -FilePath $csv -Encoding UTF8
foreach ($computer in $Computers)
{
Write-host "Pinging $Computer"
$Test = Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue -ErrorVariable Err
if ($test -ne $null)
{
    $IP = $Test.IPV4Address.IPAddressToString
    $Output = "$Computer,$IP"
    $Output | Out-File -FilePath $csv -Encoding UTF8 -Append
}
Else
{
    $Output = "$Computer,$Err"
    $output | Out-File -FilePath $csv -Encoding UTF8 -Append
}
cls
}
您可以使用将TCP连接作为PowerShell对象集合返回

$netstat = Get-NetTCPConnection
$listeningPorts = $netstat | where state -eq 'Listen' | select -expand localport -unique
$netstat | where {$_.LocalPort -and $_.RemotePort -and $_.LocalAddress -ne '127.0.0.1'} |
    Select LocalAddress,LocalPort,RemoteAddress,RemotePort,
        @{n='Direction';e={
        if ($_.LocalPort -in $listeningPorts) {
        'Inbound'
        } 
        else { 'Outbound' }
        }
    }

如果要远程运行此操作,只要已启用PSRemoting,则可以利用:


,其中
标准可能需要更改。我的假设是不包括编号为
0
的任何端口或由
127.0.0.1
进行的任何连接。一旦建立了侦听端口,我假设它们仅用于入站连接

$sb = {
$netstat = Get-NetTCPConnection
$listeningPorts = $netstat | where state -eq 'Listen' | select -expand localport -unique
$netstat | where {$_.LocalPort -and $_.RemotePort -and $_.LocalAddress -ne '127.0.0.1'} |
    Select LocalAddress,LocalPort,RemoteAddress,RemotePort,
        @{n='Direction';e={
        if ($_.LocalPort -in $listeningPorts) {
        'Inbound'
        } 
        else { 'Outbound' }
        }
    }
}

Invoke-Command -ComputerName $Computers -Scriptblock $sb