0

我正在编写一个 powershell 脚本来 ping 所有服务器并检查哪些服务器处于脱机状态。但我有一个错误。顾名思义,它完美地工作。但是,当我使用 IP 进行测试连接时,它似乎可以工作,但我无法在哈希列表中输出 IP 的名称。有人可以帮我解决这个问题吗?谢谢!!

System.Collections.Hashtable.keys 在线/可用,这是它输出的。但我想让它说“服务器名称在线/可用”

#Creating IP Array list
$ip_array = @{
Server = [ipaddress] "192.168.1.1"
sws = [ipaddress] "192.168.1.1"
}



Foreach ($ip in $ip_array)
{   
    if((Test-Connection -IPAddress $ip.values.ipaddresstostring -quiet -count 1 ) -eq $false)
    {
        
        write-output("$ip.keys  Is offline/unavailable, please troubleshoot connection, script is terminating")  | Red 
    }
    else
    {
        $ping = $true
        write-output("$ip.keys Is online/available") | Green
    }
}
4

2 回答 2

1

如果您真的打算为此使用 Hashtable,将 IP 地址与计算机名结合起来,请更改为以下内容:

# creating IP Hashtable
$ip_hash = @{
'192.168.1.1' = 'Server1'
'192.168.1.2' = 'Server2'
# etcetera
}
# loop through the hash, key-by-key
foreach ($ip in $ip_hash.Keys) {
    $ping = Test-Connection -ComputerName $ip -Quiet -Count 1 -ErrorAction SilentlyContinue
    if(!$ping) {
        Write-Host "Server $($ip_hash[$ip]) is offline/unavailable, please troubleshoot connection, script is terminating" -ForegroundColor Red
    }
    else {
        Write-Host "Server $($ip_hash[$ip]) is online/available" -ForegroundColor Green
    }
}

输出看起来像:

在此处输入图像描述

哈希中的键必须都具有唯一值

于 2021-10-05T13:54:20.073 回答
1

PowerShell 的默认管道语义(任何可以枚举和解开的集合都将是)使字典难以使用 - 在任何地方管道它们会导致不相交的键值对列表,字典本身丢失。

出于这个原因,PowerShell 拒绝自动枚举字典,您必须手动获取枚举器才能遍历其中的条目:

foreach($entry in $ip_hash.GetEnumerator()){
  # reference `$entry.Key` or `$entry.Name` for the key (eg. Server)
  # reference `$entry.Value` for the value (eg. 192.168.1.1)
}
于 2021-10-05T13:58:05.560 回答