我有一份 ADComputers 列表
$computers = Get-ADComputer -Filter {Name -like "Foo*"}
我想查看那些现在在线并返回 ping 的子集。
$results = @()
foreach ($computer in $computers) {
if (Test-Connection -ComputerName $computer.Name -Count 1 -Quiet) {
$results += $computer
}
}
但是,现在我发现我想要 ADComputer 对象和从 返回的 IPv4Address TestConnection
,因此我想我会再次过滤并将 Computer 与返回的 IPv4Address 一起包装在自定义哈希表中。
$results2 = @()
foreach ($result in $results) {
$ipv4 = Test-Connection -ComputerName $result.Name -Count 1 | Select -ExpandProperty IPv4Address
$results2 += @{Computer=$result; IPv4Address=$ipv4}
}
然后得到我的结果
$results2 | Format-Table Computer.Name, IPv4Address
但是我的结果是空白的
Computer.Name IPv4Address
------------- -----------
(many blank rows follow)
我怎样才能得到我期望的结果?或者说:我是不是选错了方向,还有更简单的方法吗?
答案1
$results = foreach ($c in $computers)
{
$ipv4 = Test-Connection -ComputerName $c.name -count 1 | select -expand IPV4Address
[PSCustomObject]@{ "Computer" = $c.name ; "IPV4" = $($ipv4.IPAddressToString) }
}
您得到这些空行是因为该IPV4Address
属性包含多个属性而不是一个字符串。该IPAddressToString
属性本身包含 IPv4Address
您的输出将保存在$results
如果您希望它们直接输出,只需删除前面的变量即可foreach
我使用了PSCustomObject
,因为我喜欢命名我的属性,如果您想将其更改为hashtable
,请将最后一行代码更改为:
[hashtable]@{ $c = $($ipv4.IPAddressToString) }
答案2
尝试这个...
Clear-Host
(Get-ADComputer -Filter *).Name | %{
If (Test-Connection -ComputerName $_ -Count 1 -ErrorAction SilentlyContinue)
{
Test-Connection -ComputerName $_ -Count 1 `
| Select Address,ProtocolAddress,
@{Name = 'Status';Expression = {'Online'}}
}
Else{$_ | Select @{Name = 'Address';Expression = {$_}},
@{Name = 'ProtocolAddress';Expression = {'NoAddress'}},
@{Name = 'Status';Expression = {'Offline'}}
}} | Format-Table -AutoSize
结果
Address ProtocolAddress Status
------- --------------- ------
DC01 192.168.0.11 Online
EX01 192.168.2.12 Online
...
WS01 NoAddress Offline
IIS01 192.168.7.11 Online
...
或者这是另一种方法来实现你想要的效果
Clear-Host
(Get-ADComputer -Filter *).Name | %{
If (Test-Connection -ComputerName $_ -Count 1 -ErrorAction SilentlyContinue)
{Resolve-DnsName -Name $_ -Type A `
| Select Name,IPaddress,@{Name = 'Status';Expression = {'Online'}}}
Else{
Resolve-DnsName -Name $_ -Type A -ErrorAction SilentlyContinue `
| Select Name,IPaddress,@{Name = 'Status';Expression = {'Offline'}}
}}
结果
Name IPAddress Status
---- --------- ------
DC01.contoso.com 192.168.0.11 Online
EX01.contoso.com 192.168.2.12 Online
...
WS01.contoso.com 192.168.8.30 Offline
IIS01.contoso.com 192.168.7.11 Online
...
答案3
我有一个用于此确切任务的 PowerShell 脚本:
$computers = Get-Content "ListOfWrkStns_Jan18.txt"
foreach ($computer in $computers) {
if (test-Connection -ComputerName $computer -Count 2 -Quiet ) {
"$computer is up."
} else
{"$computer is DOWN!"
}
}
您只需要创建一个“ListOfWrkStns.txt”(工作站列表)文件来输入所有机器名称。