我有一个文件夹,像
carlo
|
+--- Stephen King
|
+-- 22_11_63 (19989)
22_11_63 (39129)
22_11_63 (59966)
|
+-- IT (589)
IT (2893)
|
+-- A. Ribaudo
|
+-- Guidare sicuri (3859)
Guidare sicuri (39068)
例如22_11_63 (19989)
的大小为2mb,22_11_63 (39129)
的大小为1mb,最后的大小为500kb。a . Ribaudo也是一样,每个子文件夹有不同的大小。
我只希望保留大小最大的子文件夹
我使用这个脚本,但我只能移动丢失的子文件夹从父folder2
(塞尔吉奥)到另一个父folder1
(卡罗)。
# Set the path to the two folders to compare
$folder1 = "C:UsersAdministratorDesktopconfrontocarlo"
$folder2 = "C:UsersAdministratorDesktopconfrontosergio"
# Get the list of folders in each folder
$folders1 = Get-ChildItem -Path $folder1 -Directory
$folders2 = Get-ChildItem -Path $folder2 -Directory
# Loop through the folders in $folder2
$folders2 | ForEach-Object {
$folder2Name = $_.Name
$folder2Path = $_.FullName
$folder1Path = Join-Path -Path $folder1 -ChildPath $folder2Name
# Check if the folder exists in $folder1
if (Test-Path -Path $folder1Path) {
# The folder exists in both folders, so check if it has the same subfolders
$subfolders2 = Get-ChildItem -Path $folder2Path -Directory
$subfolders1 = Get-ChildItem -Path $folder1Path -Directory
$missingIn1 = Compare-Object -ReferenceObject $subfolders1 -DifferenceObject $subfolders2 -Property Name -PassThru
# Move the missing subfolders to $folder1
$missingIn1 | ForEach-Object {
$subfolderSource = $_.FullName
$subfolderDest = Join-Path -Path $folder1Path -ChildPath $_.Name
Copy-Item -Path $subfolderSource -Destination $subfolderDest -Recurse
}
# Remove duplicate subfolders from $folder1
$subfolders1 = Get-ChildItem -Path $folder1Path -Directory
$subfoldersToKeep = @()
$subfolders1 | Group-Object -Property Name | ForEach-Object {
$subfoldersGroup = $_.Group
$largestSubfolder = $subfoldersGroup | Sort-Object -Property Length -Descending | Select-Object -First 1
$subfoldersToKeep += $largestSubfolder
}
$subfolders1 | Where-Object { $subfoldersToKeep -notcontains $_ } | Remove-Item -Recurse
}
}
这是我期望的最终输出
carlo
|
+--- Stephen King
|
+-- 22_11_63 (19989)
|
+-- IT (2893)
|
+-- A. Ribaudo
|
+-- Guidare sicuri (3859)
如您所见,我只保留了大小最大的子文件夹,删除了其余的子文件夹。每个子文件夹都有相同数量的单词,除了括号
中的文本给定此场景应满足的两个特定条件。
- 从
carlo
中搜索的文件夹的深度为2。 -
文件夹名称除了括号
(..)
中的字母/数字外,名称相同。
基于此,我可以提出一个解决方案:
Get-ChildItem -Path 'C:UsersAdministratorDesktopconfrontocarlo**' -Directory |
Group-Object -Property { ($_.BaseName -split ' (')[0] } |
ForEach-Object -Process {
$_.Group | Sort-Object -Property { (Get-ChildItem -Path $_.FullName).Length } -Descending |
Select-Object -Skip 1 | Remove-Item -WhatIf
}
由于子文件夹的命名约定是相同的,您可以根据括号前的字母进行分组,将其分成2,然后只获取第一个字符串:($_.BaseName -split ' (')[0]
。因此,22_11_63 (19989)
变成了22_11_63
,允许对对象进行适当的分组。
现在,考虑到Sort-Object
在将对象输出回控制台之前如何累积对象的性质,您可以使用scriptblock对哪个文件夹的大小最大进行排序:(Get-ChildItem -Path $_.FullName).Length
,指定-Descending
将颠倒顺序,将最大的文件夹放在顶部。最后,您可以管道到Select-Object
,以便跳过第一个对象(,这将是最大的文件夹),然后将其余对象传递给Remove-Item
进行删除。
删除-WhatIf
公共/安全参数,当你指示这些是你所追求的结果。