I have the following "ping script" in which I would like to use an array along with the Export-Csv cmdlet to write the output to a CSV file rather than a txt file.
I first tried piping Write-Output to Export-Csv until reading that you cannot pipe strings to Export-Csv and must convert them into objects first.
I don't quite understand how to work with arrays in PowerShell.
Param(
[Parameter(Mandatory=$true, position=0)][string]$csvfile
)
$ColumnHeader = "Hostname"
Write-Host "Reading file" $csvfile
$ipaddresses = Import-Csv $csvfile | Select-Object $ColumnHeader
Write-Host "Started Pinging.."
foreach ($ip in $ipaddresses) {
if (Test-Connection $ip.("Hostname") -Count 1 -Quiet) {
Write-Output $ip.("Hostname") "Ping succeeded." |
Out-File -FilePath "C:\temp\pingresults.txt" -Append
} else {
Write-Output $ip.("Hostname") "Ping failed." |
Out-File -FilePath "C:\temp\pingresults.txt" -Append
}
}
Write-Host "Pinging Completed."