Formatting the detailed output of the Remove-Item command

I have the following command:

Get-ChildItem $build_path `
    -Include *.bak, *.orig, *.txt, *.chirp.config `
    -Recurse | Remove-Item -Verbose

to clear some files from the build folder of the VS solution. I use the Verbose switch so that I can see which files are being deleted. It works fine, but the output is too verbose:

VERBOSE: Performing operation "Remove File" on Target "R:\Visual Studio 2010\Projects\SomeProject\SomeProject.Web.build\App_Readme\glimpse.mvc3.readme.txt".
VERBOSE: Performing operation "Remove File" on Target "R:\Visual Studio 2010\Projects\SomeProject\SomeProject.Web.build\App_Readme\glimpse.readme.txt".

I just need to see something like this:

Removing file \App_Readme\glimpse.mvc3.readme.txt".
Removing file \App_Readme\glimpse.readme.txt".
...

I know that I can do this using the foreach statement and the Write-Host command, but I believe that this can be done using some kind of pipelining or something else. Any ideas?

+5
source share
4 answers

Usage is ForEach-Objectquite simple:

Get-ChildItem $build_path `
    -Include *.bak, *.orig, *.txt, *.chirp.config `
    -Recurse | foreach{ "Removing file $($_.FullName)"; Remove-Item $_}

As @ user978511 pointed out, using verbose output is harder:

$ps = [PowerShell]::Create()

$null = $ps.AddScript(@'
    Get-ChildItem $build_path `
        -Include *.bak, *.orig, *.txt, *.chirp.config `
        -Recurse | Remove-Item -Verbose
'@)

$ps.Invoke()
$ps.Streams.Verbose -replace '(.*)Target "(.*)"(.*)','Removing File $2'
+6
source

PowerShell 3.0 Verbose (, 4 > 1), :

Get-ChildItem $build_path `
    -Include *.bak, *.orig, *.txt, *.chirp.config `
    -Recurse | Remove-Item -Verbose 4>&1 | Foreach-Object{ `
        Write-Host ($_.Message -replace'(.*)Target "(.*)"(.*)','Removing File $2') -ForegroundColor Yellow
}
+3

, , . : Invoke-Sqlcmd . , foreach .

+1

, - , , , .

I would try deleting the file and then report success or failure. See below:

$FileList = $build_path `
    -Include *.bak, *.orig, *.txt, *.chirp.config `
    -Recurse

foreach ($File in $FileList)
{
    Try
    {
        Remove-Item $File.FullName -Force -ErrorAction Stop
        Write-Output "Deleted: $($File.Parent)\$($File.Name)"
    }
    Catch
    {
        Write-Output "Error deleting: $($File.Parent)\$($File.Name); Error Message: $($_.Exception.Message)"
    }
}

If you want to output both to the console and enter the file, you can use the Tee-Object at the end of each line, starting with Write-Output above.

| Tee-Object -FilePath $your_log_file -Append
+1
source

All Articles