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

如何使用Get-Command获取PowerShell命令的输出参数及数据类型

获取PowerShell命令输出属性及对应数据类型的方法

要获取任意PowerShell命令的输出属性(即你所说的“输出参数”)及其数据类型,无需执行命令查看实例值,直接通过类型元数据就能实现,以下是两种实用方法:

方法一:无需执行命令,直接从类型定义获取

这种方法适合执行有副作用、耗时,或你不想实际运行的命令,直接从命令的输出类型元数据中提取属性信息:

# 替换为你要查询的目标命令
$targetCommand = "Get-LocalUser"

# 获取命令的输出类型
$outputType = (Get-Command $targetCommand).OutputType.Type

# 提取属性名称和对应的数据类型(优化显示可空类型)
$outputType.GetProperties() | Select-Object Name, @{
    Name = "DataType"
    Expression = { 
        if ($_.PropertyType.IsGenericType -and $_.PropertyType.GetGenericTypeDefinition() -eq [Nullable[object]].GetGenericTypeDefinition()) {
            $_.PropertyType.GenericTypeArguments[0].Name + "?"
        } else {
            $_.PropertyType.Name
        }
    }
}

以Get-LocalUser为例,执行后会输出直观的属性与类型对应表:

NameDataType
AccountExpiresDateTime?
DescriptionString
EnabledBoolean
FullNameString
PasswordChangeableDateDateTime?
PasswordExpiresDateTime?
UserMayChangePasswordBoolean
PasswordRequiredBoolean
PasswordLastSetDateTime?
LastLogonDateTime?
NameString
SIDSecurityIdentifier
PrincipalSourcePrincipalSource?
ObjectClassString

方法二:通过命令实例获取实际输出属性

如果允许执行目标命令获取一个实例,这种方法能看到实际输出中存在的属性(部分类型属性可能在实例中未被赋值,但方法一仍会显示):

# 获取第一个实例并提取属性信息
Get-LocalUser | Select-Object -First 1 | Get-Member -MemberType Property | Select-Object Name, @{
    Name = "DataType"
    Expression = { ($_.Definition -split " ")[0] }
}

执行后会输出每个属性的名称和对应的数据类型,比如Enabled对应bool,Name对应string等。

对于你的图形程序开发需求,推荐使用方法一:无需执行命令就能提前获取所有可能的输出属性及其类型,用户可直接在界面中选择需要监控的属性,后续再执行命令获取对应属性的实际值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:38:35