Home > Back-end >  Is there a way to filter $OpenFileDialog.filter by more than extension?
Is there a way to filter $OpenFileDialog.filter by more than extension?

Time:08-27

I'd like to search for all files that end in .att, but exclude anything that starts with 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. Is there an easy way to do this?

Thanks!

CodePudding user response:

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 ;. Following this thought, we can use Get-ChildItem the get all the file names in the target location and join them with a ; 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'
  • Related