Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting the verbose output of a Remove-Item command

Tags:

powershell

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 a 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 that:

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

I know i can do this with a foreach statement and a Write-Host command, but I believe it can be done with some pipelining or something. Any ideas?

like image 333
lalibi Avatar asked Dec 29 '11 13:12

lalibi


2 Answers

Using ForEach-Object is pretty straightforward:

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

As @user978511 pointed out, using the verbose output is more complicated:

$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'
like image 189
Rynant Avatar answered Nov 16 '22 02:11

Rynant


In PowerShell 3.0 you can write the Verbose stream to the output stream (e.g 4>&1) and then replace the message:

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
}
like image 20
Shay Levy Avatar answered Nov 16 '22 03:11

Shay Levy