如何使用PowerShell指定FolderBrowserDialog中显示的初始路径

时间:2019-06-05 23:02:33

标签: powershell folderbrowserdialog

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 = "NetworkShortcuts"

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

$a = Get-Folder

如何指定初始目录而不是Desktop或NetworkShortcuts。我想指定 F:\ Folder1

之类的路径

2 个答案:

答案 0 :(得分:1)

这是我随时需要的功能:

//create hashmap
for(int i = 0; i<testDoc.length; i++){
    if(setW.contains(testDoc[i])) {
        doc.indexOf(testDoc[i]);
       //add string and its index to hashmap
    }

用法非常简单:

Function Get-FolderPath{
[CmdletBinding()]
Param(
    [String]$Description,
    [String]$InitialDirectory = "C:\",
    [Switch]$NewFolderButton = $false)

    [void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
    $FolderBrowserDialog = New-Object System.Windows.Forms.FolderBrowserDialog
    $FolderBrowserDialog.SelectedPath = $InitialDirectory
    $FolderBrowserDialog.Description = $Description
    $FolderBrowserDialog.ShowNewFolderButton = $NewFolderButton
    If($FolderBrowserDialog.ShowDialog() -eq "OK"){
        $FolderBrowserDialog.SelectedPath
    }
}

或者如果您不希望显示该按钮,请忽略$a = Get-FolderPath -Description "Select a folder" -InitialDirectory "F:\Folder1" -NewFolderButton

答案 1 :(得分:1)

rootfolder换成SelectedPath,这应该是您所要的。

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.SelectedPath = "F:\Folder1"

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

$a = Get-Folder