我使用此链接中提供的以下建议: Experts-Exchange
我正在尝试获取服务器(主机名)列表,并将主机名和IP地址保存在.csv文件中。
使用以下Powershell代码,我会在结果窗格中看到每个服务器的主机名但IP地址相同。
$servers = get-content "C:\TEMP\servers.txt"
$serversAndIps = "C:\TEMP\List_of_servers_with_ips.csv"
$results =@()
foreach ($server in $servers) {
$results =@()
$result = "" | Select ServerName , ipaddress
$result.ipaddress = [System.Net.Dns]::GetHostAddresses($server)
foreach($a in $addresses) {
"{0},{1}" -f $server, $a.IPAddressToString
}
$result.servername = $server
$results += $result
}
$results | export-csv -NoTypeInformation $serversandips
当我打开.csv文件时,我明白了:
"ServerName","ipaddress"
"Server_name_1","System.Net.IPAddress[]"
如果我运行此PowerShell脚本,我可以在结果窗格中获取主机名和正确的IP地址。我只需要知道如何将结果传输到.csv文件。
$servers = get-content "C:\TEMP\servers.txt"
foreach ($server in $servers) {
$addresses = [System.Net.Dns]::GetHostAddresses($server)
foreach($a in $addresses) {
"{0},{1}" -f $server, $a.IPAddressToString
}
}
有什么建议吗?
答案 0 :(得分:10)
看起来像是一些简单的拼写错误。
试试这个:
$servers = get-content "X:\servers.txt"
$serversAndIps ="X:\test.csv"
$results = @()
foreach ($server in $servers)
{
$result = "" | Select ServerName , ipaddress
$result.ipaddress = [System.Net.Dns]::GetHostAddresses($server)
$addresses = [System.Net.Dns]::GetHostAddresses($server)
foreach($a in $addresses)
{
"{0},{1}" -f $server, $a.IPAddressToString
$result.ipaddress = [System.Net.Dns]::GetHostAddresses($server)
}
$result.servername = $server
$result.ipaddress = $a.IPAddressToString
$results += $result
}
$results | export-csv -NoTypeInformation $serversandips