How do I properly use the FolderBrowserDialog in Powershell

血红的双手。 提交于 2019-12-01 17:38:01
Vasily Alexeev

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"

    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.

You need to add " | Out-Null" to the end of the line "[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")"

otherwise there is a bunch of info returned by Get-Folder you don't want

Cheers, Garth

Selecting a folder

Using System.Windows.Forms.FolderBrowserDialog allows you to select a folder only.

Function Get-Folder($initialDirectory) {
    [void] [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
    $FolderBrowserDialog = New-Object System.Windows.Forms.FolderBrowserDialog
    $FolderBrowserDialog.RootFolder = 'MyComputer'
    if ($initialDirectory) { $FolderBrowserDialog.SelectedPath = $initialDirectory }
    [void] $FolderBrowserDialog.ShowDialog()
    return $FolderBrowserDialog.SelectedPath
}
($FolderPermissions = Get-Folder C:\Users | get-acl | select -exp access | ft)

For more info on System.Windows.Forms.FolderBrowserDialog class check official docs.

Selecting a file

function Get-File($initialDirectory) {   
    [void] [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    if ($initialDirectory) { $OpenFileDialog.initialDirectory = $initialDirectory }
    $OpenFileDialog.filter = 'All files (*.*)|*.*'
    [void] $OpenFileDialog.ShowDialog()
    return $OpenFileDialog.FileName
}
($FilePermissions = Get-File C:\ | get-acl | select -exp access | ft)

For more info on System.Windows.Forms.OpenFileDialog class check official docs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!