Well, I have problem with Test-Connection
function in PowerShell. I have a csv file with column Server name
and IPAddress
. I need to create connection report with information Server name , IPAddress , Result . How could I add information about column server name?
My current code looks like:
$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
I think this might help you:
$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
In case your CSV file have column with hostnames you would need to change PSCustomObject
to:
$TestResult = New-Object psobject -Property @{
IPAddress = $Server.IPAddress
HostName = $Server.HostName #assuming column name is "HostName"
Result = "Result"
}
In case your CSV file does not have column with hostnames you would need to request System.Net.Dns
class with its GetHostByAddress
method. Like so:
$TestResult = New-Object psobject -Property @{
IPAddress = $Server.IPAddress
HostName = $([System.Net.Dns]::GetHostByAddress($Server.HostName).HostName -join ';')
Result = "Result"
}
In both cases you then will need to pipe HostName property to export csv file
$Report | Select-Object IPAddress, HostName, Result | Export-Csv C:\skrypt\bobi\Report.csv -nti
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.