I'm having trouble exporting this basic net-connection test into the Export-Excel (import-Excel) feature. I need to export the results of a net-connection test from the array that was created.
Each CSV serverlist has 2 columns server name and port
Here is the code:
Import-Csv -Path .\serverlist.csv -Delimiter "," | ForEach-Object {$_.servers
$status = Test-NetConnection -ComputerName $_.servers -Port $_.port
if ($status.TcpTestSucceeded -eq $True) {
$result = "ONLINE"
$onlineCount ++ }
elseif ($status.TcpTestSucceeded -eq $false) {
$result = "OFFLINE"
$offlineCount ++ }
else {
$result = "ERROR"
}
$result = [PSCustomObject]@{
ComputerName = $status.ComputerName
Port = $status.RemotePort
Status = $result
Date = Get-Date -Format "dd/MM/yyyy"
Time = Get-Date -Format "HH:mm"
}
} $result | Export-Excel -Path ".\netStatus.xlsx" -AutoSize -AutoFilter -WorksheetName Net_Test
ii ".\netStatus.xlsx"
This is the Excel result. See there is only one column with addresses. I want : ComputerName, Port, Status, Date, Time
I wanted the $result array to show in excel similar to this:
I also get this error:



I think your issue is related to where the final $result is listed. Re-created your script and even without outputting to Excel (so just to screen) if I have it as
I get that same error. but if I change it to
then it runs fine... except it doesn't do what you're after as it will only outout the last result as you're calling it from outside the ForEach loop. So it actually needs to be
So each iteration of the ForEach-Object loop it will output / export the results of that command.
The following code with my suggested changes mentioned above works and does what you're looking for.
Only difference is I've outputted to .csv rather than .xlsx as I don't have Excel on this machine to test that part.
but with a serverlist.csv containing
I get an output of