[英]Formatting the verbose output of a Remove-Item command
我有以下命令:
Get-ChildItem $build_path `
-Include *.bak, *.orig, *.txt, *.chirp.config `
-Recurse | Remove-Item -Verbose
清除VS解决方案的build文件夹中的某些文件。 我使用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".
我只需要看到类似的东西:
Removing file \App_Readme\glimpse.mvc3.readme.txt".
Removing file \App_Readme\glimpse.readme.txt".
...
我知道我可以用foreach语句和Write-Host命令来做到这一点,但我相信它可以用一些流水线或其他东西来完成。 有任何想法吗?
使用ForEach-Object
非常简单:
Get-ChildItem $build_path `
-Include *.bak, *.orig, *.txt, *.chirp.config `
-Recurse | foreach{ "Removing file $($_.FullName)"; Remove-Item $_}
正如@ user978511指出的那样,使用详细输出更复杂:
$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'
在PowerShell 3.0中,您可以将详细信息流写入输出流(例如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
}
这是几年太晚了,但它可能会帮助那些偶然发现它的人,就像我这样做,无论如何我会提供它。
我会尝试删除文件,然后报告成功或失败。 见下文:
$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)"
}
}
如果您想要输出到控制台并记录到文件,您可以在每行末尾使用Tee-Object ,从上面的Write-Output开始。
| Tee-Object -FilePath $your_log_file -Append
为了能够修改消息,首先需要输出不那么容易的输出。 您可以参考本页面上的答案: Powershell Invoke-Sqlcmd捕获详细输出以捕获输出。 从那以后,您可以修改消息并以您的格式显示它,但foreach选项看起来更容易
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.