gpt4 book ai didi

PowerShell 删除除根目录中的一个文件和子文件夹中的一个文件之外的所有其他文件

转载 作者:行者123 更新时间:2023-12-03 01:03:48 37 4
gpt4 key购买 nike

我需要删除所有文件和文件夹,除了根文件夹中的一个文件和子文件夹中的另一个文件。此外,文件名作为参数作为逗号分隔的字符串传递给脚本,例如 '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
}

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

最佳答案

最简单的方法是使用 get-childitem 中的 -Exclude 参数。

以下是排除文件的示例:

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

移除

希望对你有帮助。

关于PowerShell 删除除根目录中的一个文件和子文件夹中的一个文件之外的所有其他文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52142938/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com