无法使用 Powershell 将正在删除的文件名重定向到输出 csv 文件

Could not redirect the file names that are being deleted to an output csv file using Powershell

我正在尝试删除早于 x 天的文件,想知道正在删除哪个文件。

我正在使用下面的 powershell 脚本,它不起作用

$limit = (Get-Date).AddDays(-365)
$path = $args[0]

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force | select Name,LastWriteTime | Export-CSV -NoTypeInformation -Path $args[1] 

我将第一个参数作为文件所在的路径传递。 第二个参数是输出文件,它应该包含那些被删除的文件和日期修改值。

上面的代码可以很好地删除,但不会重定向被删除的文件名和最后修改的值。

如果我使用下面的代码,它只会重定向文件名和最后修改的值,但文件不会被删除。

Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | select Name,LastWriteTime | Export-CSV -NoTypeInformation -Path $args[1] | Remove-Item -Force

使用下面的命令 运行 它 -

./OlderFiles_Cleansing.ps1 'C:\Dev\PS' 'C:\dev\CleanedFiles_01062016.csv'

我错过了什么?

Export-Csv 和 Remove-Item Cmdlet return 都不是您通过管道输入的集合,因此无法进一步处理管道中的项目。

不过您可以执行以下操作 - 拆分命令:

$filesToDelete = Get-ChildItem -Path $path -Recurse -Force -Attributes !Directory | Where-Object CreationTime -lt $limit  
$filesToDelete | select Name,LastWriteTime | Export-CSV -NoTypeInformation -Path $args[1] 
$filesToDelete | Remove-Item -Force

请注意,我改进了使用 Attributes 参数等可以简化 Where 管道部分