某些 JSON 文件出现 PowerShell FilterScript 错误

2023-12-04

感谢 iRon 本周早些时候提供的帮助question,他对我目前正在进行的一项工作提供了巨大帮助。

总之,我们有一个 Azure CICD 管道来部署策略。我们有一个包含 200 多个 JSON 策略文件的文件夹,CICD 流程将它们全部放在 1 个 JSON 文件中并将它们部署出来。我们发现的最初问题是参数需要一个额外的前导“[”,否则该过程将失败。这一点在本文中得到了强调article(如果您搜索 [[)。

无论如何,解决问题。 iRons 支持帮了很大的忙,但在 200 个文件中,我们得到了一些文件,其中我们收到以下消息:

Cannot bind argument to parameter 'FilterScript' because it is null.

代码:

iRon提供的功能:

function Get-Node {
    [CmdletBinding()][OutputType([Object[]])] param(
        [ScriptBlock]$Where,
        [Parameter(ValueFromPipeLine = $True, Mandatory = $True)]$InputObject,
        [Int]$Depth = 10
    )
    process {
        if ($_ -isnot [String] -and $Depth -gt 0) {
            if ($_ -is [Collections.IDictionary]) {
                if (& $Where) {$_}
                $_.get_Values() | Get-Node -Where $Where -Depth ($Depth -1)
            }
            elseif  ($_ -is [Collections.IEnumerable]) {
                for ($i = 0; $i -lt $_.get_Count(); $i++) { $_[$i] | Get-Node -Where $Where -Depth ($Depth -1) }
            }
            elseif ($Nodes = $_.PSObject.Properties.Where{$_.MemberType -eq 'NoteProperty'}) {
                $Nodes.ForEach{
                    if (& $Where) { $_ }
                    $_.Value | Get-Node -Where $Where -Depth ($Depth -1)
                }
            }
        }
    }
}

我在其中调用上述函数(此代码位于每个文件的循环中):

    $policyRule = @("notIn", "in", "value", "equals", "field", "effect", "like", "greaterOrEquals", "name", "resourceGroupName", "resourceGroup", "location", "storageName", "uniqueStorage", "storageContainerPath", "storageAccountAccessKey", "dependsOn", "targetResourceId", "storageId", "enabled")
    
    if ($content.properties -ne $null){
        # Loop all the Policy Rule names for fix the values within them
        foreach ($rule in $policyRule){
            $Node = $content.properties.policyRule | Get-Node -Where {$_.name -eq $rule -and $_.value -Match "^\[\w+" -and $_.value -ne ""} 
            $Node | ForEach-Object {$_.Value  = '[' + $_.Value}
        }                 
    }

一个有效的 JSON 文件:

{
  "name": "POLICY-001",
  "properties": {
    "displayName": "Allowed Locations for Resources",
    "policyType": "Custom",
    "mode": "Indexed",
    "description": "This policy enables you to restrict the locations your organization can specify when deploying resources. Use to enforce your geo-compliance requirements. Excludes resource groups, Microsoft.AzureActiveDirectory/b2cDirectories, and resources that use the 'global' region.",
    "metadata": {
      "version": "1.0.0",
      "category": "General"
    },
    "parameters": {
      "listOfAllowedLocations": {
        "type": "Array",
        "metadata": {
          "description": "The list of locations that can be specified when deploying resources.",
          "strongType": "location",
          "displayName": "Allowed locations"
        },
        "allowedValues": [
          "uksouth",
          "ukwest"
        ],
        "defaultValue": [
          "uksouth",
          "ukwest"
        ]
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "location",
            "notIn": "[parameters('listOfAllowedLocations')]"
          },
          {
            "field": "location",
            "notEquals": "global"
          },
          {
            "field": "type",
            "notEquals": "Microsoft.Resources/subscriptions/resourceGroups"
          },
          {
            "field": "type",
            "notEquals": "Microsoft.Resources/b2cDirectories"
          }
        ]
      },
      "then": {
        "effect": "deny"
      }
    }
  },
  "excludedScopes": [
    
  ],
  "nonComplianceMessage": "only allow resources to be deployed from UK South and UK West"
}

失败的一个:

{
  "Name": "Policy-106",
  "Properties": {
    "Description": "This policy automatically deploys and enable diagnostic settings to Log Analytics",
    "DisplayName": "Apply diagnostic settings for Log Analytics Workspaces",
    "Mode": "Indexed",
    "policyType": "Custom",
    "Metadata": {
      "version": "1.0",
      "category": "Monitoring"
    },
    "Parameters": {
      "diagnosticsSettingNameToUse": {
        "type": "string",
        "metadata": {
          "displayName": "Apply diagnostic settings for Log Analytics Workspaces - Setting name",
          "description": "Name of the policy for the diagnostics settings."
        },
        "defaultValue": "setViaPolicy"
      },
      "logAnalytics": {
        "type": "string",
        "metadata": {
          "displayName": "Apply diagnostic settings for Log Analytics Workspaces - Log Analytics workspace",
          "description": "Select the Log Analytics workspace from dropdown list",
          "strongType": "omsWorkspace",
          "assignPermissions": true
        },
        "defaultValue": "/subscriptions/......"
      }
    },
    "PolicyRule": {
      "if": {
        "field": "type",
        "equals": "Microsoft.OperationalInsights/Workspaces"
      },
      "then": {
        "effect": "deployIfNotExists",
        "details": {
          "type": "Microsoft.Insights/diagnosticSettings",
          "roleDefinitionIds": [
            "/providers/Microsoft.Authorization/roleDefinitions/123"
          ],
          "existenceCondition": {
            "allOf": [
              {
                "field": "Microsoft.Insights/diagnosticSettings/logs.enabled",
                "equals": "True"
              },
              {
                "field": "Microsoft.Insights/diagnosticSettings/metrics.enabled",
                "equals": "True"
              },
              {
                "field": "Microsoft.Insights/diagnosticSettings/workspaceId",
                "matchInsensitively": "[parameters('logAnalytics')]"
              }
            ]
          },
          "deployment": {
            "properties": {
              "mode": "incremental",
              "template": {
                "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                "contentVersion": "1.0.0.0",
                "parameters": {
                  "diagnosticsSettingNameToUse": {
                    "type": "string"
                  },
                  "resourceName": {
                    "type": "string"
                  },
                  "logAnalytics": {
                    "type": "string"
                  },
                  "location": {
                    "type": "string"
                  }
                },
                "variables": {},
                "resources": [
                  {
                    "type": "Microsoft.OperationalInsights/Workspaces/providers/diagnosticSettings",
                    "apiVersion": "2017-05-01-preview",
                    "name": "[concat(parameters('resourceName'), '/', 'Microsoft.Insights/', parameters('diagnosticsSettingNameToUse'))]",
                    "location": "[parameters('location')]",
                    "dependsOn": [],
                    "properties": {
                      "workspaceId": "[parameters('logAnalytics')]",
                      "metrics": [
                        {
                          "category": "AllMetrics",
                          "timeGrain": null,
                          "enabled": true,
                          "retentionPolicy": {
                            "enabled": false,
                            "days": 0
                          }
                        }
                      ],
                      "logs": [
                        {
                          "category": "Audit",
                          "enabled": true
                        }
                      ]
                    }
                  }
                ],
                "outputs": {}
              },
              "parameters": {
                "diagnosticsSettingNameToUse": {
                  "value": "[parameters('diagnosticsSettingNameToUse')]"
                },
                "logAnalytics": {
                  "value": "[parameters('logAnalytics')]"
                },
                "location": {
                  "value": "[field('location')]"
                },
                "resourceName": {
                  "value": "[field('name')]"
                }
              }
            }
          }
        }
      }
    }
  },
  "excludedScopes": [

  ],
  "nonComplianceMessage": ""
}

正如我在原来的帖子中提到的,我的 PowerShell 充其量只是基本的,任何支持将不胜感激。


处理失败的JSON文件包含null值,这会变成$null通过以下方式将 JSON 文件转换为对象图时 PowerShell 中的值ConvertFrom-Json.

The Get-Node您问题中所示的函数不支持绑定$null到它的管道绑定-InputObject参数,每当$_.Value恰好是$null在以下声明中:
$_.Value | Get-Node -Where $Where -Depth ($Depth - 1)

解决方案很简单:允许-InputObject接受参数$null,通过添加[AllowNull()]归因于原始功能:

function Get-Node {
  [CmdletBinding()][OutputType([Object[]])] param(
    [ScriptBlock]$Where,
    [AllowNull()]   # <- now $null may be passed too
    [Parameter(ValueFromPipeLine = $True, Mandatory = $True)]$InputObject,
    [Int]$Depth = 10
  )
  process {
    if ($_ -isnot [String] -and $Depth -gt 0) {
      if ($_ -is [Collections.IDictionary]) {
        if (& $Where) { $_ }
        $_.get_Values() | Get-Node -Where $Where -Depth ($Depth - 1)
      }
      elseif ($_ -is [Collections.IEnumerable]) {
        for ($i = 0; $i -lt $_.get_Count(); $i++) { $_[$i] | Get-Node -Where $Where -Depth ($Depth - 1) }
      }
      elseif ($Nodes = $_.PSObject.Properties.Where{ $_.MemberType -eq 'NoteProperty' }) {
        $Nodes.ForEach{
          if (& $Where) { $_ }
          $_.Value | Get-Node -Where $Where -Depth ($Depth - 1)
        }
      }
    }
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

某些 JSON 文件出现 PowerShell FilterScript 错误 的相关文章

随机推荐

  • 迭代变量如何只读?

    在 C 规范的 8 8 4 中 提供了以下示例 形式的 foreach 语句 foreach V v in x embedded statement 然后扩展为 E e C x GetEnumerator try V v while e M
  • 更改 Woocommerce 中购买产品的“添加到购物车”按钮

    我想做的是这样的 客户购买产品 它不会显示 添加到购物车 而是显示 查看数字产品 并具有指向特定页面的自定义链接 我正在查找 WooCommerce 的数据库 并试图弄清楚如何知道某个商品已被购买 以便我可以弄清楚如何让一个函数自动执行此操
  • 支持所有 Android 平板电脑分辨率

    我们公司的设计师希望我给他 Android 平板电脑的分辨率 以便他开始设计一个新的应用程序 我知道有很多不同的解决方案 此处列出 安卓平板电脑 我还知道 Android 对不同 dpi 的划分 ldpi mdpi 我的问题 我应该告诉设计
  • 如何更改CListCtrl列的颜色

    我想将特定列的背景颜色更改为对话框的颜色 灰色 我怎样才能实现它 void CUcsOpTerminalDlg OnCustomdrawFeatureList NMHDR pNMHDR LRESULT pResult LPNMCUSTOMD
  • 正则表达式 javascript 中仅排除 0

    我想创建一个正则表达式 它将采用一到十个数值 但如果只提供 0 则它不应该接受 例如 1 is valid input 1111123455 is valid input 01 is valid input 010 is valid inp
  • 如何使用 Java DeflaterOutputStream

    编辑 我真的只需要知道 Deflater 派生类何时决定写入页眉和页脚数据 以及如何利用这些事实 我真的很想做以下事情 用一些字节为 Deflater 派生类准备字典 我想我明白了 发送一些要压缩的数据到 Deflater 派生类 我想我明
  • 填充第二个选择框 - 绑定问题

    我使用以下代码用城市填充第二个选择框 jQuery country live change function populateCityListBox alert jQuery select city val function populat
  • Objective-C 从自定义单元格访问方法

    好吧 这可能是一个新手问题 但我需要帮助 我有一个 someview m 其中有一个在 customCell h 和 m 中定义的自定义单元格 所以在 someview m 我有 UITableViewCell tableView UITa
  • 如何在php中创建hmac md5?

    我正在使用 payU 信用卡系统 但我没办法 payU 告诉我必须创建 hmac md5 哈希值 我的密钥是 3 9 X4 660 ak h6 T 我想转换为 HMAC MD5 哈希 8GEMISEPE6208617192012 12 15
  • 创建文件夹并使 ES File Explorer 添加我的应用程序的图标

    我想将文件夹与我的应用程序关联起来 就像 WhatsApp 和 Viber 那样 我尝试创建文件夹 File folder new File Environment getExternalStorageDirectory getPath M
  • 注释可以出现在 DOCTYPE 声明之前吗?

    我想发表评论 style 位于 HTML 代码的最顶部 位于 DOCTYPE 声明之前 这符合标准吗 主流浏览器都支持吗 这样做有什么陷阱吗 It is 完全有效 to do However 带来allIE 版本怪癖模式 除非是forced
  • 如何避免 Xstream 生成带有 & 或 "e 或类似字符的 xml 文件?

    我开始工作Xstream与Java 我有一个名为的汽车列表CarList 我有一辆汽车作为一个名为Car XStream xstream new XStream new StaxDriver xstream alias Car Car cl
  • 使用 Rvest 抓取包含多个表的 URL

    我正在尝试学习如何做一些scraping使用 rvest 包 我正在用这个url加载信息 我试图获取 URL 中标记为 高级 的表的信息 当我尝试加载信息时 我所能得到的只是第一个表 我的意思是 当我使用谷歌浏览器检查时 我看到表中的数字被
  • 在 XSLT v1.0 中使用以结尾

    我正在尝试编辑当前的 XSLT 我想要的功能是当 code no 的值以01结尾时我想编辑当前城市位置 目前此功能不存在 我尝试过使用字符串和子字符串 但它给了我一个错误 说结尾功能不存在 请帮忙 来自 xml 的值是
  • 使 Android 模拟器适用于 1600x1200

    我尝试在模拟器中将 Android 的皮肤布局编辑为 1600x1200 但模拟器无法打开窗口 它适用于较小的分辨率 如 1024x480 等 但不适用于大分辨率 尽管即使使用 1024x480 模拟器窗口的一部分也无法访问且不可见 我的问
  • PHP 编码电子邮件地址

    我需要一条路PHP仅使用对电子邮件地址进行编码a zA Z0 9所以基本上编码时没有任何特殊字符 但随后能够将其解码回原始内容 Example email protected gt ENCODE gt n6bvJjdh7w6QbdVB373
  • NodeJS并行回调设计模式

    我正在尝试找到一个好的模式来执行一堆并行任务 让我定义一些任务来举例说明 任务a b c d e f g执行为a function er ra task a returned ra is result so do b to g 还有一些任务
  • Webpack 反应热加载程序不工作

    下面是我的 webpack config js 代码 var webpack require webpack var path require path module exports context dirname app entry we
  • 右栏按钮项目不显示

    我有以下用于放置 rightbarbuttonitem 的代码 UIButton rightbutton UIButton buttonWithType UIButtonTypeCustom rightbutton setBackgroun
  • 某些 JSON 文件出现 PowerShell FilterScript 错误

    感谢 iRon 本周早些时候提供的帮助question 他对我目前正在进行的一项工作提供了巨大帮助 总之 我们有一个 Azure CICD 管道来部署策略 我们有一个包含 200 多个 JSON 策略文件的文件夹 CICD 流程将它们全部放