Hai*_*ali 2 build-automation 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
}
Run Code Online (Sandbox Code Playgroud)
通过这样做,所有文件夹都保留下来,所有文件都被删除。任何人都可以建议我应该如何尝试这样做,因为我很难做到这一点。
得到它使用的是做最简单的方法-Exclude在paramater get-childitem。
以下是排除文件的示例:
Get-ChildItem C:\Path -Exclude SampleFileToExclude.txt| Remove-Item -Force
Run Code Online (Sandbox Code Playgroud)
使用通配符排除具有特定扩展名的文件:
Get-ChildItem C:\Path -Exclude *.zip | Remove-Item -Force
Run Code Online (Sandbox Code Playgroud)
递归获取所有文件并排除相同的文件:
Get-ChildItem C:\Path -Recurse -Exclude *.zip | Remove-Item -Force
Run Code Online (Sandbox Code Playgroud)
根据您的意愿在同一命令中排除项目列表:
Get-ChildItem C:\Path -Recurse -Exclude *.zip, *.docx | Remove-Item -Force
Run Code Online (Sandbox Code Playgroud)
您甚至可以使用数组和 where 条件:
$exclude_ext = @(".zip", ".docx")
$path = "C:\yourfolder"
Get-ChildItem -Path $path -Recurse | Where-Object { $exclude_ext -notcontains $_.Extension }
Run Code Online (Sandbox Code Playgroud)
然后你可以删除使用 Remove-Item
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
3132 次 |
| 最近记录: |