Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly use the FolderBrowserDialog in Powershell

So I'm still fairly new to Powershell and I'm trying to write a script that allows the user to select a file or folder and then get back the security permissions for said folder/file. The problem is, I can't seem to get the file path to record as a variable to be used later. Here's what I have so far:

Function Get-Folder($initialDirectory)
{
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")

    $foldername = New-Object System.Windows.Forms.FolderBrowserDialog
    $foldername.rootfolder = "MyComputer"
    $foldername.ShowDialog()

    if($foldername.ShowDialog() -eq "OK") {
        $folder += $foldername.SelectedPath
    }
}

Maybe I'm way off on this, but it will pull up the window to select a file or folder and makes me choose twice and then doesn't set the variable as the file path. Again, I'm pretty new to this kind of thing so I could be totally wrong, but any help would be incredibly helpful.

Thanks!

like image 582
Ben_the_Terrible Avatar asked Sep 05 '14 16:09

Ben_the_Terrible


People also ask

How do I select a folder in PowerShell?

You can also change directory in PowerShell to a specified path. To change directory, enter Set-Location followed by the Path parameter, then the full path you want to change directory to. If the new directory path has spaces, enclose the path in a double-quote (“”).

How do I get user input in PowerShell?

Use the Read-Host to Prompt for User Input in PowerShell The -Prompt parameter is used to specify a text to provide the information about what to input. It appends a colon : to the text you enter. The Read-Host pauses execution and receives input. When a user enters the value at the prompt, it returns that same value.


1 Answers

The folder selector window shows twice because you have two calls to $foldername.ShowDialog(). Remove the first one, and leave only the one inside if.

I tried to run your code, and am sure that $folder variable is in fact set. If you think that it is not set you are doing something wrong. For example, be aware, that it is only visible inside your Get-Folder function. If you need to use it outside of the function, you should return it (return $folder) and assign it to a variable outside the function. For example:

Function Get-Folder($initialDirectory="")

{
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null

    $foldername = New-Object System.Windows.Forms.FolderBrowserDialog
    $foldername.Description = "Select a folder"
    $foldername.rootfolder = "MyComputer"
    $foldername.SelectedPath = $initialDirectory

    if($foldername.ShowDialog() -eq "OK")
    {
        $folder += $foldername.SelectedPath
    }
    return $folder
}

$a = Get-Folder

This way you will have your selected folder in the $a variable.

like image 126
Spc_555 Avatar answered Oct 18 '22 13:10

Spc_555