简体   繁体   English

递归删除带有 Powershell 问题的文件夹

[英]Deleting folders with Powershell recursively issue

I need to delete some subfolders under a folder 'ToDelete'.我需要删除文件夹“ToDelete”下的一些子文件夹。 I am using this to do that: (both should do the same deletion).我用这个来做那个:(两者都应该做同样的删除)。 my problem is that there is other folder called 'Do_Not_Copy' under ToDelete folder that contain also a folder called 'Tools' that should not be deleted.我的问题是 ToDelete 文件夹下还有一个名为“Do_Not_Copy”的文件夹,其中还包含一个名为“Tools”的文件夹,不应删除。 how I can protect this 'Tools' subfolder?我如何保护这个“工具”子文件夹? -Exclude doesn't work. -排除不起作用。 My workaround for now is to use Rename-Item for the Tools folder我现在的解决方法是对 Tools 文件夹使用 Rename-Item

$DestinationFolder = "\\google\server\ToDelete"

Remove-Item -Path $DestinationFolder\  -Include "Tools", "Support", "Installer", "GUI", "Filer", "Documentation" -Recurse -Exclude "Do_not_copy\SI\Tools" -Force 
Get-ChildItem $DestinationFolder\ -Include "Tools", "Support", "Installer", "GUI", "Filer", "Documentation" -Recurse -Force | ForEach-Object { Remove-Item -Path $_.FullName -Recurse -Force }

The -Recurse switch does not work properly on Remove-Item (it will try to delete folders before all the subfolders in the folder have been deleted). -Recurse开关在 Remove-Item 上无法正常工作(它将尝试在删除文件夹中的所有子文件夹之前删除文件夹)。
Sorting the fullnames in descending order by length ensures than no folder is deleted before all the child items in the folder have been deleted.按长度降序对全名进行排序可确保在删除文件夹中的所有子项之前不会删除任何文件夹。

Try尝试

$rootFolder = '\\google\server\ToDelete'
# create a regex of the folders to exclude
$Exclude = 'Do_not_copy\SI\Tools'  # this can be an array of items to exclude or a single item
# each item will be Regex Escaped and joined together with the OR symbol '|'
$notThese = ($Exclude | ForEach-Object { [Regex]::Escape($_) }) -join '|'
# the array of folder names (not full paths) to delete
$justThese = 'Tools', 'Support', 'Installer', 'GUI', 'Filer', 'Documentation'

(Get-ChildItem -Path $rootFolder -Directory -Recurse -Include $justThese).FullName |
    Where-Object { $_ -notmatch $notThese } |
    Sort-Object Length -Descending |
    Remove-Item -Recurse -Confirm:$false -Force -WhatIf

As usual, I have added the -WhatIf safety switch, so no folders will be deleted and in the console you can see what would happen.像往常一样,我添加了-WhatIf安全开关,因此不会删除任何文件夹,您可以在控制台中看到发生什么。 When satisfied the correct folders will be removed, comment out or remove that -WhatIf switch and run again如果满意,将删除正确的文件夹,注释掉或删除-WhatIf开关并再次运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM