【问题标题】:Powershell: Delete a file inside a folder with different name of parent folderPowershell:删除具有不同父文件夹名称的文件夹中的文件
【发布时间】:2013-04-12 13:48:40
【问题描述】:

我想使用此选项来删除那些具有特定扩展名(在我的情况下为 .cfg)且文件夹名称不同的文件。例如,如果我在一个名为 MYFOLDER 的文件夹中,并且在这两个文件 MYFOLDER.cfg 和 otherfile.cfg 中,则应该(递归地)删除 otherfile.cfg。

这就是我目前所拥有的:

$folder = Get-ChildItem * -exclude *.* -name -recurse
$file = Get-ChildItem * -include *.cfg* -name -recurse | % { [IO.Path]::GetFileNameWithoutExtension($_) }
#$folder | ForEach-Object {Compare-Object $folder $file | <DELETE file with different name>}

我怎样才能做到最后一行?

提前致谢。问候。

【问题讨论】:

    标签: file powershell directory get-childitem


    【解决方案1】:

    这将为您完成:

    Get-ChildItem -Recurse -Include *.cfg  | % { If ( $_.Name.Split(".")[0] -ne $_.Directory.Name ) {$_.Delete()}}
    

    【讨论】:

    • 不客气。如果它解决了您的问题,请随意投票或选择正确答案:-)
    【解决方案2】:

    双衬里,但你可以把它做成单衬里;)

    $FolderName = (Get-Location).Path.Split("\")[(Get-Location).Path.Split("\").Count -1]
    $Files = Get-ChildItem | Where-Object {$_.Extension -ne ".cfg" -or $_.Name.Split(".")[0] -ne $FolderName} | Remove-Item -Recurse
    

    但是当文件的名称包含一个点(例如 File.Name.cfg)时,此代码以及 Musaab Al-Okaidi 的代码都不能处理这种情况

    【讨论】:

      【解决方案3】:

      Remove -WhatIf 删除文件:

      Get-ChildItem -Filter *.cfg -Recurse | 
      Where-Object {$_.BaseName -ne $_.Directory.Name} | 
      Remove-Item -WhatIf
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-01
        • 1970-01-01
        • 2018-06-21
        • 2014-11-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多