0

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 
7
  • 2
    Pretty sure -Whatif generates Verbose output so there wouldn't be any objects in the pipeline to pass to Export-csv. Commented Apr 2, 2018 at 16:33
  • @EBGreen: Good point about -WhatIf in general, but it looks like the information is printed straight to the console, not to the verbose output stream (number 4). Commented Apr 2, 2018 at 17:00
  • @mklement0 You are correct in that assumption (it's a [string] object output to the 1 stream) Commented Apr 2, 2018 at 17:07
  • @TheIncorrigible1: In the context of PowerShell, 1 is the success (data) output stream, but this is not where -WhatIf output goes - as far as I can tell, you cannot capture / redirect it all from within PowerShell. (You could from the outside, such as when calling from cmd.exe). Commented Apr 2, 2018 at 17:12
  • 1
    @mklement0 Hmm, I was quick to jump the gun here. Wrapping a command in parens and accessing its type reported string, but now attempting to use redirection or other cmdlets doesn't capture that output. It doesn't even use 5 (Information) like Write-Host does in PSv5 Commented Apr 2, 2018 at 17:18

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.