Reputation: 1124
I'm using the following code to get a list of machines with IP addresses. It prints out the hostname and IP address. If the host is offline, it says "$computername is offline." Here is the code:
$csv = Get-Content TEST_MACHINES.csv
foreach ($computer in $csv)
{
try
{
Test-Connection $computer -Count 1 -ErrorAction Stop | Select Address, IPV4Address
}
catch
{
"$computer is offline"
}
}
It works great and outputs the data like so:
Address IPV4Address
------- -----------
TESTMACHINE 192.168.1.1
TESTMACHINE2 192.168.1.2
TESTMACHINE3 is offline.
However no amount of trickery is allowing me to write all of this to a file, even though it's displaying like that in the console. It writes to a blank file or only writes the exception.
How can I capture this output exactly as it is?
Upvotes: 2
Views: 6158
Reputation: 46
You can create a custom powershell object using the same field names as the test-connection fields you are selecting and then export both success and failure to CSV. See below for an example:
$csv = Get-Content TEST_MACHINES.csv
foreach ($computer in $csv)
{
try
{
Test-Connection $computer -Count 1 -ErrorAction Stop | Select Address, IPV4Address | Export-Csv -Path .\ConnectionTest.csv -Append
}
catch
{
$Output = New-Object PSObject -Property @{
Address = $computer
IPV4Address = "Offline"
}
$Output | Export-Csv -Path .\ConnectionTest.csv -Append
}
}
Upvotes: 3
Reputation: 202032
Try this:
$csv = Get-Content TEST_MACHINES.csv
'' > foo.log
foreach ($computer in $csv)
{
try
{
Test-Connection $computer -Count 1 -ErrorAction Stop | Select Address, IPV4Address >> foo.log
}
catch
{
"$computer is offline" >> foo.log
}
}
Upvotes: 1
Reputation: 799
In my style of writing scripts I'd use simple if..then..else loop. It seems most logical to me. You did try the "Out-File" switch after pipe, didn't you?... I have just run the below on localhost and some random name, and that worked just fine...
$csv = Get-Content TEST_MACHINES.csv
foreach ($computer in $csv)
{
if (Test-Connection $computer -Count 1 -Quiet)
{
Test-Connection $computer -Count 1 -ErrorAction Stop | Select Address, IPV4Address | Out-file -append "SomeFile.txt"
}
else
{
"$computer is offline" | Out-File -Append "SomeFile.txt"
}
}
Upvotes: 1