You need to enable JavaScript to run this app. PowerShell使用OpenFileDialog多选文档遇属性不存在错误求助
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell使用OpenFileDialog多选文档遇属性不存在错误求助

报错核心原因

Description、ShowNewFolderButton 是 System.Windows.Forms.FolderBrowserDialog(文件夹选择弹窗)的专属属性,OpenFileDialog(文件选择弹窗)本身未定义这两个属性,直接给它赋值自然会触发“未找到Description属性”的报错。

代码中存在的连带问题

  • 变量拼写错误:代码中$OpenFileDialogr多输入了一个尾字母r,和实际定义的变量名不匹配
  • 变量作用域错误:原代码里的$OpenFileDialog是Get-FileName函数内部的局部变量,函数外部无法直接访问
  • 跨语言语法混用:end function Get-FileName是VBA/VBScript的语法,PowerShell不存在该语法规则,写入会直接触发解析错误
  • 字符兼容问题:代码中使用的全角弯引号“”不属于PowerShell可识别的语法引号,会触发解析异常
  • 需求适配缺失:如果要实现选择多个待打开文档的功能,需要给OpenFileDialog开启Multiselect属性,否则默认仅支持选择单个文件

适配多文件选择需求的修正代码

# 加载WinForm依赖程序集,无需在函数内重复加载
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# 配置默认打开的初始文件夹
$defaultFolder = 'C:\替换为你的实际默认路径'

Function Get-MultiSelectedFile {
    param(
        [string]$InitialDirectory
    )
    # 初始化文件选择弹窗
    $openDialog = New-Object System.Windows.Forms.OpenFileDialog
    $openDialog.initialDirectory = $InitialDirectory
    $openDialog.filter = "All files (*.*)| *.*"
    # 开启多选模式
    $openDialog.Multiselect = $true

    # 弹窗并判断用户操作结果
    if ($openDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
        # 返回所有选中的文件完整路径数组
        return $openDialog.FileNames
    }
    # 用户点击取消则返回空数组
    return @()
}

# 调用函数获取选中的文件列表
$selectedFiles = Get-MultiSelectedFile -InitialDirectory $defaultFolder

如果实际需求是选择待归档的文件夹(而非选择多个文档),则需要替换为FolderBrowserDialog组件,对应属性可正常使用:

Add-Type -AssemblyName System.Windows.Forms
$folderDialog = New-Object System.Windows.Forms.FolderBrowserDialog
$folderDialog.Description = "Bitte zu archivierenden Ordner wählen"
$folderDialog.ShowNewFolderButton = $false
if ($folderDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
    $selectedFolderPath = $folderDialog.SelectedPath
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.20 22:45:10