【问题标题】:PowerShell Delete everything else except one file in root and one in sub folderPowerShell 删除除根目录中的一个文件和子文件夹中的一个文件之外的所有其他文件
【发布时间】:2018-09-03 03:48:54
【问题描述】:

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

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

【问题讨论】:

    标签: powershell build-automation


    【解决方案1】:

    完成它的最简单方法是使用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删除

    希望对你有帮助。

    【讨论】:

    • 感谢您的帮助,但您看到我的根文件夹可以有多个 txt 文件,除了一个特定文件外,我需要删除它们,因此尽管我尝试使用 Get-ChildItem C,但使用扩展名删除文件是不可行的: \Path -排除 SampleFileToExclude.txt| Remove-Item -Force 但它仍然会删除所有内容,如何保护子文件夹中的第二个文件,因为我必须运行此命令一次,而且我在参数中获取了排除文件名。
    • @HaiyanJamali:具体的文件名是什么,并告诉我具体的根文件夹路径。
    • 有两种方法:首先尝试仅使用带有Exclude参数的get-childitem并提及具体的文件名。这将列出除您保留在排除中的文件之外的文件。如果它仍然显示排除的那些,那么名称或空间问题或其他问题中的一些问题。进一步,如果它列出来,然后去删除管道对象
    • 检查stackoverflow.com/a/14776054/2715716,看看为什么thisRemove-Item -Recurse更好,如果你想知道为什么不直接使用它。
    猜你喜欢
    • 1970-01-01
    • 2019-11-21
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 2018-01-05
    • 1970-01-01
    相关资源
    最近更新 更多