get a folder path from the explorer menu to a powershell variable

别等时光非礼了梦想. 提交于 2020-01-11 09:24:07

问题


is it possible to open a explorer window from powershell and store the path selected in the explorer, to a variable?

to open explorer window from powershell

PS C:> explorer


回答1:


Maybe this script is what you want:

Function Select-FolderDialog
{
    param([string]$Description="Select Folder",[string]$RootFolder="Desktop")

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

   $objForm = New-Object System.Windows.Forms.FolderBrowserDialog
        $objForm.Rootfolder = $RootFolder
        $objForm.Description = $Description
        $Show = $objForm.ShowDialog()
        If ($Show -eq "OK")
        {
            Return $objForm.SelectedPath
        }
        Else
        {
            Write-Error "Operation cancelled by user."
        }
    }

Use as:

$folder = Select-FolderDialog # the variable contains user folder selection



回答2:


I found the use of reflection in the selected answer to be a little awkward. The link below offers a more direct approach

http://www.powershellmagazine.com/2013/06/28/pstip-using-the-system-windows-forms-folderbrowserdialog-class/

Copy and pasted relevant code:

Add-Type -AssemblyName System.Windows.Forms
$FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
[void]$FolderBrowser.ShowDialog()
$FolderBrowser.SelectedPath



回答3:


The above did not work for me. Running Windows 7 with Powershell Version 2. I did find the following, which did allow the pop-up and selection:

    Function Select-FolderDialog
    {
         param([string]$Description="Select Folder",[string]$RootFolder="Desktop")

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

     $objForm = New-Object System.Windows.Forms.FolderBrowserDialog
     $objForm.Rootfolder = $RootFolder
     $objForm.Description = $Description
     $Show = $objForm.ShowDialog()
     If ($Show -eq "OK")
     {
         Return $objForm.SelectedPath
     }
     Else
     {
        Write-Error "Operation cancelled by user."
     }
    }

Just in case others have the same issues.




回答4:


Just wanted to post an addendum, I believe there is a pipe | missing from in-between:

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")

and:

Out-Null


来源:https://stackoverflow.com/questions/11412617/get-a-folder-path-from-the-explorer-menu-to-a-powershell-variable

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