删除数组中重复的文件

问题描述 投票:0回答:1

我有一个包含重复文件的文件夹,文件名中的前 10 个字母相同,后 2 个字母是随机的,我想通过 PWSH 脚本删除这些文件。 特定文件位于重复文件所在的同一文件夹中。 我不想删除这个特定文件,我只想删除 1 周之前的重复文件。

编辑:我想删除 C: emp\Folder 中超过 1 周的所有内容,除了“DontDelete”之外,我想保存该文件。 (DontDelete 也有重复项)

$Location = "C:\temp\Folder\" # Here is where all the duplicate files are located
$W = "7" 
$Date = (Get-date).AddDays(-$W)
$DontDelete = "DontDelete*"  
$Array = Get-Content -Path @("C:\Delete\Remove.txt")

Get-ChildItem -Path $Location |
  where { $_.LastWriteTime -lt $Date } |
    Out-file "C:\Delete\Remove.txt" 

Set-Location "$Location" 
$Array 

foreach ($Item in $Array) {
    Remove-Item -Recurse -Force
}

# If $DontDelete exsist in $array (Which it will) don't delete the $Dontdelete file.
# Delete the rest of the files which are older then 7-days.

windows powershell file
1个回答
1
投票

我对你的要求感到困惑,但如果你要求不删除一个文件。将您的 Get-Child 通过管道传输到 where 对象

$time=(Get-Date).AddDays(-7)
$fnd="/file/not/to/delete.txt"
Get-ChildItem -Path $Location | Where-Object {$_.LastWriteTime -lt $time -and $_.Name -ne $fnd} | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue


然后你就可以一次性完成你所要求的一切。最初的

Get-Child
获取目录中的所有文件管道到
Where-Object
,然后过滤一周前的所有文件,而不是您想要的文件。最后通过管道进入
Remove-item
,删除所有项目。

© www.soinside.com 2019 - 2024. All rights reserved.