Extract data from json using powershell - powershell

I executing below command using strem from powershell and I am getting response in form of json using the below code
$session = New-SSHSession -ComputerName $S_1 -Credential $cred
$Strem = New-SSHShellStream -SSHSession $Session
$cmd_4 = $Strem.WriteLine("shell.connect('USER#X92SL224XXX2XX:3306')")
sleep -Seconds 5
$Strem.read()
$pass = $Strem.WriteLine("password")
sleep -Seconds 5
$Strem.read()
$cmd_5 = $Strem.WriteLine("var cluster = dba.getCluster('IBDCluster')")
sleep -Seconds 5
$Strem.read()
$cmd_6 = $Strem.WriteLine("cluster.status()")
sleep -Seconds 5
$ClusterStatus = $Strem.read()
[DBG]: PS C:\Windows\system32>>
cluster.status()
{
"clusterName": "IBDCluster",
"defaultReplicaSet": {
"name": "default",
"primary": "X92SL224XXX2XX:3306",
"ssl": "REQUIRED",
"status": "OK_NO_TOLERANCE",
"statusText": "Cluster is NOT tolerant to any failures. 1 member is not active.",
"topology": {
"X92SL224XXX1XX:3306": {
"address": "X92SL224XXXXXXX:3306",
"memberRole": "SECONDARY",
"mode": "R/O",
"readReplicas": {},
"role": "HA",
"status": "ONLINE",
"version": "5.7.36"
},
"X92SL224XXX2XX:3306": {
"address": "X92SL224XXX2XX:3306",
"memberRole": "PRIMARY",
"mode": "R/W",
"readReplicas": {},
"role": "HA",
"status": "ONLINE",
"version": "5.7.36"
},
"X92SL224XXXX3XX:3306": {
"address": "X92SL224XXX3XX:3306",
"instanceErrors": [
"ERROR: group_replication has stopped with an error."
],
"memberRole": "SECONDARY",
"memberState": "ERROR",
"mode": "R/O",
"readReplicas": {},
"role": "HA",
"status": "(MISSING)",
"version": "5.7.36"
}
},
"topologyMode": "Single-Primary"
},
"groupInformationSourceMember": "X92SL224XXXXXXX:3306"
}
[48;5;254m[38;5;23m My[0m[48;5;254m[38;5;166mSQL [0m[48;5;237m[38;5;15m X92SL224QDBA2DB:3306 ssl [0m[48;5;221m[38;5;0m JS [0m[48;5;0m> [0m
I need to fetch all the address, memberRole, memberState from the above data.
I was trying to convert from Json but getting error like
ConvertFrom-Json : Invalid JSON primitive: cluster.status.
Please let me know how to get the data from above

It looks like you simply need to remove the cluster.status() line that precedes the JSON text in the multi-line string that $Strem.Read() returns, as well as the extra line that follows it:
$ClusterStatus = $Strem.Read() -replace '^.+|.+$' | ConvertFrom-Json
Note: -replace '^.+|.+$' removes the first and last line from the input string, without also trying to remove a newline that follows / precedes them; however, these newlines are incidental whitespace that doesn't affect the operation of ConvertFrom-Json.

Related

fetch value from json using powershell

I have the below JSON which I am getting after executing certain commands
cluster.status()
{
"clusterName": "ICluster",
"defaultReplicaSet": {
"name": "default",
"primary": "?",
"ssl": "REQUIRED",
"status": "ERROR",
"statusText": "Cluster has no quorum as visible from 'X92A1DB:3306' and no ONLINE members that can be used to restore it. 3 members are not active.",
"topology": {
"X92A1DB:3306": {
"address": "X92A1DB:3306",
"instanceErrors": [
"ERROR: group_replication has stopped with an error."
],
"memberRole": "SECONDARY",
"mode": "R/O",
"readReplicas": {},
"role": "HA",
"status": "ERROR",
"version": "5.7.36"
},
"X92A2DB:3306": {
"address": "X92A2DB:3306",
"instanceErrors": [
"ERROR: split-brain! Instance is not part of the majority group, but has state ONLINE"
],
"memberRole": "SECONDARY",
"memberState": "ONLINE",
"mode": "R/O",
"readReplicas": {},
"role": "HA",
"status": "(MISSING)",
"version": "5.7.36"
},
"X92A3DB:3306": {
"address": "X92A3DB:3306",
"instanceErrors": [
"ERROR: split-brain! Instance is not part of the majority group, but has state ONLINE",
"WARNING: Instance is NOT a PRIMARY but super_read_only option is OFF."
],
"memberRole": "SECONDARY",
"memberState": "ONLINE",
"mode": "R/O",
"readReplicas": {},
"role": "HA",
"status": "(MISSING)",
"version": "5.7.36"
}
},
"topologyMode": "Single-Primary",
"warning": "The cluster description may be inaccurate as it was generated from an instance in Error state"
},
"groupInformationSourceMember": "X921DB:3306"
}
I need to identify the node name X92A1DB:3306 and having "status": "ERROR" or have to get "ERROR: group_replication has stopped with an error."
Based on which I need to execute further commands.
Below is the code using which I am getting the above output (output of Cluster.status())
$NewServerList=#()
$GetServerData = #(Import-Csv -Path "E:\MySQL_Cluster\NONPRODServerDetails.csv")
foreach($S_List in $GetServerData)
{
$S_1 = $S_List.IP
$session = New-SSHSession -ComputerName $S_1 -Credential $Mysqlcred
$Strem = New-SSHShellStream -SSHSession $Session
$cmd_1 = $Strem.WriteLine("sudo su - mysql")
sleep -Seconds 5
$Strem.read()
$cmd_5 = $Strem.WriteLine("var cluster = dba.getCluster('ICluster')")
sleep -Seconds 5
$IBCL = $Strem.read()
Write-Host $IBCL
$statustowrite = $Strem.WriteLine("cluster.status()")
sleep -Seconds 5
"Initial Cluster Status"| Out-File -FilePath $OutputFile -Force -Append
"==============================================="|Out-File -FilePath $OutputFile -Force -Append
$Strem.Read() | Out-File -FilePath $OutputFile -Force -Append
"==============================================="| Out-File -FilePath $OutputFile -Force -Append
}
Please let me know how to get it.
This should work
(Get-Content "path_to_json" | Select-Object -Skip 1) | ConvertFrom-Json

Extract value from json using powershell

I am having the below json
{
"clusterName": "IBDCluster",
"defaultReplicaSet": {
"name": "default",
"primary": "X92SL224XXX2XX:3306",
"ssl": "REQUIRED",
"status": "OK_NO_TOLERANCE",
"statusText": "Cluster is NOT tolerant to any failures. 1 member is not active.",
"topology": {
"X92SL224XXX1XX:3306": {
"address": "X92SL224XXXXXXX:3306",
"memberRole": "SECONDARY",
"mode": "R/O",
"readReplicas": {},
"role": "HA",
"status": "ONLINE",
"version": "5.7.36"
},
"X92SL224XXX2XX:3306": {
"address": "X92SL224XXX2XX:3306",
"memberRole": "PRIMARY",
"mode": "R/W",
"readReplicas": {},
"role": "HA",
"status": "ONLINE",
"version": "5.7.36"
},
"X92SL224XXXX3XX:3306": {
"address": "X92SL224XXX3XX:3306",
"instanceErrors": [
"ERROR: group_replication has stopped with an error."
],
"memberRole": "SECONDARY",
"memberState": "ERROR",
"mode": "R/O",
"readReplicas": {},
"role": "HA",
"status": "(MISSING)",
"version": "5.7.36"
}
},
"topologyMode": "Single-Primary"
},
"groupInformationSourceMember": "X92SL224XXXXXXX:3306"
}
I need to extract value like memberRole, status from the topology section.
when I go to the topology part
$ClusterDetails = $ClusterStatus.defaultReplicaSet.topology
the $ClusterDetails have value like (data visible only for 2 servers but all 3 servers are present)
PS C:\Windows\system32> $ClusterDetails
X92SL224XXXX1XX:3306 X92SL224XXXX2XX:3306
-------------------- --------------------
#{address=X92SL224XXXX1XX:3306; memberRole=SECONDARY; mode=R/O; readReplicas=; role=HA; status=ONLINE; version=5.7.36} #{address=X92SL224XXXX2XX:3306; memberRole=PRIM...
from shell I am able to see the individual output if i select like
PS C:\Windows\system32> $ClusterDetails.'X92SL224XXXX1XX:3306'
address : X92SL224XXXX1XX:3306
memberRole : PRIMARY
mode : R/W
readReplicas :
role : HA
status : ONLINE
version : 5.7.36
I need help to fetch the data from $ClusterDetails for individual servers like above but not getting how to get that dot part via script. please let me know how to do that.
Quite a long statement but this should work:
$json.defaultReplicaSet.topology.PSObject.Properties.Value | Select-Object memberRole, status
# Results in:
memberRole status
---------- ------
SECONDARY ONLINE
PRIMARY ONLINE
SECONDARY (MISSING)
You can access the Values of each Property of the Object in $json.defaultReplicaSet.topology accessing the PSObject Properties.
It's worth noting that .PSObject.Properties.Value works to enumerate all Property Values at once due to Member-Access Enumeration.
The same can be accomplished using a loop, for example:
foreach($property in $json.defaultReplicaSet.topology.PSObject.Properties) {
[pscustomobject]#{
ThisProperty = $property.Name
memberRole = $property.Value.memberRole
status = $property.Value.status
}
}

Powershell Iterate through multidimensional array of hashtables to find a match and combine values from both arrays

I need to combine values from 2 JSONs:
If there is a match in alerts IDs, I need to create structure, that will take data from both jsons
Result for a match should look like:
$array = #()
$hashtable = #{}
$hashtable.AlertID (does not matter what JSON is it from)
$hashtable.Tags (from JSON 1)
$hashtable.IncidentName (from JSON2)
$hashtable.IncidentID (from JSON2)
$array += $hashtable
I would prefer if this would be done with c style powershell loop.
c style for loop = for ($x = 0; $x -array.count; $x++)
JSON 1:
[
{
"Status": "Active",
"IncidentId": "3",
"tags": "SINC0008009",
"AlertId": [
"da637563185629568182_-638872186",
"da637563185631732095_1120592736",
"da637563185706412029_-614525914",
"da637563185760439486_-276692370",
"da637563185856325888_-1949235651",
"da637563186785996176_2128073884",
"da637563186789897000_1239551047",
"da637563186806513555_1512241399",
"da637563193194338043_-244132089"
],
"severity": "Medium"
},
{
"Status": "Active",
"IncidentId": "4",
"tags": "SINC0008008",
"AlertId": [
"da637643650725801726_1735022501",
"da637643650741237104_1473290917",
"da637643650748739479_-40211355",
"da637643652767933265_-1887823168",
"da637643670830160376_-443360743"
],
"severity": "Medium"
},
{
"Status": "Active",
"IncidentId": "2",
"tags": null,
"AlertId": [
"caD76232A5-F386-3C5D-94CD-7C82A7F778DC"
],
"severity": "Medium"
},
{
"Status": "Active",
"IncidentId": "1",
"tags": null,
"AlertId": [
"ca6534FF45-D62A-3FB7-BD6B-FF5029C553DB"
],
"severity": "Medium"
}
]
JSON 2:
{
"value": [
{
"incidentId": 3,
"incidentName": "Multi-stage incident involving Initial access & Discovery on one endpoint",
"status": "Active",
"severity": "Medium",
"tags": ["SINC0000001"],
"comments": [],
"alerts": [
{
"alertId": "da637563185629568182_-638872186",
"incidentId": 3,
"description": "A suspicious PowerShell activity was observed on the machine. ",
"status": "New",
"severity": "Medium",
"devices": [
{
"deviceDnsName": "xxxxx"
}
],
"entities": [
{
"entityType": "User",
"accountName": "xxxxxx",
"userPrincipalName": "xxx#xx.xx"
},
{
"entityType": "Process"
},
{
"entityType": "Process",
"verdict": "Suspicious"
},
{
"entityType": "File"
}
]
},
{
"alertId": "da637563185631732095_1120592736",
"incidentId": 3,
"devices": [
{
"osPlatform": "Windows10",
"version": "1909"
}
],
"entities": [
{
"entityType": "User",
"remediationStatus": "None"
}
]
}
]
},
{
"incidentId": 4,
"incidentName": "Multi-stage incident involving Initial access & Discovery on one endpoint",
"status": "Active",
"severity": "Medium",
"tags": ["SINC0000002"],
"comments": [],
"alerts": [
{
"alertId": "da637563185629568182_-638872186",
"incidentId": 3,
"description": "A suspicious PowerShell activity was observed on the machine. ",
"status": "New",
"severity": "Medium",
"devices": [
{
"deviceDnsName": "xxxxx"
}
],
"entities": [
{
"entityType": "User",
"accountName": "xxxxxx",
"userPrincipalName": "xxx#xx.xx"
},
{
"entityType": "Process"
},
{
"entityType": "Process",
"verdict": "Suspicious"
},
{
"entityType": "File"
}
]
},
{
"alertId": "da637563185631732095_1120592736",
"incidentId": 3,
"devices": [
{
"osPlatform": "Windows10",
"version": "1909"
}
],
"entities": [
{
"entityType": "User",
"remediationStatus": "None"
}
]
}
]
}
]
}
Till now, I was looking into using nested foreach loop to address it but it does not behave like I want. I am looking for for loop as I could use the indexes.
Instead of creating an array of Hashtables, I think it's better to create an array of PsCustomObjects, because outputting the result to console/file/json would be a lot easier then.
$json1 = Get-Content -Path 'X:\json1.json' -Raw | ConvertFrom-Json
$json2 = Get-Content -Path 'X:\json2.json' -Raw | ConvertFrom-Json
$result = foreach ($incident in $json1) {
foreach ($alertId in $incident.AlertId) {
$json2.value | Where-Object { $_.alerts.alertId -eq $alertId } | ForEach-Object {
# output an object with the wanted properties
[PsCustomObject]#{
AlertID = $alertId # from json1
Tags = $incident.Tags # from json1
IncidentName = $_.incidentName # from json2
IncidentID = $_.incidentId # from json2
}
}
}
}
# output on screen
$result | Format-Table -AutoSize # or use Out-GridView
# output to new JSON
$result | ConvertTo-Json
# output to CSV file
$result | Export-Csv -Path 'X:\incidents.csv' -NoTypeInformation
Using your examples, the output to console window is:
AlertID Tags IncidentName IncidentID
------- ---- ------------ ----------
da637563185629568182_-638872186 SINC0008009 Multi-stage incident involving Initial access & Discovery on one endpoint 3
da637563185629568182_-638872186 SINC0008009 Multi-stage incident involving Initial access & Discovery on one endpoint 4
da637563185631732095_1120592736 SINC0008009 Multi-stage incident involving Initial access & Discovery on one endpoint 3
da637563185631732095_1120592736 SINC0008009 Multi-stage incident involving Initial access & Discovery on one endpoint 4

deploying webapp in azure devops pipeline release w powershell / json templates - error - modal dialog box is not valid

#Using Azure DevOps pipeline release with a powershell script and a json template file and json parameter #file. Note-authenticating to the azure portal requires multi factor authentication (ie.authenticator on my mobile)
#'ERROR- >>>>> <strong>"Showing a modal dialog box or form when the application is not running in #UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly #style to display a notification from a service application."</strong>
#(Note- Bottom of logs immediately below contains this modal error.)'
2020-11-14T20:33:38.7159389Z ##[section]Starting: WebApp_Create01
2020-11-14T20:33:38.7499602Z ==============================================================================
2020-11-14T20:33:38.7499865Z Task : Azure PowerShell
2020-11-14T20:33:38.7499927Z Description : Run a PowerShell script within an Azure environment
2020-11-14T20:33:38.7499981Z Version : 3.1.28
2020-11-14T20:33:38.7500050Z Author : Microsoft Corporation
2020-11-14T20:33:38.7500132Z Help : https://learn.microsoft.com/azure/devops/pipelines/tasks/deploy/azure-powershell
2020-11-14T20:33:38.7500215Z ==============================================================================
2020-11-14T20:33:40.5542183Z ##[command]Import-Module -Name C:\Program Files\WindowsPowerShell\Modules\AzureRM\6.13.1\AzureRM.psd1 -Global
2020-11-14T20:33:54.9421385Z ##[command]Clear-AzureRmContext -Scope Process
2020-11-14T20:33:55.3824175Z ##[command]Disable-AzureRmContextAutosave -ErrorAction Stop
2020-11-14T20:33:56.1766169Z ##[command]Add-AzureRMAccount -ServicePrincipal -Tenant *** -Credential System.Management.Automation.PSCredential -Environment AzXXXXXXXXXXXXXnt #processScope
2020-11-14T20:33:57.8815316Z ##[command] Select-AzureRMSubscription -SubscriptionId c27XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX2 -TenantId ***
2020-11-14T20:33:58.5484671Z ##[command]& 'C:\agent\Workfolder_CloudUiPathAgent03\_temp\939d1XXXXXXXXXXXXXXXXXXXXXXXX2127.ps1'
2020-11-14T20:33:58.7424214Z ##[command]Disconnect-AzureRmAccount -Scope Process -ErrorAction Stop
2020-11-14T20:33:59.1018440Z ##[command]Clear-AzureRmContext -Scope Process -ErrorAction Stop
<strong>2020-11-14T20:33:59.7603535Z ##[error]Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.</strong>
2020-11-14T20:33:59.8133689Z ##[section]Finishing: WebApp_Create01
<br>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#The immediately below is the ps1 pasted into the section for the "Inline" script. Pipeline was #created as "Azure Powershell":
Connect-AzureRmAccount -Environment AzXXXXXXXXXXXXXnt -TenantId '410XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXf1d' -Force
Select-AzureRmSubscription -Subscription "c271XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX832"
# Tried both Connect-AzureRmAccount and Login-AzureRmAccount without any success?
#Login-AzureRmAccount -Environment AzXXXXXXXXXXXXXt | Out-Null
#Select-AzureRmSubscription -Subscription "c271XXXXXXXXXXXXXXXXXXXXXXXXX832" | Out-Null
<br>
# Deploy App Service Plan, Web App & Deployment Slots
$DeploymentParametersBuildVM = #{
ResourceGroupName = 'DXXXXXXXXXXXXXXXXXXXXXXXXamic'
TemplateUri = 'https://dXXXXXXXXXXXXXXXXX.blob.core.XXXXXcloudapi.net/blob-uXXXXXXXXXXXXXXXXXXXXXXXXX7/webappcreate.json'
TemplateParameterFile = "https://XXXXXXXXXXXXXapi.net/blob-uXXXXXXXXXXXXXXXXXXXXXXXXX7/webappcreate.parameters.json"
Verbose = $true
webAppName = 'uXXXXXXXXXXXXXXXXXXXXXXXXXXX7'
hostingPlanName = 'WebXXXXXXXXXXXXXXXXXXXXXX01'
templateSasToken = 'mtAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXpSTQ=='
subscriptionId = 'c271XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX832'
name = 'uXXXXXXXXXXXXXXXXXXXXX7'
location = 'UXXXXXXXXXXXXXXX'
serverFarmResourceGroup = 'DXXXXXXXXXXXXXXXXXXXXXXXXamic'
Tenantid = '410XXXXXXXXXXXXXXXXXXXXXXXXXXXf1d'
alwaysOn = 'off'
sku = 'Free'
skuCode = 'F1'
workerSize = '0'
workerSizeId = '0'
numberOfWorkers = '1'
currentStack = 'dotnet'
phpVersion = 'OFF'
appInsightValue = 'uXXXXXXXXXXXXXXXXXXXXXXo7Insight'
netFrameworkVersion = 'v4.0'
azureAccountPassword = '12XXXXXXXXXXXXXXXXXditto'
accountid = 'a183XXXXXXXXXXXXXXXXXXXXXXXXXXXXX68fa'
Credential = '12XXXXXXXXXXXXXXXXXditto'
ServicePrincipal = '_MV_XXXXXXXXXXXXXXXXXXXXXXXXXXXX9~1e'
}
# DEPLOY
New-AzureRmResourceGroupDeployment #DeploymentParametersBuildVM
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#webapp.parameters.json (this is the azure webapp "parameter" json immediately below):
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"subscriptionId": {
"value": "c271XXXXXXXXXXXXXXXXXXXXXXXXXXXXX832"
},
"name": {
"value": "uXXXXXXXXXXXXXXXXXXX7"
},
"location": {
"value": "UXXXXXXXXXXXXXX"
},
"hostingPlanName": {
"value": "WebXXXXXXXXXXXXXXXXXXX01"
},
"serverFarmResourceGroup": {
"value": "DXXXXXXXXXXXXXXXXXXXic"
},
"alwaysOn": {
"value": "true"
},
"sku": {
"value": "Free"
},
"skuCode": {
"value": "F1"
},
"workerSize": {
"value": "0"
},
"workerSizeId": {
"value": "0"
},
"numberOfWorkers": {
"value": "1"
},
"currentStack": {
"value": "dotnet"
},
"phpVersion": {
"value": "OFF"
},
"appInsightValue": {
"value": "uXXXXXXXXXXXXXXXXXX7Insight"
},
"netFrameworkVersion": {
"value": "v4.0"
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#webappacreate.json (this is the azure webapp "template" json immediately below)
{
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"subscriptionId": {
"type": "string"
},
"name": {
"type": "string"
},
"location": {
"type": "string"
},
"hostingPlanName": {
"type": "string"
},
"serverFarmResourceGroup": {
"type": "string"
},
"alwaysOn": {
"type": "bool"
},
"sku": {
"type": "string"
},
"skuCode": {
"type": "string"
},
"workerSize": {
"type": "string"
},
"workerSizeId": {
"type": "string"
},
"numberOfWorkers": {
"type": "string"
},
"currentStack": {
"type": "string"
},
"phpVersion": {
"type": "string"
},
"appInsightValue": {
"type": "string"
},
"netFrameworkVersion": {
"type": "string"
}
},
"variables": {
"appInsightName": "[concat('microsoft.insights/components/',parameters('appInsightValue'))]"
},
"resources": [
{
"apiVersion": "2018-11-01",
"name": "[parameters('name')]",
"type": "Microsoft.Web/sites",
"location": "[parameters('location')]",
"tags": {},
"dependsOn": [
"[concat('microsoft.insights/components/',parameters('appInsightValue'))]",
"[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
],
"properties": {
"name": "[parameters('name')]",
"siteConfig": {
"appSettings": [
{
"name": "APPINSIGHTS_INSTRUMENTATIONKEY",
"value": "[reference(variables('appInsightName'), '2015-05-01').InstrumentationKey]"
},
{
"name": "APPLICATIONINSIGHTS_CONNECTION_STRING",
"value": "[reference(variables('appInsightName'), '2015-05-01').ConnectionString]"
},
{
"name": "ApplicationInsightsAgent_EXTENSION_VERSION",
"value": "~2"
},
{
"name": "XDT_MicrosoftApplicationInsights_Mode",
"value": "default"
}
],
"metadata": [
{
"name": "CURRENT_STACK",
"value": "[parameters('currentStack')]"
}
],
"phpVersion": "[parameters('phpVersion')]",
"netFrameworkVersion": "[parameters('netFrameworkVersion')]",
"alwaysOn": "[parameters('alwaysOn')]"
},
"serverFarmId": "[concat('/subscriptions/', parameters('subscriptionId'),'/resourcegroups/', parameters('serverFarmResourceGroup'), '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
"clientAffinityEnabled": true
}
},
{
"apiVersion": "2018-11-01",
"name": "[parameters('hostingPlanName')]",
"type": "Microsoft.Web/serverfarms",
"location": "[parameters('location')]",
"kind": "",
"tags": {},
"dependsOn": [],
"properties": {
"name": "[parameters('hostingPlanName')]",
"workerSize": "[parameters('workerSize')]",
"workerSizeId": "[parameters('workerSizeId')]",
"numberOfWorkers": "[parameters('numberOfWorkers')]"
},
"sku": {
"Tier": "[parameters('sku')]",
"Name": "[parameters('skuCode')]"
}
},
{
"apiVersion": "2015-05-01",
"name": "[parameters('appInsightValue')]",
"type": "microsoft.insights/components",
"location": "[parameters('location')]",
"tags": {},
"properties": {
"ApplicationId": "[parameters('name')]",
"Request_Source": "IbizaWebAppExtensionCreate"
}
}
]
}
According to the error message, it seems you need to set the options of MessageBox.Show to either ServiceNotification or DefaultDesktopOnly. You can try the workaround provided in this ticket: adding MessageBoxOptions.ServiceNotification
MessageBox.Show(msg, "Print Error", System.Windows.Forms.MessageBoxButtons.YesNo,
System.Windows.Forms.MessageBoxIcon.Error,
System.Windows.Forms.MessageBoxDefaultButton.Button1,
System.Windows.Forms.MessageBoxOptions.ServiceNotification);
But, MessageBox is for use within windows (as opposed to web) applications. It would attempt to open a message box on the server. Here is a ticket you can refer to.
Found out that no authentication was required for azure devops pipeline hence no login or connect is required. This got rid of the popup (modal error).
Next I checked with the azure devops person and he said to not use powershell in the pipeline.
He recommended "Azure Resource Group Deployment" option for the pipeline release. This does not require any initiation script but just a json template and a json parameter.
Thank You.

Cannot pass an array type parameter in ARM template via Powershell

I have an ARM Template with the following parameters:
"parameters": {
"projectName": {
"type": "string",
"metadata": {
"description": "Name of the project"
}
},
"environmentName": {
"type": "string",
"defaultValue": "testing",
"metadata": {
"description": "Name/Type of the environment"
}
},
"vmResourceGroupName": {
"type": "string",
"metadata": {
"description": "Resource Group in which VMs wil be deployed"
}
},
"vmName": {
"type": "string",
"metadata": {
"description": "Name of the Virtual Machine"
}
},
"vmIPAddress": {
"type": "string",
"metadata": {
"description": "IP Address of the Virtual Machine"
}
},
"osDiskVhdUri": {
"type": "string",
"metadata": {
"description": "Uri of the existing VHD in ARM standard or premium storage"
}
},
"dataDiskVhdUri": {
"type": "array",
"metadata": {
"description": "Uri of the existing VHD in ARM standard or premium storage"
}
},
"vmSize": {
"type": "string",
"metadata": {
"description": "Size of the Virtual Machine"
}
},
"osType": {
"type": "string",
"allowedValues": [
"Windows",
"Linux"
],
"metadata": {
"description": "OS of the VM - Typically Windows or Linux"
}
},
"ManagedDisk": {
"type": "string",
"allowedValues": [
"Yes",
"No"
],
"metadata": {
"description": "Yes for Managed Disks, No for VHDs"
}
}
As evident, $dataDiskVHDURI is of type:array and I am trying to deploy the template using -TemplateParameterObject with New-AzureRMresourceGroupDeployment cmdlet in Powershell using the following code:
{
$vmWithDDTemplate = 'azuredeploy.json'
$vmWithoutDDTemplate = 'azuredeploy-withoutdd.json'
$dataDiskVhdUri = New-Object -TypeName System.Collections.ArrayList
$dataDiskVhdUri.Add("$VM.dataDiskVhduri")
#Creating VM param object
$VMTemplateObject = #{"projectname" = $projectName; `
"environmentname" = $environmentName; `
"vmResourceGroupName" = $vmResourceGroupName; `
"vmName" = $VM.vmName; `
"vmIPAddress" = $VM.vmIPAddress; `
"osDiskVhdUri" = $VM.osDiskVhdUri; `
"dataDiskVhdUri" = ,$dataDiskVhdUri; `
"vmSize" = $VM.vmSize; `
"osType" = $VM.osType; `
"ManagedDisk" = $VM.ManagedDisk
}
#$VMTemplateObject
# Checking if VM contains a data disk
if($VM.dataDiskVhdUri -ne $null)
{
Write Output "$VM contains data disk"
New-AzureRmResourceGroupDeployment -Name ('vmwithdd' + '-' + ((Get-Date).ToUniversalTime()).ToString('MMdd-HHmm')) `
-ResourceGroupName $ResourceGroupName `
-TemplateParameterObject $VMTemplateObject `
-TemplateFile $vmWithDDTemplate `
-Force -Verbose -ErrorVariable ErrorMessages `
-ErrorAction Stop -DefaultProfile $azureCred
}
else
{
Write-output '$VM does not contain data disk'
}
}
However, I get the following error every time:
Microsoft.PowerShell.Utility\Write-Error : 4:46:14 PM - Error:
Code=InvalidTemplate; Message=Deployment template validation failed:
'The provided value for the template parameter 'dataDiskVhdUri' at
line '44' and column '27' is not valid.'. At Create-Environment:73
char:73
+
+ CategoryInfo : NotSpecified: (:) [Write-Error], RemoteException
+ FullyQualifiedErrorId : System.Management.Automation.RemoteException,Microsoft.PowerShell.Commands.WriteErrorCommand
+ PSComputerName : [localhost]
Does anyone know how to resolve this?
Not sure, but maybe feeding it with an ArrayList object wrapped in an array by use of the preceeding , is not what it wants. If i lookup examples, i see only single values added there like "dataDiskVhdUri" = $VM.dataDiskVhduri;
Try this:
$OptionalParameters = New-Object -TypeName Hashtable
$OptionalParameters.Add("aParam", #(1,2,3))
New-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName `
-TemplateFile azuredeply.json `
#OptionalParameters
With:
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"aParam": {
"type": "array"
}
},
"variables": { },
"resources": [ ],
"outputs": {
"dump": {
"type": "array",
"value": "[parameters('aParam')]"
}
}
}