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

PowerShell 5.1中动态创建可修改enum的更简便方法咨询

动态创建可修改的PowerShell枚举(Enum)问题

我需要从[string[]]类型的数据中,在运行时动态创建可修改的枚举(Enum)。最初我使用如下代码:

$fruits = 'apple','orange'
Add-Type "public enum fruits { $($fruits -join ",`n") }"

但第二次运行并修改fruits列表时,出现错误:
add-type : Cannot add type. The type name 'fruits' already exists.

随后我尝试:

$fruits = 'apple','orange'
[scriptblock]::create("enum fruits {$($fruits -join "`n")}").invoke()

但脚本块在独立上下文执行,新创建的枚举无法在当前会话中访问。

之后我发现一种可行的方法:

$fruits = 'apple','orange'
$executioncontext.InvokeCommand.InvokeScript($false, [scriptblock]::create("enum fruits {$($fruits -join "`n")}"), $null, $null)

现在可以随意重新定义枚举且无错误,例如:

$fruits = 'apple','orange','banana'
$executioncontext.InvokeCommand.InvokeScript($false, [scriptblock]::create("enum fruits {$($fruits -join "`n")}"), $null, $null)

该方法有效但略显复杂,请问我是否遗漏了什么?在PowerShell 5.1中有没有更简单的动态创建可修改enum的方法?

环境信息
PSVersion                      5.1.19041.4046
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.4046
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 02:33:23