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

How do I specify the initial path shown in the FolderBrowserDialog using PowerShell

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

如何指定初始目录而不是桌面或网络快捷方式。我想指定像 F:\Folder1

这样的路径

这是我手边的功能,以备不时之需:

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

如果您不想显示该按钮,则可以省略 -NewFolderButton

将您的 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