powershell - 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
}
通过这样做,所有文件夹都保留下来,所有文件都被删除。任何人都可以建议我应该如何尝试这样做,因为我很难做到这一点。
解决方案
完成它的最简单方法是-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
希望能帮助到你。
推荐阅读
- flutter - 我想让我的代码响应任何屏幕尺寸的颤振飞镖
- ios - Firebase Crashlytics 没有出现在 Xamarin.Forms 应用程序 (iOS) 中,尽管构建成功并上传了 dsym
- javascript - 为什么我在上传到 s3 时在终端中收到此错误?我写的不对?
- visual-studio-code - VSCode - 光标在 AltGr 上向左移动。如何解决?
- java - 在 Spring Boot WebFlux 中读取 postman 上传的 Excel 文件
- visual-studio - 在visual studio 2019 intellisense提供的建议列表中上下移动的快捷键
- javascript - 使用下拉菜单更改图像,仅适用于添加的最后一张图像
- connection - snowflake snowsql 错误 250003 (n/a): 未能获得响应。绞刑?
- html - 如何制作带有图像和标题的容器
- flutter - TweenAnimationBuilder 没有正确重复 Flutter