Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Breakup List of file filters in FileOpenDialog

I have a function to open a list of files with filters and after selecting one, it opens in the default program for the file type. I want to break the filter list up so I have one per line as I’m going to have quite a few but it isn’t working with the normal backtick. If I do them all on a single line, it works fine. Here is what I’m trying to accomplish. I tried doing it before and after the pipe but it made no difference. If I set it to all files I see Word documents but if I set it to *.docx they don’t show. The same for *.xlsx files and *.csvs they show up in the filter dialog but they just aren’t being read. Can this be done or do I Have to do them all on the same line?

function Open-FileDialog {
        [cmdletBinding()]
        param(
            [Parameter()]
            [ValidateScript({Test-Path $_})]
            [String]
            $InitialDirectory
        )
    Add-Type -AssemblyName System.Windows.Forms
    $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog 
    if($InitialDirectory){
        $FileBrowser.InitialDirectory = $InitialDirectory
    }

    else{
    $fileBrowser.InitialDirectory = [Environment]::GetFolderPath('MyDocuments')
    }$FileBrowser.Filter = 'SpreadSheet (*.xlsx)|*.xlsx`
    |Document (*.docx)|*.docx`
    |CSV (*.csv)|*.csv`
    |All Files (*.*)|*.*'

[void]$FileBrowser.ShowDialog()
$FileBrowser.FileName

}

$file = Open-FileDialog
Invoke-item $file

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The .Filter property has to be a string joined by pipes | it doesn’t recognize backticks ` as a separator. See FileDialog.Filter Remarks for more details.

What you can do to keep it clean is an array that is later on joined by | with -join operator. This way you can add or remove more filters quite easily.

$FileBrowser.Filter = @(
    'SpreadSheet (*.xlsx)|*.xlsx'
    'Document (*.docx)|*.docx'
    'CSV (*.csv)|*.csv'
    'All Files (*.*)|*.*'
) -join '|'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading