PowerShell中JSON数组转List失败,无法创建Azure Sentinel告警
Azure Sentinel告警规则创建时Tactics参数格式错误问题解决
问题场景
从data.json中提取tactics属性,尝试通过循环创建数组并传入New-AzSentinelAlertRule命令创建Azure Sentinel告警,但执行时出现BadRequest错误,提示tactics[0]包含无效值InitialAccess PrivilegeEscalation。
data.json内容
{ "displayName": "travel with mailbox permission", "tactics": [ "InitialAccess", "PrivilegeEscalation" ], "techniques": [ "T1078", "T1548" ] }
原代码
$content = Get-Content -Raw -Path "data.json" | ConvertFrom-Json [System.Collections.Generic.List[System.String]]$TacticObject = @() foreach ($Tactic in $content.tactics) { $TacticObject.Add($Tactic) } echo $TacticObject New-AzSentinelAlertRule -ResourceGroupName $resourceGroupName -WorkspaceName $workspaceName -Tactic $TacticObject
执行输出
InitialAccess PrivilegeEscalation
错误信息
[BadRequest] : Field 'tactics[0]' contains an invalid value 'InitialAccess PrivilegeEscalation'.
问题原因
New-AzSentinelAlertRule的-Tactic参数需要接收独立字符串元素组成的数组,但原代码传递List对象时,PowerShell隐式将其转换为单个空格分隔的字符串,导致Azure Sentinel API接收到的不是数组,而是包含两个战术值的单个字符串,触发格式错误。
解决方案
方案1:直接使用解析后的数组(推荐)
ConvertFrom-Json已将JSON中的tactics解析为PowerShell字符串数组,无需手动循环构建List,直接传递即可:
$content = Get-Content -Raw -Path "data.json" | ConvertFrom-Json # 直接使用解析完成的tactics数组 New-AzSentinelAlertRule -ResourceGroupName $resourceGroupName -WorkspaceName $workspaceName -Tactic $content.tactics
方案2:保留List对象的正确传递方式
如果需要保留List对象,直接赋值并传递即可,无需手动循环添加元素:
$content = Get-Content -Raw -Path "data.json" | ConvertFrom-Json [System.Collections.Generic.List[System.String]]$TacticObject = $content.tactics # 直接传递List,PowerShell会正确识别为数组参数 New-AzSentinelAlertRule -ResourceGroupName $resourceGroupName -WorkspaceName $workspaceName -Tactic $TacticObject
说明
两种方案的核心都是确保传递给-Tactic参数的是字符串数组/集合,而非被拼接成单个字符串的内容,这样Azure Sentinel API才能正确识别每个战术值。
内容的提问来源于stack exchange,提问作者dev333
相关产品推荐
相关产品推荐

