[英]Mass test-connection powershell
好吧,我在PowerShell中的Test-Connection
函數有問題。 我有一個csv文件,其列Server name
和IPAddress
。 我需要使用信息服務器名稱 IPAddress Result創建連接報告。 如何添加有關列服務器名稱的信息?
我當前的代碼如下:
$Report = @()
$Servers = Import-CSV "C:\skrypt\bobi\servers.csv" -Delimiter ';'
foreach ($Server in $Servers) {
if ($Alive = Test-Connection -ComputerName $Server.IPAddress -Count 1 -quiet) {
$TestResult = New-Object psobject -Property @{
IPAddress = $Server.IPAddress
Result = "Online"
}
}
else {
$TestResult = New-Object psobject -Property @{
IPAddress = $Server.IPAddress
Result = "Offline"
}
}
$Report += $TestResult
}
$Report | Select-Object IPAddress, Result | Export-Csv C:\skrypt\bobi\Report.csv -nti
我認為這可能對您有幫助:
$Servers = @(
[PSCustomObject]@{
'Server Name' = 'Server1'
IPAddress = '10.10.10.10'
}
[PSCustomObject]@{
'Server Name' = 'Wrong'
IPAddress = '10.10.10.999'
}
[PSCustomObject]@{
'Server Name' = 'Server2'
IPAddress = '10.10.10.15'
}
)
$Report = foreach ($Server in $Servers) {
# First we collect all details we know in an object
$Result = [PSCustomObject]@{
Name = $Server.'Server Name'
IP = $Server.IPAddress
Online = $false
}
# Then we do the test
if (Test-Connection -ComputerName $Server.IPAddress -Count 1 -Quiet) {
# If the connection is successful, we set it to True
$Result.Online = $true
}
# As a last step we return the complete object
# where it is collected in the array of Report
$Result
}
$Report | Select-Object Name, IP, Online
如果您的CSV文件包含帶有主機名的列,則需要將PSCustomObject
更改為:
$TestResult = New-Object psobject -Property @{
IPAddress = $Server.IPAddress
HostName = $Server.HostName #assuming column name is "HostName"
Result = "Result"
}
如果您的CSV文件中沒有帶有主機名的列,則需要使用其GetHostByAddress
方法請求System.Net.Dns
類。 像這樣:
$TestResult = New-Object psobject -Property @{
IPAddress = $Server.IPAddress
HostName = $([System.Net.Dns]::GetHostByAddress($Server.HostName).HostName -join ';')
Result = "Result"
}
在這兩種情況下,您都需要使用管道的HostName屬性來導出csv文件
$Report | Select-Object IPAddress, HostName, Result | Export-Csv C:\skrypt\bobi\Report.csv -nti
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.