简体   繁体   English

有没有办法通过扩展名过滤 $OpenFileDialog.filter ?

[英]Is there a way to filter $OpenFileDialog.filter by more than extension?

I'd like to search for all files that end in.att, but exclude anything that starts with sorted_ .我想搜索以 .att 结尾的所有文件,但排除以sorted_开头的任何文件。

Function Get-AttName($initialDirectory)
{   
 [System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) |
 Out-Null

 $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
 $OpenFileDialog.initialDirectory = $initialDirectory
 $OpenFileDialog.filter = “All files (*.att)| *.att”
 $OpenFileDialog.ShowDialog() | Out-Null
 $OpenFileDialog.filename
} #end function Get-FileName 

And here are some files:这里有一些文件:

test.att
sorted_test.att
Nav_HF_New.att
Sorted_Nav_HF_New.att

I want to only be able to select test.att and Nav_HF_New.att .我只想能够 select test.attNav_HF_New.att Is there an easy way to do this?是否有捷径可寻?

Thanks!谢谢!

Unfortunately Wildcard expressions don't have an option to "not match" something as far as I know, however there is one workaround we could use via string manipulation.不幸的是,据我所知, 通配符表达式没有“不匹配”某些东西的选项,但是我们可以通过字符串操作使用一种解决方法。

By looking at Remarks from the FileDialog.Filter Property Docs we can tell that we can add several patterns to the filter expression separating them with a semi-colon ;通过查看FileDialog.Filter Property Docs 中的Remarks ,我们可以看出我们可以在过滤器表达式中添加几个模式,用分号分隔它们; . . Following this thought, we can use Get-ChildItem the get all the file names in the target location and join them with a ;按照这个想法,我们可以使用Get-ChildItem来获取目标位置的所有文件名,并用;将它们连接起来。 and use that as our filter, which seems to work properly however it would only work in the target directory, if you want to navigate to other directory it wouldn't work unless there is a file name that matches with one of those in the target directory.并将其用作我们的过滤器,这似乎可以正常工作,但是它只能在目标目录中工作,如果您想导航到其他目录,除非有与目标中的文件名之一匹配的文件名,否则它将无法工作目录。

Here is the code:这是代码:

function Get-AttName {
    param(
        [string] $InitialDirectory,
        [string] $Extension,
        [string] $Exclude
    )

    Add-Type -AssemblyName System.Windows.Forms

    $InitialDirectory = Convert-Path $initialDirectory
    $filter = (Get-ChildItem $initialDirectory -Filter $Extension |
        Where-Object Name -NotMatch $Exclude).Name -join ';'

    if(-not $filter) {
        $filter = $Extension
    }

    $OpenFileDialog = [System.Windows.Forms.OpenFileDialog]@{
        InitialDirectory = $InitialDirectory
        Filter           = "All files ($Extension)|$filter"
    }

    if($OpenFileDialog.ShowDialog() -eq 'Ok') {
        $OpenFileDialog.FileName
    }
}

Get-AttName . -Extension *.att -Exclude '^sorted'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM