Need to output command results to file

Jeff L 21 Reputation points
2021-09-10T17:48:45.273+00:00

Is there an easy way for me to pump the output of a series of file deletions using foreach?

Get-ChildItem -Path C:\Temp\Testing*\Beep* -Include * | foreach {$_.Delete()}

I know foreach doesn't support pipelining but I'm trying to keep this simple and am not well versed with the ForEach-Object command..

Thanks,

J

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,388 questions
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 32,076 Reputation points
    2021-09-21T17:49:33.733+00:00

    You can't reference .Fullname in the catch because "$ underscore" will be the error object.

    Please use the Code Sample icon when posting code. The "101010" icon.

    Try it like this. I highly recommend using -whatif on the Remove-Item when you are testing.

    $Folders = Get-ChildItem 'C:\Users\*\AppData\Roaming\Temp*' -Recurse
    ""
    "Folders contains {0} entries." -f $Folders.count 
    ""
    $csv = ForEach ($File in $folders) {
        Try {
            Remove-Item $File.FullName -ErrorAction Stop -whatif 
            [PSCustomObject]@{
                Path = $File.FullName
                Action = "Removed"
                Error = ""
                }
            }
        Catch {
            [PSCustomObject]@{
                Path = $File.FullName
                Action = "NotRemoved"
                Error = $_ 
            }
        }
    } 
    
    $csv | Export-Csv C:\Temp\RR_Cleanup_Output.csv -NoTypeInformation
    

6 additional answers

Sort by: Most helpful
  1. Jeff L 21 Reputation points
    2021-09-20T20:57:48.88+00:00

    So this worked fine in test with just a couple directories thrown in, but on Server 2019 with 100's of results, it doesn't delete anything just throws the below error: Any thoughts?

    "Path","Action","Error"
    ,"NotRemoved","Cannot bind argument to parameter 'Path' because it is null."

    The initial command pulls down all the folders/files properly, but it seems somewhere the logic loop is pulling back a null value? Any thoughts?


  2. Jeff L 21 Reputation points
    2021-09-21T19:20:12.03+00:00

    Looks like it's working based on the Whatif run, thanks guys. Appreciate all the help!

    0 comments No comments