如何修改此PowerShell脚本将两个部分导出为CSV而不切断任何数据?
问题描述:
我从网上得到了这个脚本。至少我能想出如何将数据导出到CSV。事实证明,这远远超过了我的能力。我试过Export-Csv
和管道,但都没有成功。如何修改此PowerShell脚本将两个部分导出为CSV而不切断任何数据?
我有一个成功的尝试,但所有的数据被推进到1列并切断,-Width
参数也没有解决这一问题。剩下的时间,我只是得到像Length
这样的随机信息,或者看起来像数字和字母混杂在一起的损坏数据。
所有此脚本都会在IP列表上运行ping
和nslookup
。我想把它移到一个CSV文件中,这样我就可以对数据进行排序,找到空的/不再用来清理IP空间的IP,甚至可以识别DNS中的问题。
$InputFile = 'C:\Temp\list.txt'
$addresses = Get-Content $InputFile
$reader = New-Object IO.StreamReader $InputFile
while ($reader.ReadLine() -ne $null) { $TotalIPs++ }
Write-Host ""
Write-Host "Performing nslookup on each address..."
foreach ($address in $addresses) {
## Progress bar
$i++
$percentdone = (($i/$TotalIPs) * 100)
$percentdonerounded = "{0:N0}" -f $percentdone
Write-Progress -Activity "Performing nslookups" -CurrentOperation "Working on IP: $address (IP $i of $TotalIPs)" -Status "$percentdonerounded% complete" -PercentComplete $percentdone
## End progress bar
try {
[System.Net.Dns]::Resolve($address) | Select HostName, AddressList
} catch {
Write-Host "$address was not found. $_" -ForegroundColor Green
}
}
Write-Host ""
Write-Host "Pinging each address..."
foreach($address in $addresses) {
## Progress bar
$j++
$percentdone2 = (($j/$TotalIPs) * 100)
$percentdonerounded2 = "{0:N0}" -f $percentdone2
Write-Progress -Activity "Performing pings" -CurrentOperation "Pinging IP: $address (IP $j of $TotalIPs)" -Status "$percentdonerounded2% complete" -PercentComplete $percentdone2
## End progress bar
if (Test-Connection -ComputerName $address -Count 2 -Quiet) {
Write-Host "$address responded" -ForegroundColor Green
} else {
Write-Warning "$address does not respond to pings"
}
}
Write-Host ""
Write-Host "Done!"
答
简单,再简单...
Get-Content $InputFile | ForEach-Object {
$ip = $_
try {
$dns = [Net.Dns]::Resolve($ip)
} catch {
Write-Host "$address not found.`n$_"
}
New-Object -Type PSObject -Property @{
'Address' = $ip
'Hostname' = $dns.Hostname
'AddressList' = $dns.AddressList
'Online' = [bool](Test-Connection $ip -Count 2 -Quiet)
}
} | Export-Csv 'C:\path\to\output.csv' -NoType
我感谢你的回复。但我不完全理解这个脚本中发生了什么。其中一些我明白,但是...我想我应该玩它,看看会发生什么。 –
你对代码有什么不了解?它从输入文件读取地址,将每个地址解析为一个主机名,并使用主机名,地址和联机状态构建一个自定义对象,并将对象导出为CSV。自定义对象是“Export-Csv”期望的输入。 –
啊我明白了。我对PS并不熟悉。回复较晚,抱歉。非常感谢你。 –