2024年如何在PowerShell中正确关联System.Windows.Forms?
在PowerShell中正确引用System.Windows.Forms的方法
首先纠正你代码里的一个拼写错误:Add-Type的参数是-TypeDefinition,你写成了-TypeDefition(少了一个i),这会导致命令解析错误,也是报错的原因之一。
接下来分PowerShell版本给出正确方案:
1. Windows PowerShell(5.1及以下,Windows系统默认自带版本)
这个版本原生支持System.Windows.Forms,用以下任意一种方式加载即可:
- 方式一(推荐):
Add-Type -AssemblyName System.Windows.Forms
加载后直接调用类,比如:
[System.Windows.Forms.MessageBox]::Show("测试弹窗")
- 方式二(已过时但仍可用):
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
2. PowerShell 7+(跨平台的Core版本)
PowerShell Core默认不包含System.Windows.Forms,需要先安装专用模块:
- 安装模块(可指定
-Scope CurrentUser避免管理员权限):
Install-Module -Name Microsoft.PowerShell.Windows.Forms -Scope CurrentUser -Force
- 导入模块:
Import-Module Microsoft.PowerShell.Windows.Forms
之后就可以正常使用System.Windows.Forms的各类控件了。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

