Search code examples
powershelldropdown

Powershell dropdown select item, loads a specific text file into text box on form


In Powershell I want to have a dropdown list with following items:

Textfile1 Textfile2 Textfile3

When one if the list items is selected it reads file contents into textbox on form.

For example:

dropdown "Textfile1" is selected, that loads c:\Textfile1.txt into textbox on form.

already tried a function with if/elseif but having difficulty tying it together, unfortunately still learning Powershell.


Solution

  • I wouldn't recommend create a form with a dropdown list and return the choice from that, as Powershell is pretty much not built for that stuff.

    Of course,I dont think it is impossible, but i'd use in this case the Out-GridView function to do work that is similar to your needs.

    $files_location = "C:\yourlocation\*"
    
    
    $options = Get-ChildItem $files_location
    
    
    $user_choice = $options | Out-GridView -Title 'Select the File you want to show'  -PassThru
    
    Switch ($user_choice)  {
    
        #Condition to check:
    
        { $user_choice.Name -eq 'textfile1.txt' }
    
    
        #Do something:
        {
            Write-Host "Im going to open $($user_choice.Name)"
            #Open the file:
            start "$user_choice"
        }
    
        #Continue your switch/case conditions here...
    
    }
    

    I'm using the output object from the Get-ChildItem function and outputting a gridview from that.

    You can change the Switch case to if statement if you more comfortable with this function:

    $files_location = "C:\yourlocation\*"
    
    
    $options = Get-ChildItem $files_location
    
    
    $user_choice = $options | Out-GridView -Title 'Select the File you want to show'  -PassThru
    
    if ($user_choice.Name -eq 'a.txt')
    {
        start $user_choice
    }