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

PowerShell 5.1中如何将PSCustomObject转为Hashtable适配New-AzTag

在PowerShell 5.1中将PSCustomObject转换为Hashtable的方法

针对你遇到的问题,这里提供两种实用方法,可在PowerShell 5.1中把ConvertFrom-Json返回的PSCustomObject转为New-AzTag所需的Hashtable类型:

方法一:遍历属性手动构建Hashtable

直接遍历PSCustomObject的属性集合,逐个添加到空Hashtable中:

# 从存储表读取标签并转换为PSCustomObject
$Setting = Get-AzTableRow -Table $cloudTable -PartitionKey $PartKey -RowKey mykey
$psCustomTags = ConvertFrom-Json -InputObject $Setting.Tags

# 初始化空Hashtable
$tagHashtable = @{}

# 遍历属性填充Hashtable
foreach ($prop in $psCustomTags.PSObject.Properties) {
    $tagHashtable[$prop.Name] = $prop.Value
}

方法二:通过管道批量构建Hashtable

利用New-Object创建Hashtable实例,再通过管道批量添加属性:

$Setting = Get-AzTableRow -Table $cloudTable -PartitionKey $PartKey -RowKey mykey
$psCustomTags = ConvertFrom-Json -InputObject $Setting.Tags

# 创建Hashtable并批量填充属性
$tagHashtable = New-Object System.Collections.Hashtable
$psCustomTags.PSObject.Properties | ForEach-Object {
    $tagHashtable[$_.Name] = $_.Value
}

验证与使用

转换完成后,可通过以下命令确认类型是否正确:

$tagHashtable.GetType()

输出应为System.Collections.Hashtable,此时即可将其传入New-AzTag:

New-AzTag -ResourceId "<目标资源ID>" -Tag $tagHashtable

注意:PowerShell 7及以上版本支持ConvertFrom-Json -AsHashtable参数直接返回Hashtable,但该参数在PowerShell 5.1中不可用,因此需使用上述手动转换方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 04:10:23