Is there a way to have errors print to your csv file as well as the data you were searching for?
I can get the script to output a csv with the servers that are pingable and get the correct info but the servers that are not pingable receive an error but I cannot get them added to the out-file csv to save my life:| My Script is below:
$machine=Get-Content "<path to file>\slist.txt"
$report=@()
$object=@()
foreach-Object {
if (!(Test-Connection -ComputerName $machine -Count 1)) {
Write-Host "Unable to ping $machine." -fore red
}
else {
$object=Get-WmiObject Win32_OperatingSystem
-ComputerName $machine | select csname,
@{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}
$report += $object
}
$report | Out-File -FilePath .\output.csv -Append
}
Answers (1)
Top Answer
Sure- definitely possible. This script will include a status online/offline for each machine.
A few things from yours you need to fix:
A) Foreach-Object expects pipeline input, which you have none. Use a for-loop instead.
B) You are evaluating Test-NetConnection, which expects a true/false outcome to execute its scriptblock. In order for Test-NetConnection to return a boolean true/false value, you need to append -Quiet.
C) Next, don't use Out-File for CSV. Your headers are getting mangled. Use Export-CSV with -NoTypeInformation.
D) I like to use PSCustomObject for...custom objects :P Doing this, you can remove declaring both $report and $object as an array, as neither are now arrays, nor necessary.
Comments:
-
I made the changes you recommended (thank you!) but I get no output.csv file. I'm exporting to the same dir as I'm running the script from but nothing. Here are my changes:
$machine=Get-Content "<path to script>\slist.txt"
foreach ($machine in $machines) {
if (!(Test-Connection -ComputerName $machine -Count 1 -Quiet)) {
$report = [PSCustomObject]@{
'Computer Name' = $machine
'Status' = 'Offline'
'Last Boot Time'= $null
}
}
else {
$object=Get-WmiObject Win32_OperatingSystem -ComputerName $machine | select-object csname, @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}
$report = [PSCustomObject]@{
'Computer Name' = $machine
'Status' = 'Online'
'Last Boot Time'= $object.LastBootUpTime
}
}
$report | Export-Csv "<path to script>\output.csv" -Append -NoTypeInformation
} - milo2 5 years ago-
$machine=Get-Content "<path to script>\slist.txt"
Make this $Machines, not $Machine. Your forloop is empty. - isudothings 5 years ago-
My bad, I didn't even notice I did that. Works like a charm now, thanks a ton! I've been working on this for a lil over a week now (yes, I'm a newbert)! - milo2 5 years ago