Search code examples
powershelloutputexport-csv

Powershell: Export-CSV and OutFile not doing what I expect


Why am I getting a blank file here? When I run it before the export-csv I get PLENTY of records all showing up in the console.

output

So here's the code I'm using

$path = "C:\test"

Get-ChildItem -Path $path -Include *.edi, *.x12, *.filename, *.dat, *.log, *.mdn, *.req -Recurse -Force |
Where-Object {!$_.PSIsContainer -and ((get-date)-$_.LastWriteTime).days -gt 30 } |
Remove-Item -force -whatif | export-csv D:\output.csv #also I try out-file D:\output.txt 

Solution

  • Common parameter -WhatIf - used for previewing a command's actions - never outputs data; instead, the preview information is printed straight to the console, meaning it can neither be sent through the pipeline, nor redirected to file, nor captured.

    As an aside: Remove-Item without -WhatIf also never produces data output, so there is generally no point in trying to process its output in a subsequent pipeline segment.

    Your best bet is to add an -OutVariable (-ov) common parameter to your Where-Object call, which allows you to export the collected file-info objects via Export-Csv in a separate command:

    Get-ChildItem ... | Where-Object -OutVariable filesToRemove { ... } | 
      Remove-Item -WhatIf ...
    $filesToRemove | Export-Csv D:\output.csv
    

    The above still prints the preview information to the console, but also collects the [System.IO.FileInfo] objects selected by Where-Object in variable $filesToRemove, which you can then export in CSV format.