我最近一直在疯狂地运行这个脚本,我试图修改它,以适应我的需要。我最近发现用"LastWriteTime“删除文件不是我想要的。
我需要我的脚本做的是使用"CreationTime“属性删除30天以上的文件,问题是在修改脚本之后,它会删除整个文件夹结构吗?
这个小小的修改如何改变整个脚本的行为呢?
这就是我所用的:
$limit = (Get-Date).AddDays(-30)
$del30 = "D:\CompanyX_ftp\users"
$ignore = Get-Content "C:\Users\UserX\Documents\Scripts\ignorelist.txt"
Get-ChildItem $del30 -Recurse |
Where-Object {$_.CreationTime -lt $limit } |
Select-Object -ExpandProperty FullName |
Select-String -SimpleMatch -Pattern $ignore -NotMatch |
Select-Object -ExpandProperty Line |
Remove-Item -Recurse因此,如果我将"CreationTime“属性替换为"LastWriteTime”,脚本将运行并执行它应该做的事情,但是如果我使用"CreationTime“,它只会删除文件夹结构下的所有内容,包括文件夹本身及其应该忽略的路径。
UPDATE:脚本现在正在为我工作,用于实际删除文件,但用于获取脚本将要删除的实际文件的report的脚本实际上包括ignorelist.txt文件的路径吗?请参阅以下脚本:
$limit = (Get-Date).AddDays(-30)
$del30 = "D:\CompanyX_ftp\users"
#Specify path for ignore-list
$ignore = Get-Content "C:\Users\UserX\Documents\Scripts\ignorelist.txt"
Get-ChildItem $del5 -File -Recurse |
Where-Object {$_.CreationTime -lt $limit } |
Select-Object -ExpandProperty FullName |
Select-String -SimpleMatch -Pattern $ignore -NotMatch |
Select-Object -ExpandProperty Line |
Get-ChildItem -Recurse | Select-Object FullName,CreationTimeignorelist.txt样本数据:
D:\CompanyX_ftp\user\ftp-customerA\Customer下载
D:\CompanyX_ftp\user\ftp-customerB\Customer下载
D:\CompanyX_ftp\user\ftp-customerC\Customer下载
D:\CompanyX_ftp\user\ftp-customerD\Customer下载
D:\CompanyX_ftp\user\ftp-customerE\Customer下载
D:\CompanyX_ftp\user\ftp-customerF\Customer下载
D:\CompanyX_ftp\user\ftp-customerG\Customer下载
D:\CompanyX_ftp\user\ftp-customerH\Customer下载\
对于为什么包括我在ignorelist.txt上提到的路径,有什么想法吗?(我也将提供一个图像,以更好地说明)。
在此之前感谢您的帮助或指导。
//伦纳特
发布于 2021-02-17 14:55:41
我看到更新后的代码有两个问题:
Get-ChildItem递归地遍历目录的内容。稍后,在管道中,对第一个Get-ChildItem返回的项开始另一个递归迭代,导致重叠。$ignore筛选时,只忽略与$ignore路径完全匹配的路径。忽略列表中项的子路径不会被忽略。我就是这样做的。创建一个与给定路径与忽略列表匹配的函数Test-IgnoreFile,检查当前路径是否从忽略列表中的任何路径开始。这样,子路径也会被忽略。这使我们能够大大简化管道。
Param(
[switch] $ReportOnly
)
# Returns $true if $File.Fullname starts with any path in $Ignore (case-insensitive)
Function Test-IgnoreFile( $File, $Ignore ) {
foreach( $i in $Ignore ) {
if( $File.FullName.StartsWith( $i, [StringComparison]::OrdinalIgnoreCase ) ) {
return $true
}
}
$false
}
$limit = (Get-Date).AddDays(-30)
$del30 = "D:\CompanyX_ftp\users"
$ignore = Get-Content "C:\Users\UserX\Documents\Scripts\ignorelist.txt"
Get-ChildItem $del30 -File -Recurse |
Where-Object { $_.CreationTime -lt $limit -and -not ( Test-IgnoreFile $_ $ignore ) } |
ForEach-Object {
if( $ReportOnly) {
$_ | Select-Object FullName, CreationTime
}
else {
$_ | Remove-Item -Force
}
}https://stackoverflow.com/questions/66240915
复制相似问题