34
foreach ($computer in $computerlist) {
    if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
    {
        foreach ($file in $REMOVE) {
            Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
            Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"            
        }
    } else {
        Write-Host "\\$computer\$DESTINATION\"
    }
}

I want to export Write-Host "\$computer\$DESTINATION\" to the CSV files so I know which computers were offline when the script ran.

I am running this from a Windows 7 machine

2

4 Answers 4

51

This solution creates a psobject and adds each object to an array, it then creates the csv by piping the contents of the array through Export-CSV.

$results = @()
foreach ($computer in $computerlist) {
    if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
    {
        foreach ($file in $REMOVE) {
            Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
            Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"            
        }
    } else {

        $details = @{            
                Date             = get-date              
                ComputerName     = $Computer                 
                Destination      = $Destination 
        }                           
        $results += New-Object PSObject -Property $details  
    }
}
$results | export-csv -Path c:\temp\so.csv -NoTypeInformation

If you pipe a string object to a csv you will get its length written to the csv, this is because these are properties of the string, See here for more information.

This is why I create a new object first.

Try the following:

write-output "test" | convertto-csv -NoTypeInformation

This will give you:

"Length"
"4"

If you use the Get-Member on Write-Output as follows:

write-output "test" | Get-Member -MemberType Property

You will see that it has one property - 'length':

   TypeName: System.String

Name   MemberType Definition
----   ---------- ----------
Length Property   System.Int32 Length {get;}

This is why Length will be written to the csv file.


Update: Appending a CSV Not the most efficient way if the file gets large...

$csvFileName = "c:\temp\so.csv"
$results = @()
if (Test-Path $csvFileName)
{
    $results += Import-Csv -Path $csvFileName
}
foreach ($computer in $computerlist) {
    if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
    {
        foreach ($file in $REMOVE) {
            Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
            Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"            
        }
    } else {

        $details = @{            
                Date             = get-date              
                ComputerName     = $Computer                 
                Destination      = $Destination 
        }                           
        $results += New-Object PSObject -Property $details  
    }
}
$results | export-csv -Path $csvFileName -NoTypeInformation
6
  • anyway to Append the file instead of overwrite? I tried the -NoClobber flag but didn't seem to help Jan 10, 2014 at 15:29
  • 6
    As a minor improvement, you can use $details = [ordered] @{... This will make sure the columns in the csv file appear in the same order as specified.
    – vmb100
    Jan 10, 2017 at 16:16
  • Export-CSV already has a -Append parameter so you can use it like Export-CSV -Append $path See the docs: learn.microsoft.com/en-us/powershell/module/…
    – Thomas K.
    Feb 28, 2022 at 16:13
  • @ThomasK. It does now, it didn't in 2014 :) Mar 1, 2022 at 8:37
  • @DavidMartin no offense, I just added it if someone stumbles about this topic in the future (such as me)
    – Thomas K.
    Mar 1, 2022 at 10:11
11

simply use the Out-File cmd but DON'T forget to give an encoding type: -Encoding UTF8

so use it so:

$log | Out-File -Append C:\as\whatever.csv -Encoding UTF8

-Append is required if you want to write in the file more then once.

2

what you are searching for is the Export-Csv file.csv

try using Get-Help Export-Csv to see whats possible

also Out-File -FilePath "file.csv" will work

2
  • I tried that already but my file is created with no data.Write-Host "\\$computer\$DESTINATION\" | Export-Csv E:\Code\powershell\logs\offline.txt Jan 10, 2014 at 14:55
  • 5
    Don't use Write-Host. Use Write-Output. Write-Host does not go to the pipe.
    – EBGreen
    Jan 10, 2014 at 15:01
2

You can always use the

echo "Column1`tColumn2`tColumn3..." >> results.csv

You will need to put "`t" between the columns to separates the variables into their own column. Here is the way I wrote my script:

echo "Host`tState" >> results.csv
$names = Get-Content "hostlist.txt"
foreach ($name in $names) {
    $count = 0
    $count2 = 13490

    if ( Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue ) {
        echo "$name`tUp" >> results.csv
    }
    else {
        echo "$name`tDown" >> results.csv
    }

    $count++
    Write-Progress -Activity "Gathering Information" -status "Pinging Hosts..." -percentComplete ($count / $count2 *100)

}

This is the easiest way to me. The output I get is :

Host|State
----------
H1  |Up
H2  |UP
H3  |Down

You can play around with the look, but that's the basic idea. The $count is just a progress bar if you want to spice up the look

1
  • Hey, stumbled upon your answer and it works great, thank you! Only problem I have is if I use the hostname, it automatically shows it as offline aka "Down". If I use the hostname's IP address, it will show as online aka "Up". Could you possibly assist? Thanks again Mar 23, 2017 at 18:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.