Reputation: 11
I am trying to export the result of the powershell to csv with $server as the first column and online/offline as the second column. There are many column i want to define actually. I think this is a good start. Please let me know how to achieve this.
$ErrorActionPreference = 'SilentlyContinue'
$ServerName = "TDL498", "TDL498123", "TDL498456"
foreach ($Server in $ServerName)
{
if (test-Connection -ComputerName $Server -Count 2 -Quiet)
{
write-Host "$Server Online" -ForegroundColor Green
}
else
{
Write-Host "$Server Offline"
}
}
Upvotes: 0
Views: 143
Reputation: 7489
you can do that by making a PSCustomObject. [grin] as far as i can tell, there is no need to set any special error handling with the Test-Connection
cmdlet since it returns a False/True
for connection tests with the -Quiet
parameter.
$ComputerNameList = @(
'LocalHost'
'10.0.0.1'
'127.0.0.1'
'BetterNotBeThere'
$env:COMPUTERNAME
)
$Results = foreach ($CNL_Item in $ComputerNameList)
{
[PSCustomObject]@{
ComputerName = $CNL_Item
Online = Test-Connection -ComputerName $CNL_Item -Count 1 -Quiet
}
}
# on screen
$Results
# to csv file
$Results |
Export-Csv -LiteralPath "$env:TEMP\MuhammadSuhailAsrulsani_ComputerStatus.csv" -NoTypeInformation
output to screen ...
ComputerName Online
------------ ------
LocalHost True
10.0.0.1 False
127.0.0.1 True
BetterNotBeThere False
[MySysName] True
CSV file content ...
"ComputerName","Online"
"LocalHost","True"
"10.0.0.1","False"
"127.0.0.1","True"
"BetterNotBeThere","False"
"[MySysName]","True"
Upvotes: 1