Extract value from .json and pass to powershell script

Hi all! Please help me with this question. I have this powershell script:

# Set variables $ApiMgmtRG = "MyResourceGroup"  
 $ApiMgmtServiceName = "MyApiManagementService" $ApiId = "MyApiId"  
  # Connect to API Management context  
 $apimContext = New-AzApiManagementContext -ResourceGroupName $ApiMgmtRG -ServiceName $ApiMgmtServiceName   
 # Get all operationIds for the API 
$operationIds = Get-Content .\OpenAPISpecification.json | ConvertFrom-Json | Select-Object -ExpandProperty OperationId  
  # Loop through each operationId and execute the Set-AzApiManagementPolicy cmdlet  
 foreach ($operationId in $operationIds) {     Set-AzApiManagementPolicy -Context $apimContext -ApiId $ApiId -OperationId $operationId -PolicyFilePath $operationId.xml -Format application/vnd.ms-azure-apim.policy.raw+xml  
 }

Example json file:

{
	"components": {
		"schemas": {
			"ClientSubscriptionResponse": {
				"additionalProperties": false,
				"properties": {
					"clientId": {
						"nullable": true,
						"type": "string"
					},
					"createdAtUtc": {
						"format": "date-time",
						"type": "string"
					},
					"equipmentNumber": {
						"nullable": true,
						"type": "string"
					},
					"id": {
						"nullable": true,
						"type": "string"
					},
					"isPaused": {
						"type": "boolean"
					},
					"messageMetadata": {
						"nullable": true,
						"type": "string"
					},
					"rules": {
						"items": {
							"$ref": "#/components/schemas/SubscriptionRuleDto"
						},
						"nullable": true,
						"type": "array"
					},
					"updatedAtUtc": {
						"format": "date-time",
						"type": "string"
					},
					"url": {
						"nullable": true,
						"type": "string"
					}
				},
				"type": "object"
			},
			"EndpointDto": {
				"additionalProperties": false,
				"properties": {
					"webSocket": {
						"$ref": "#/components/schemas/WebSocketEndpointConfig"
					}
				},
				"type": "object"
			},
			"Error": {
				"additionalProperties": false,
				"properties": {
					"message": {
						"nullable": true,
						"type": "string"
					},
					"source": {
						"nullable": true,
						"type": "string"
					}
				},
				"type": "object"
			},
			"ErrorResponse": {
				"additionalProperties": false,
				"properties": {
					"errors": {
						"items": {
							"$ref": "#/components/schemas/Error"
						},
						"nullable": true,
						"type": "array"
					},
					"traceId": {
						"nullable": true,
						"type": "string"
					}
				},
				"type": "object"
			},
			"SubscriptionDto": {
				"additionalProperties": false,
				"properties": {
					"clientId": {
						"nullable": true,
						"type": "string"
					},
					"createdAtUtc": {
						"format": "date-time",
						"type": "string"
					},
					"description": {
						"nullable": true,
						"type": "string"
					},
					"endpoint": {
						"$ref": "#/components/schemas/EndpointDto"
					},
					"equipmentNumber": {
						"nullable": true,
						"type": "string"
					},
					"id": {
						"nullable": true,
						"type": "string"
					},
					"isPaused": {
						"type": "boolean"
					},
					"messageMetadata": {
						"nullable": true,
						"type": "string"
					},
					"rules": {
						"items": {
							"$ref": "#/components/schemas/SubscriptionRuleDto"
						},
						"nullable": true,
						"type": "array"
					},
					"updatedAtUtc": {
						"format": "date-time",
						"type": "string"
					}
				},
				"type": "object"
			},
			"SubscriptionRuleDto": {
				"additionalProperties": false,
				"properties": {
					"field": {
						"pattern": "^[ -~]{1,200}$",
						"type": "string"
					},
					"operator": {
						"pattern": "^\\D{1,20}$",
						"type": "string"
					},
					"value": {
						"pattern": "^[ -~]{1,50}$",
						"type": "string"
					}
				},
				"required": [
					"field",
					"operator",
					"value"
				],
				"type": "object"
			},
			"UpsertClientSubscriptionRequest": {
				"additionalProperties": false,
				"properties": {
					"clientId": {
						"pattern": "^[ -~]{0,50}$",
						"type": "string"
					},
					"equipmentNumber": {
						"nullable": true,
						"pattern": "^((?!.*(&|<|>|\\\\|\\/|\\s))[ -~]){0,25}$",
						"type": "string"
					},
					"id": {
						"nullable": true,
						"type": "string"
					},
					"isPaused": {
						"nullable": true,
						"type": "boolean"
					},
					"messageMetadata": {
						"nullable": true,
						"pattern": "^[ -~üöäÜÖÄß]{0,200}$",
						"type": "string"
					},
					"rules": {
						"items": {
							"$ref": "#/components/schemas/SubscriptionRuleDto"
						},
						"type": "array"
					}
				},
				"required": [
					"clientId",
					"rules"
				],
				"type": "object"
			},
			"UpsertServerSubscriptionRequest": {
				"additionalProperties": false,
				"properties": {
					"clientId": {
						"pattern": "^[ -~]{0,50}$",
						"type": "string"
					},
					"description": {
						"nullable": true,
						"pattern": "^[ -~üöäÜÖÄß]{0,300}$",
						"type": "string"
					},
					"endpoint": {
						"$ref": "#/components/schemas/EndpointDto"
					},
					"equipmentNumber": {
						"pattern": "^((?!.*(&|<|>|\\\\|\\/|\\s))[ -~]){0,25}$",
						"type": "string"
					},
					"id": {
						"nullable": true,
						"type": "string"
					},
					"isPaused": {
						"nullable": true,
						"type": "boolean"
					},
					"messageMetadata": {
						"nullable": true,
						"pattern": "^[ -~üöäÜÖÄß]{0,200}$",
						"type": "string"
					},
					"rules": {
						"items": {
							"$ref": "#/components/schemas/SubscriptionRuleDto"
						},
						"type": "array"
					}
				},
				"required": [
					"clientId",
					"equipmentNumber",
					"rules"
				],
				"type": "object"
			},
			"WebSocketEndpointConfig": {
				"additionalProperties": false,
				"properties": {
					"uri": {
						"nullable": true,
						"type": "string"
					}
				},
				"type": "object"
			}
		},
		"securitySchemes": {
			"apiKeyHeader": {
				"in": "header",
				"name": "Ocp-Apim-Subscription-Key",
				"type": "apiKey"
			},
			"apiKeyQuery": {
				"in": "query",
				"name": "subscription-key",
				"type": "apiKey"
			}
		}
	},
	"info": {
		"title": "Notifications API",
		"version": "1.0"
	},
	"openapi": "3.0.1",
	"paths": {
		"/v1/clientsubscriptions": {
			"get": {
				"description": "Returns the list of client subscriptions by the clientId.",
				"operationId": "get-v1-clientsubscriptions-clientid-clientid",
				"parameters": [
					{
						"description": "The client identifier.",
						"in": "query",
						"name": "clientId",
						"schema": {
							"type": "string"
						}
					}
				],
				"responses": {
					"200": {
						"content": {
							"application/json": {
								"example": [
									{
										"clientId": "string",
										"createdAtUtc": "string",
										"equipmentNumber": "string",
										"id": "string",
										"isPaused": true,
										"messageMetadata": "string",
										"rules": [
											{
												"field": "string",
												"operator": "string",
												"value": "string"
											}
										],
										"updatedAtUtc": "string",
										"url": "string"
									}
								],
								"schema": {
									"items": {
										"$ref": "#/components/schemas/ClientSubscriptionResponse"
									},
									"type": "array"
								}
							}
						},
						"description": "Success"
					}
				},
				"summary": "Returns the list of client subscriptions by the clientId.",
				"tags": [
					"ClientSubscriptions"
				]
			},
			"put": {
				"description": "Creates or updates a client subscription.",
				"operationId": "put-v1-clientsubscriptions",
				"requestBody": {
					"content": {
						"application/json": {
							"example": {
								"clientId": "string",
								"equipmentNumber": "string",
								"id": "string",
								"isPaused": true,
								"messageMetadata": "string",
								"rules": [
									{
										"field": "string",
										"operator": "string",
										"value": "string"
									}
								]
							},
							"schema": {
								"$ref": "#/components/schemas/UpsertClientSubscriptionRequest"
							}
						}
					},
					"description": "A json body containing the properties of a new subscription."
				},
				"responses": {
					"200": {
						"content": {
							"application/json": {
								"example": {
									"clientId": "string",
									"createdAtUtc": "string",
									"equipmentNumber": "string",
									"id": "string",
									"isPaused": true,
									"messageMetadata": "string",
									"rules": [
										{
											"field": "string",
											"operator": "string",
											"value": "string"
										}
									],
									"updatedAtUtc": "string",
									"url": "string"
								},
								"schema": {
									"$ref": "#/components/schemas/ClientSubscriptionResponse"
								}
							}
						},
						"description": "Success"
					},
					"400": {
						"content": {
							"application/json": {
								"example": {
									"errors": [
										{
											"message": "string",
											"source": "string"
										}
									],
									"traceId": "string"
								},
								"schema": {
									"$ref": "#/components/schemas/ErrorResponse"
								}
							}
						},
						"description": "Bad Request"
					}
				},
				"servers": [
					{
						"url": "http://notification.eos-dns-test.internal"
					}
				],
				"summary": "Creates or updates a client subscription.",
				"tags": [
					"ClientSubscriptions"
				]
			}
		},
		"/v1/clientsubscriptions/{id}": {
			"delete": {
				"description": "Delete the client subscription.",
				"operationId": "delete-v1-clientsubscriptions-id",
				"parameters": [
					{
						"description": "The subscription identifier.",
						"in": "path",
						"name": "id",
						"required": true,
						"schema": {
							"type": "string"
						}
					}
				],
				"responses": {
					"204": {
						"description": "Success"
					},
					"404": {
						"content": {
							"application/json": {
								"example": {
									"errors": [
										{
											"message": "string",
											"source": "string"
										}
									],
									"traceId": "string"
								},
								"schema": {
									"$ref": "#/components/schemas/ErrorResponse"
								}
							}
						},
						"description": "Not Found"
					}
				},
				"summary": "Delete the client subscription.",
				"tags": [
					"ClientSubscriptions"
				]
			}
		},
		"/v1/clientsubscriptions/{subscriptionId}": {
			"get": {
				"description": "Returns the client subscription by the subscription identifier.",
				"operationId": "627e36d220946866fb06db56",
				"parameters": [
					{
						"in": "path",
						"name": "subscriptionId",
						"required": true,
						"schema": {
							"type": ""
						}
					},
					{
						"description": "The client identifier.",
						"in": "query",
						"name": "clientId",
						"schema": {
							"type": "string"
						}
					}
				],
				"responses": {
					"200": {
						"content": {
							"application/json": {
								"example": [
									{
										"clientId": "string",
										"createdAtUtc": "string",
										"equipmentNumber": "string",
										"id": "string",
										"isPaused": true,
										"messageMetadata": "string",
										"rules": [
											{
												"field": "string",
												"operator": "string",
												"value": "string"
											}
										],
										"updatedAtUtc": "string",
										"url": "string"
									}
								],
								"schema": {
									"items": {
										"$ref": "#/components/schemas/ClientSubscriptionResponse"
									},
									"type": "array"
								}
							}
						},
						"description": "Success"
					}
				},
				"summary": "Returns the client subscription by the subscription identifier."
			}
		},
		"/v1/eventhandler": {
			"options": {
				"description": "WebPubSub options",
				"operationId": "webpubsub-options",
				"responses": {
					"200": {
						"description": "null"
					}
				},
				"summary": "WebPubSub options"
			},
			"post": {
				"description": "WebPubSub eventhandler",
				"operationId": "webpubsub-eventhandler",
				"responses": {
					"200": {
						"description": "null"
					}
				},
				"summary": "WebPubSub eventhandler"
			}
		},
		"/v1/serversubscriptions": {
			"get": {
				"description": "Returns the list of server subscriptions by the clientId.",
				"operationId": "get-v1-serversubscriptions-clientid-clientid",
				"parameters": [
					{
						"description": "The client identifier.",
						"in": "query",
						"name": "clientId",
						"schema": {
							"type": "string"
						}
					}
				],
				"responses": {
					"200": {
						"content": {
							"application/json": {
								"example": [
									{
										"clientId": "string",
										"createdAtUtc": "string",
										"description": "string",
										"endpoint": {
											"webSocket": {
												"uri": "string"
											}
										},
										"equipmentNumber": "string",
										"id": "string",
										"isPaused": true,
										"messageMetadata": "string",
										"rules": [
											{
												"field": "string",
												"operator": "string",
												"value": "string"
											}
										],
										"updatedAtUtc": "string"
									}
								],
								"schema": {
									"items": {
										"$ref": "#/components/schemas/SubscriptionDto"
									},
									"type": "array"
								}
							}
						},
						"description": "Success"
					}
				},
				"summary": "Returns the list of server subscriptions by the clientId.",
				"tags": [
					"ServerSubscriptions"
				]
			},
			"put": {
				"description": "Creates or updates a server subscription.",
				"operationId": "put-v1-serversubscriptions",
				"requestBody": {
					"content": {
						"application/json": {
							"example": {
								"clientId": "string",
								"description": "string",
								"endpoint": {
									"webSocket": {
										"uri": "string"
									}
								},
								"equipmentNumber": "string",
								"id": "string",
								"isPaused": true,
								"messageMetadata": "string",
								"rules": [
									{
										"field": "string",
										"operator": "string",
										"value": "string"
									}
								]
							},
							"schema": {
								"$ref": "#/components/schemas/UpsertServerSubscriptionRequest"
							}
						}
					},
					"description": "A json body containing the properties of a new subscription."
				},
				"responses": {
					"200": {
						"content": {
							"application/json": {
								"example": {
									"clientId": "string",
									"createdAtUtc": "string",
									"description": "string",
									"endpoint": {
										"webSocket": {
											"uri": "string"
										}
									},
									"equipmentNumber": "string",
									"id": "string",
									"isPaused": true,
									"messageMetadata": "string",
									"rules": [
										{
											"field": "string",
											"operator": "string",
											"value": "string"
										}
									],
									"updatedAtUtc": "string"
								},
								"schema": {
									"$ref": "#/components/schemas/SubscriptionDto"
								}
							}
						},
						"description": "Success"
					},
					"400": {
						"content": {
							"application/json": {
								"example": {
									"errors": [
										{
											"message": "string",
											"source": "string"
										}
									],
									"traceId": "string"
								},
								"schema": {
									"$ref": "#/components/schemas/ErrorResponse"
								}
							}
						},
						"description": "Bad Request"
					}
				},
				"summary": "Creates or updates a server subscription.",
				"tags": [
					"ServerSubscriptions"
				]
			}
		},
		"/v1/serversubscriptions/{id}": {
			"delete": {
				"description": "Delete the server subscription.",
				"operationId": "delete-v1-serversubscriptions-id",
				"parameters": [
					{
						"description": "The subscription identifier.",
						"in": "path",
						"name": "id",
						"required": true,
						"schema": {
							"type": "string"
						}
					}
				],
				"responses": {
					"204": {
						"description": "Success"
					},
					"404": {
						"content": {
							"application/json": {
								"example": {
									"errors": [
										{
											"message": "string",
											"source": "string"
										}
									],
									"traceId": "string"
								},
								"schema": {
									"$ref": "#/components/schemas/ErrorResponse"
								}
							}
						},
						"description": "Not Found"
					}
				},
				"summary": "Delete the server subscription.",
				"tags": [
					"ServerSubscriptions"
				]
			}
		},
		"/v1/serversubscriptions/{subscriptionId}": {
			"get": {
				"description": "Returns the server subscription by the subscription identifier.",
				"operationId": "627e376e899783a4b16184fe",
				"parameters": [
					{
						"in": "path",
						"name": "subscriptionId",
						"required": true,
						"schema": {
							"type": ""
						}
					},
					{
						"description": "The client identifier.",
						"in": "query",
						"name": "clientId",
						"schema": {
							"type": "string"
						}
					}
				],
				"responses": {
					"200": {
						"content": {
							"application/json": {
								"example": [
									{
										"clientId": "string",
										"createdAtUtc": "string",
										"equipmentNumber": "string",
										"id": "string",
										"isPaused": true,
										"messageMetadata": "string",
										"rules": [
											{
												"field": "string",
												"operator": "string",
												"value": "string"
											}
										],
										"updatedAtUtc": "string",
										"url": "string"
									}
								],
								"schema": {
									"items": {
										"$ref": "#/components/schemas/ClientSubscriptionResponse"
									},
									"type": "array"
								}
							}
						},
						"description": "Success"
					}
				},
				"summary": "Returns the server subscription by the subscription identifier."
			}
		}
	},
	"security": [
		{
			"apiKeyHeader": []
		},
		{
			"apiKeyQuery": []
		}
	],
	"servers": [
		{
			"url": "http://test.com"
		}
	]
}

I’m trying to parse a json file, take all the “operationId” that it has, and substitute it in the deployment script in APIm. But I can’t seem to parse it correctly. Can you suggest where I’m making a mistake?
Thank you in advance!

I tend to just through some extra Write-Output statements in to see what is stored in variables. Something may not be quite in the format you’re expecting.

Petro,
Welcome to the forum. :wave:t3:

Your post is hard to read. It is hard to distinguish between text and code and the code is actually broken because of line breaks. Please go back, edit your post again and fix the formatting of your code.

When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

How to format code in PowerShell.org 1 <---- Click :point_up_2:t4: :wink:

1 Like

Your JSON example is actually broken or incomplete. And with this small excerpt it is nearly impossible to recommend something meaningful. In general you can access JSON subnodes with the so called dot notation.

Sample input:

{
    "openapi": "3.0.1",
    "paths": {
        "/v1/test": {
            "get": {
                "description": "test.",
                "operationId": "test1",
                "parameters": [
                    {
                        "description": "test.",
                        "in": "query",
                        "name": "clientId",
                        "schema": {
                            "type": "string"
                        }
                    }
                ]
            }
        }
    }
}

Code to output the value of operationId:

$operationIds = 
    Get-Content -Path .\OpenAPISpecification.json | ConvertFrom-Json 
$operationIds.paths.'/v1/test'.get.operationId

The ouput would be

test1

Thank you for reply. I am update my json file. I will try to parse all operation id, not only one

This might be helpful :
https://topanswers.xyz/powershell?q=930

Using the function Get-PropertyValues from @PeterVandivier from this site should bring you close to what you need … if I got it right. :wink:

$operationIds = 
    Get-Content -Path .\OpenAPISpecification.json | ConvertFrom-Json 

$operationIds | 
    Get-PropertyValues | 
        Where-Object -Property Path -Like -Value '*operationId'

The output looks like this:

Path                                                              Value
----                                                              -----
.paths.'/v1/clientsubscriptions'.get.operationId                  get-v1-clientsubscriptions-clientid-clientid     
.paths.'/v1/clientsubscriptions'.put.operationId                  put-v1-clientsubscriptions
.paths.'/v1/clientsubscriptions/{id}'.delete.operationId          delete-v1-clientsubscriptions-id
.paths.'/v1/clientsubscriptions/{subscriptionId}'.get.operationId 627e36d220946866fb06db56
.paths.'/v1/eventhandler'.options.operationId                     webpubsub-options
.paths.'/v1/eventhandler'.post.operationId                        webpubsub-eventhandler
.paths.'/v1/serversubscriptions'.get.operationId                  get-v1-serversubscriptions-clientid-clientid     
.paths.'/v1/serversubscriptions'.put.operationId                  put-v1-serversubscriptions
.paths.'/v1/serversubscriptions/{id}'.delete.operationId          delete-v1-serversubscriptions-id
.paths.'/v1/serversubscriptions/{subscriptionId}'.get.operationId 627e376e899783a4b16184fe

this script solved my problem:

$operationIds = Get-Content myjson.json -Raw |
    Select-String -pattern '"operationId":\s*"?([^",]+)"?,?' -allmatches |
        Foreach-Object { $_.Matches |
            Foreach-Object { $_.Groups[1].Value }
        }
foreach ($operationId in $operationIds) {
    Set-AzApiManagementPolicy -Context $apimContext -ApiId $ApiId -OperationId "$operationId" -PolicyFilePath "$operationId.xml" -Format application/vnd.ms-azure-apim.policy.raw+xml
}