使用PowerShell脚本获取远程主机的IP配置信息

  • 代码如下:

[cmdletbinding()] param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$ComputerName = $env:computername )

begin {} process { foreach ($Computer in $ComputerName) { if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) { $Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer | ? {$_.IPEnabled} foreach ($Network in $Networks) { $IPAddress = $Network.IpAddress[0] $SubnetMask = $Network.IPSubnet[0] $DefaultGateway = $Network.DefaultIPGateway $DNSServers = $Network.DNSServerSearchOrder $IsDHCPEnabled = $false If($network.DHCPEnabled) { $IsDHCPEnabled = $true } $MACAddress = $Network.MACAddress $OutputObj = New-Object -Type PSObject $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper() $OutputObj | Add-Member -MemberType NoteProperty -Name IPAddress -Value $IPAddress $OutputObj | Add-Member -MemberType NoteProperty -Name SubnetMask -Value $SubnetMask $OutputObj | Add-Member -MemberType NoteProperty -Name Gateway -Value $DefaultGateway $OutputObj | Add-Member -MemberType NoteProperty -Name IsDHCPEnabled -Value $IsDHCPEnabled $OutputObj | Add-Member -MemberType NoteProperty -Name DNSServers -Value $DNSServers $OutputObj | Add-Member -MemberType NoteProperty -Name MACAddress -Value $MACAddress $OutputObj } } } }

end {}


步骤:

  1. 将上面代码保存为PS1文件。例如: GetIP.ps1

  2. 准备好一个远程主机的列表名文件(TXT文件格式),例如; Computer_List.txt

  3. 在PowerShell下执行下面的任意一个命令:

Get-Content Computer_List.txt | .\GetIP.ps1 | ft -AutoSize

或者

Get-Content Computer_List.txt | .\GetIP.ps1 | ft ComputerName, IPAddress, DNSServers -AutoSize