首页 > 解决方案 > Powershell从“删除项目”获取日志输出

问题描述

我对powershell很陌生。我需要学习它。我从一个简单的脚本开始,它删除不同路径中的某些文件扩展名,如果它们超过 10 天。

    $DeleteDate = (Get-Date).AddDays(-10)
    $path1 = "\\path1\*.tibx*"
    $path2 = "\\path2\*Backup Set*"
    $path3 = "\\path3\*.tibx*"
    
    Get-ChildItem $path1 | Where {$_.LastWriteTime -lt "$DeleteDate"} | Remove-Item
    Get-ChildItem $path2 -Recurse | Where {$_.LastWriteTime -lt "$DeleteDate"} | Remove-Item  
    Get-ChildItem $path3 | Where {_.LastWriteTime -lt "$DeleteDate"} | Remove-Item

到目前为止,这有效。现在我还需要的是,它正在记录,它被删除的内容和时间。唯一的问题是 Remove-Item 似乎没有输出。甚至没有“详细”。

我考虑将 Items 放入一个数组中,然后将删除前后的数组写入日志文件中。但对于这么简单的任务来说,这似乎有点复杂。你有什么可以帮助我的想法吗?

标签: powershelllogging

解决方案


在 之前插入ForEach-Object管道Remove-Item,然后在此处记录:

Get-ChildItem $path1 | Where {$_.LastWriteTime -lt "$DeleteDate"} | ForEach-Object {
  Write-Verbose "Deleting '$($_.FullName)' at [$(Get-Date -Format o)]"
  $_
} | Remove-Item

推荐阅读