作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要删除所有文件和文件夹,除了根文件夹中的一个文件和子文件夹中的另一个文件。此外,文件名作为参数作为逗号分隔的字符串传递给脚本,例如 '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/
我是一名优秀的程序员,十分优秀!