首页 > 解决方案 > PowerShell 删除除根目录中的一个文件和子文件夹中的一个文件之外的所有其他文件

问题描述

我需要删除除根文件夹中的一个文件和子文件夹中的另一个文件之外的所有文件和文件夹。此外,文件名作为逗号分隔的字符串作为参数传递给脚本,例如“file1.txt,Subfolder\file2.txt”。

我试图做这样的事情,

$Path = "C:\\Delete\\"
$Argument= "file1.txt,Subfolder\\file2.txt"
$ExcludedFiles = [string]::Join(',', $Argument);
$files = [System.IO.Directory]::GetFiles($Path, "*", "AllDirectories")

foreach($file in $files) { 
    $clearedFile = $file.replace($Path, '').Trim('\\');

    if($ExcludedFiles -contains $clearedFile){
        continue;
    } 

    Remove-Item $file
}

通过这样做,所有文件夹都保留下来,所有文件都被删除。任何人都可以建议我应该如何尝试这样做,因为我很难做到这一点。

标签: powershellbuild-automation

解决方案


完成它的最简单方法是-Exclude使用get-childitem.

以下是排除文件的示例:

Get-ChildItem C:\Path -Exclude SampleFileToExclude.txt| Remove-Item -Force

使用通配符排除具有特定扩展名的文件:

Get-ChildItem C:\Path -Exclude *.zip | Remove-Item -Force

递归获取所有文件并排除相同的文件:

Get-ChildItem C:\Path -Recurse -Exclude *.zip | Remove-Item -Force

在同一命令中根据您的意愿排除项目列表:

Get-ChildItem C:\Path -Recurse -Exclude *.zip, *.docx | Remove-Item -Force

你甚至可以使用数组和 where 条件:

$exclude_ext = @(".zip", ".docx")
$path = "C:\yourfolder"
Get-ChildItem -Path $path -Recurse | Where-Object { $exclude_ext -notcontains $_.Extension }

然后你可以删除使用Remove-Item

希望能帮助到你。


推荐阅读