繁体   English   中英

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

[英]Deleting folders with Powershell recursively issue

我需要删除文件夹“ToDelete”下的一些子文件夹。 我用这个来做那个:(两者都应该做同样的删除)。 我的问题是 ToDelete 文件夹下还有一个名为“Do_Not_Copy”的文件夹,其中还包含一个名为“Tools”的文件夹,不应删除。 我如何保护这个“工具”子文件夹? -排除不起作用。 我现在的解决方法是对 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 }

-Recurse开关在 Remove-Item 上无法正常工作(它将尝试在删除文件夹中的所有子文件夹之前删除文件夹)。
按长度降序对全名进行排序可确保在删除文件夹中的所有子项之前不会删除任何文件夹。

尝试

$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

像往常一样,我添加了-WhatIf安全开关,因此不会删除任何文件夹,您可以在控制台中看到发生什么。 如果满意,将删除正确的文件夹,注释掉或删除-WhatIf开关并再次运行

暂无
暂无

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

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