You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell脚本中打开与OpenFileDialogUI一致的文件夹选择对话框

实现方案(原生资源管理器UI,零额外依赖)

直接调用Windows原生文件对话框接口并开启文件夹选择模式即可,得到的选择窗口和OpenFileDialog UI完全一致,支持资源管理器的所有操作逻辑,无需引入任何第三方依赖,可直接运行:

Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;

public class FolderPicker {
    [DllImport("comdlg32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern int GetOpenFileName(ref OPENFILENAME lpofn);

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    private class OPENFILENAME {
        public int lStructSize;
        public IntPtr hwndOwner;
        public IntPtr hInstance;
        public string lpstrFilter;
        public string lpstrCustomFilter;
        public int nMaxCustFilter;
        public int nFilterIndex;
        public string lpstrFile;
        public int nMaxFile;
        public string lpstrFileTitle;
        public int nMaxFileTitle;
        public string lpstrInitialDir;
        public string lpstrTitle;
        public int Flags;
        public short nFileOffset;
        public short nFileExtension;
        public string lpstrDefExt;
        public IntPtr lCustData;
        public IntPtr lpfnHook;
        public string lpTemplateName;
        public IntPtr pvReserved;
        public int dwReserved;
        public int FlagsEx;
    }

    private const int OFN_EXPLORER = 0x00080000;
    private const int OFN_PATHMUSTEXIST = 0x00000800;
    private const int FOS_PICKFOLDERS = 0x00000020;

    public static string ShowDialog(string title = "选择文件夹") {
        OPENFILENAME ofn = new OPENFILENAME();
        ofn.lStructSize = Marshal.SizeOf(ofn);
        ofn.lpstrTitle = title;
        ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | FOS_PICKFOLDERS;
        ofn.lpstrFile = new string('\0', 260);
        ofn.nMaxFile = 260;

        return GetOpenFileName(ref ofn) != 0 ? ofn.lpstrFile.Trim('\0') : null;
    }
}
'@

# 调用示例
$selectedPath = [FolderPicker]::ShowDialog("请选择目标文件夹")
if ($null -eq $selectedPath) {
    exit
}
Write-Host "Chose $selectedPath"

轻量魔改方案(无需自定义类型)

如果不需要严格的交互逻辑校验,也可以直接修改OpenFileDialog的内置参数实现文件夹选择,代码更简短:

Add-Type -AssemblyName System.Windows.Forms

Push-Location
$FolderBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
    Title = "选择文件夹..."
    Filter = "文件夹|*."
    CheckFileExists = $false
    CheckPathExists = $true
    ValidateNames = $false
    AddExtension = $false
}

if($FolderBrowser.ShowDialog() -ne "OK") {
    exit
}
Pop-Location

$SelectedFolder = $FolderBrowser.FileName
Write-Host "Chose $SelectedFolder"

使用说明:进入需要选择的文件夹后,直接点击「打开」按钮即可选中当前文件夹。

内容的提问来源于stack exchange,提问作者MHebes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 09:48:04