代码之家  ›  专栏  ›  技术社区  ›  svick Raja Nadar

排除PowerShell中的目录

  •  24
  • svick Raja Nadar  · 技术社区  · 17 年前

    我想从PowerShell中的搜索中排除所有目录。两个 FileInfo DirectoryInfo 包含 Attributtes 属性似乎正是我想要的,但我无法找到如何基于它进行筛选。两者都是

    ls | ? { $_.Attributes -ne 'Direcory' }
    ls | ? { $_.Attributes -notcontains 'Direcory' }
    

    不起作用。我该怎么做?

    3 回复  |  直到 13 年前
        1
  •  25
  •   Joey Gumbo    13 年前

    你可以使用 PSIsContainer 财产:

    gci | ? { !$_.PSIsContainer }
    

    您的方法也可以,但必须如下所示:

    gci | ? { !($_.Attributes -band [IO.FileAttributes]::Directory) }
    

    因为属性是枚举和位掩码。

    或者,对于您的其他方法:

    gci | ? { "$($_.Attributes)" -notmatch "Directory" }
    

    这将导致属性转换为字符串(可能看起来像“directory,reparsepoint”),并且在字符串上可以使用 -notmatch 操作员。

    PowerShell v3最终具有 -Directory 参数对 Get-ChildItem :

    Get-ChildItem -Directory
    gci -ad
    
        2
  •  9
  •   Alain O'Dea    14 年前

    排除PowerShell中的目录:

    Get-ChildItem | Where-Object {$_ -isnot [IO.DirectoryInfo]}
    

    或者简明扼要,但很难阅读:

    gci | ? {$_ -isnot [io.directoryinfo]}
    

    感谢@joey使用 -is 操作员:)

    然而

    技术上,我更喜欢 包括 只有排除后的文件或目录才能导致意外结果,因为get childitem可以返回的不仅仅是文件和目录:)

    仅包括文件:

    Get-ChildItem | Where-Object {$_ -is [IO.FileInfo]}
    

    或:

    gci | ? {$_ -is [io.fileinfo]}
    

    仅包括目录:

    Get-ChildItem | Where-Object {$_ -is [IO.DirectoryInfo]}
    

    或:

    gci | ? {$_ -is [io.directoryinfo]}
    
        3
  •  6
  •   Anton I. Sipos    17 年前

    您还可以通过直接查看目录的类型来筛选目录:

    ls | ?{$_.GetType() -ne [System.IO.DirectoryInfo]}
    

    目录由system.io.directoryinfo类型的get childitem(或ls或dir)返回,文件的类型为system.io.fileinfo。在PowerShell中将类型用作文本时,需要将它们放在括号中。

    推荐文章