记录删除的内容

时间:2016-04-04 10:08:37

标签: powershell

我对此很新,但我在删除30天的旧文件时遇到问题,我在这里找到了答案:Powershell - Delete subfolder(s) in folder with specific name(s) older than 30 days

但我想就此提出一个问题。
我使用的代码是:

gci P:\ -directory -recurse | ?{$_.FullName -match ".:\\.+?\\.+?\\.+?\\.+?\\.+?\\" -and $_.CreationTime -lt (get-date).AddDays(-30)}|Remove-Item -recurse -whatif

是否可以记录删除的内容?如果文件的大小包含在日志文件中,那将是很棒的。谢谢!

1 个答案:

答案 0 :(得分:1)

使删除操作详细并将verbose stream重定向到文件:

... | Remove-Item -Recurse -Verbose 4> 'C:\path\to\your.log'

请注意,这至少需要PowerShell v3。

如果您只想记录要删除的内容而不实际删除它,请使用-WhatIf代替-Verbose

... | Remove-Item -Recurse -WhatIf

你也可以将两者结合起来:

$dryrun = $true   # set to $false to actually delete
... | Remove-Item -Recurse -Verbose -WhatIf:$dryrun 4> 'C:\path\to\your.log'

但是,-WhatIf输出到主机控制台,因此无法重定向到文件。您可以使用Start-Transcript作为解决方法,但这会记录所有内容,而不仅仅是可能的删除。或者您可以在新的PowerShell进程中运行整个代码/脚本(无重定向):

powershell.exe -File 'C:\path\to\your.ps1' > 'C:\path\to\your.log'

子PowerShell进程的主机输出被合并到其STDOUT中,因此您可以“从外部”重定向它。

相关问题