How to pass Json parameters to powershell script - json

I would like to pass Json data to Powershell script.
PowerShell script:
Get-AzMySqlFirewallRule -ResourceGroupName "dev" -ServerName "dev-DB-Server" | Out-File "file.json"
New-AzMySqlFirewallRule -Name “” -ResourceGroupName "dev" -ServerName "dev-core" -EndIPAddress "" -StartIPAddress ""
In the above powershell script I need to get values to "" from Json file mentioned below.So how to get Json parameter values during run time and all 3 parameters should be passed to the above command and so that it will create new firewall rule to new DB server.
Also, when I run the powershell command (Get-AzMySqlFirewallRule -ResourceGroupName "dev" -ServerName "dev-DB-Server" | Out-File "file.json") I am getting my Json file data in the below format.Not sure whether this format looks good but I need the below values start from pdbr_home,1.2.3.4 and 5.6.7.8 and similarly another 2 rows of data should be passed to my powershell command here New-AzMySqlFirewallRule -Name “” -ResourceGroupName "dev" -ServerName "dev-core" -EndIPAddress "" -StartIPAddress "". via for loop.
file.Json:
[
{
"EndIPAddress": "1.3.2.2",
"Id": "/subscriptions/abcdefg/resourceGroups/dev/providers/Microsoft.DBforMySQL/servers/db-dev- vm/firewallRules/praveen_Home",
"Name": "praveen_Home",
"StartIPAddress": "4.3.1.2",
"Type": "Microsoft.DBforMySQL/servers/firewallRules"
},
{
"EndIPAddress": "2.4.5.6",
"Id": "/subscriptions/abcdefg/resourceGroups/dev/providers/Microsoft.DBforMySQL/servers/db-dev- vm/firewallRules/pdbr_Home",
"Name": "pdbr_Home",
"StartIPAddress": "3.2.1.2",
"Type": "Microsoft.DBforMySQL/servers/firewallRules"
}
]
The below command output as follows.
PS /home/praveen> Get-Command json
CommandType Name Version Source
----------- ---- ------- ------
Cmdlet ConvertFrom-Json 7.0.0.0 Microsoft.PowerShell.Utility
Cmdlet ConvertTo-Json 7.0.0.0 Microsoft.PowerShell.Utility
Cmdlet Test-Json 7.0.0.0 Microsoft.PowerShell.Utility
Application json_pp 0.0.0.0 /usr/bin/json_pp
Application json_pp 0.0.0.0 /bin/json_pp
Error:
Error:
New-AzMySqlFirewallRule: /home/praveen/dbtest.ps1:21
Line |
21 | … -ServerName "praveen-dev" -EndIPAddress $entry.EndIPAddress -StartI …
| ~~~~~~~~~~~~~~~~~~~
| Cannot bind argument to parameter 'EndIPAddress' because it is an empty string.
Final solution worked for me now:
##################### Updating Firewall rules from Soiurce DB server to Target DB server ##################
Write-Host -NoNewline "Updating Firewall rules from Soiurce DB server to Target DB server"
Get-AzMySqlFirewallRule -ResourceGroupName $ResourceGroupName -ServerName $SourceDBServerName | Select-Object Name, StartIPaddress, EndIPaddress | Convertto-Json | Out-File "firewallrule.json"
foreach ($frule in (Get-Content firewallrule.json -raw | ConvertFrom-Json)) {
New-AzMySqlFirewallRule -Name $frule.Name -ResourceGroupName $ResourceGroupName -ServerName $TargetDBServerName -EndIPAddress $frule.EndIPAddress -StartIPAddress $frule.StartIPAddress
}

Use Convertto-Json before writing file.
Docs: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json?view=powershell-7.2
Get-AzMySqlFirewallRule -ResourceGroupName "dev" -ServerName "dev-DB-Server" | Convertto-Json | Out-File "file.json"
EDIT as requested:
Get-AzMySqlFirewallRule -ResourceGroupName "dev" -ServerName "dev-DB-Server" | Select-Object Name,"StartIP address", "EndIP address"| Convertto-Json | Out-File "file.json"
Another EDIT as requested (fixed my mistake - thank you #sage pourpre):
foreach ($entry in (Get-Content file.json -raw | ConvertFrom-Json) {
New-AzMySqlFirewallRule -name $entry.Name `
-ResourceGroupName "dev" `
-ServerName "dev-core" `
-StartIPAddress $entry.StartIPAddress `
-EndIPAddress $entry.EndIPAddress
}

try the below:
Get-AzMySqlFirewallRule -ResourceGroupName "dev" -ServerName "dev-DB-Server" | Convertto-Json | Out-File "file.json"
$data = Get-Content "C:\Users\me\file.json" | Out-String | ConvertFrom-Json #replace path to where you have exported the json file
foreach ($line in $data) {
New-AzMySqlFirewallRule -name $line.Name `
-ResourceGroupName "dev" `
-ServerName "dev-core" `
-StartIPAddress $line.StartIPAddress `
-EndIPAddress $line.EndIPAddress
}
A different method, although the question is for JSON, would be to just store the rules in a variable.
$rules = Get-AzMySqlFirewallRule -ResourceGroupName "dev" -ServerName "dev-DB-Server"
foreach ($rule in $rules){
New-AzMySqlFirewallRule -name $rule.Name `
-ResourceGroupName "dev" `
-ServerName "dev-core" `
-StartIPAddress $rule.StartIPAddress `
-EndIPAddress $rule.EndIPAddress
}

I was able to fix this solution with help of all the above inputs few days ago. Thanks to all.Really appreciated your help.
Updating Firewall rules from Source DB server to Target DB server
Write-Host -NoNewline "Updating Firewall rules from Soiurce DB server to Target DB server"
Get-AzMySqlFirewallRule -ResourceGroupName $ResourceGroupName -ServerName $SourceDBServerName | Select-Object Name, StartIPaddress, EndIPaddress | Convertto-Json | Out-File "firewallrule.json"
foreach ($frule in (Get-Content firewallrule.json -raw | ConvertFrom-Json)) {
New-AzMySqlFirewallRule -Name $frule.Name -ResourceGroupName $ResourceGroupName -ServerName $TargetDBServerName -EndIPAddress $frule.EndIPAddress -StartIPAddress $frule.StartIPAddress
}

//role-definition.json
{
"RoleName": "MyReadWriteRole",
"Type": "CustomRole",
"AssignableScopes": ["/"],
"Permissions": [{
"DataActions": [
"Microsoft.DocumentDB/databaseAccounts/readMetadata",
"Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*",
"Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*"
]
}]
}
Coverting it into json object as i need to pass it as an argument in a powershell parameter.
So i did below -
Created a powershell parameter
$roleDef= #"
{
"RoleName": "MyReadWriteRole",
"Type": "CustomRole",
"AssignableScopes": ["/"],
"Permissions": [{
"DataActions": [
"Microsoft.DocumentDB/databaseAccounts/readMetadata",
"Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/",
"Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/"
]
}]
}
"#
$jsonObject = $roleDef | ConvertFrom-Json
az cosmosdb sql role definition create --account-name cosmosdbaccname --resource-group 'my-rg' --body $jsonObject
but I get below error -
Failed to parse string as JSON:
#{RoleName=MyReadWriteRole; Type=CustomRole; AssignableScopes=System.Object[]; Permissions=System.Object[]}
Error detail: Expecting value: line 1 column 1 (char 0)

Related

Assign Value To Variable After Extracting From Json File Using Powershell

I have the below json file
{
"name": "ca",
"version": "5.2.0"
}
I am extracting the value of version and trying to assign it to a variable ver
$jsonString = Get-Content -Path ./package.json
$jsonObj = $jsonString | ConvertFrom-Json
echo $jsonObj.version
Write-Host "##vso[task.setvariable variable=ver]$jsonObj.version"
echo $ver
Below is the output
5.2.0
I am expecting the value to be printed twice and also get it assigned to the variable ver but it is not getting assigned
If you are trying to use it in builds, you will not see a new value in the same step. Additionally, use $($jsonObj.version) in the logging command:
steps:
- powershell: |
$jsonString = Get-Content -Path ./package.json
$jsonObj = $jsonString | ConvertFrom-Json
$jsonObj.version
Write-Host "##vso[task.setvariable variable=my.ver]$($jsonObj.version)"
displayName: 'Set vars'
- powershell: |
$ver = '$(my.ver)'
$ver
displayName: 'Read vars'

How to Get the values from json using powershell

Guys this is my JSON file and I want to create a PowerShell script which will give me result like
I have used method like Get-Content and other but there are some issues with the JSON parsing. Please find what is my requirement I have explained in details below.
MyLocalMachineHome
LocalMachine = Sahil_LocalMachine
Second_MyLocalMachine = Sahil_MylocalMachine
Second_MyLocalMachine = ""
Staging
Second_Staging = Sahil;_Secconf
Staging = Sahil_Staging
third_staging = stsajiii
There is also one functionality which I would like to have if I want to get only variables of "staging".
I was using this function Get-Content -Raw -Path E:\shell\Powershell\1ReleasePipelines.json | ConvertFrom-Json | select -ExpandProperty variables on my original JSON file but somehow there is some kind of limit in storing string which I was getting from this method.
{
"environments": [
{
"id": 3,
"name": "MyLocalMachineHome",
"variableGroups": [],
"variables": {
"LocalMachine": {
"value": "Sahil_LocalMachine"
},
"Second_MyLocalMachine": {
"value": "Sahil_MylocalMachine"
},
"thirf_mylocal": {
"value": ""
}
}
},
{
"id": 7,
"name": "Staging",
"variableGroups": [],
"variables": {
"Second_Staging": {
"value": "Sahil;_Secconf"
},
"Staging": {
"value": "Sahil_Staging"
},
"third_staging": {
"value": "stsajiii"
}
}
}
]
}
If we assume that $json contains your JSON content, you can do the following ugly code:
$environment = 'staging'
$j = $json | ConvertFrom-Json
($j.environments | where name -eq $environment).variables | Foreach-Object {
$CurrentObject = $_
$CurrentObject | Get-Member -MemberType NoteProperty |
Select-Object -Expand Name | Foreach-Object {
$CurrentObject.$_.value
}
}
It appears your issue is that you don't know what variables are going to be contained within your JSON. So you can't easily use Select-Object variable or $object.variable. You need a dynamic approach.
If you know your variables ahead of time, things become simpler. You can store your variable names in an array and loop over them.
$variables = 'Second_Staging','Staging','third_staging'
$environment = 'staging'
$j = $json | ConvertFrom-Json
$jsonVars = ($j.environments | where name -eq $environment).variables
$variables | Foreach-Object {
$jsonVars.$_.value
}
View all the sub-properties of variables with format-list instead of format-table. Since the properties vary, format-table won't show all of them. There's a lot of sloppy object construction in json.
$a = get-content file.json
$a.environments.variables | format-table
LocalMachine Second_MyLocalMachine thirf_mylocal
------------ --------------------- -------------
#{value=Sahil_LocalMachine} #{value=Sahil_MylocalMachine} #{value=}
$a.environments.variables | format-list
LocalMachine : #{value=Sahil_LocalMachine}
Second_MyLocalMachine : #{value=Sahil_MylocalMachine}
thirf_mylocal : #{value=}
Second_Staging : #{value=Sahil;_Secconf}
Staging : #{value=Sahil_Staging}
third_staging : #{value=stsajiii}
Get the staging variables?
$a.environments | where name -eq staging | foreach variables
Second_Staging Staging third_staging
-------------- ------- -------------
#{value=Sahil;_Secconf} #{value=Sahil_Staging} #{value=stsajiii}
cls
start-transcript -path 'C:\E\Devops\PowerShell_Chapters\ABC.txt'
write-output "**********Variables of Release************"
get-content -raw -path 'C:\E\Devops\PowerShell_Chapters\Release.json'| Convertfrom-Json | Select -ExpandProperty variables
$json = get-content -raw -path 'C:\E\Devops\PowerShell_Chapters\Release.json'| Convertfrom-Json | Select -ExpandProperty environments
$EnvirnomentsVariables = get-content -raw -path 'C:\E\Devops\PowerShell_Chapters\Release.json'| Convertfrom-Json | Select -ExpandProperty environments |Select -ExpandProperty name
$ReleaseVariable = get-content -raw -path 'C:\E\Devops\PowerShell_Chapters\Release.json'| Convertfrom-Json | Select -ExpandProperty environments |Select -ExpandProperty variables
$i = 0
foreach($a in $EnvirnomentsVariables)
{
$ABC_Staging = $EnvirnomentsVariables[$i]
#write-output $ABC_Staging
if( $ABC_Staging -match "ABC Staging")
{
write-output "****************Variables of " $EnvirnomentsVariables[$i]*************"
#add-content 'C:\E\Devops\PowerShell_Chapters\ABC.txt' $EnvirnomentsVariables[$i]
# Set-content -path 'C:\E\Devops\PowerShell_Chapters\Sahil.json'| ConvertTo-Json | select $EnvirnomentsVariables[$i]
write-output $ReleaseVariable[$i]
# add-content 'C:\E\Devops\PowerShell_Chapters\ABC.txt' $ReleaseVariable[$i]
# Set-content -path 'C:\E\Devops\PowerShell_Chapters\Sahil.json'| ConvertTo-Json | select $ReleaseVariable[$i]
}
$i = $i + 1
}
stop-transcript

Iterate over json Array using Power shell

This is what I have tried so far:
$Path="C:\Users\Desktop\test.json"
$json=(Get-Content $Path | ConvertFrom-Json).parameters.FileArray
//FileArray is array name in json file
$demo=$json.GetType().FullName //System.Object[]
foreach($file in Get-ChildItem "D:\A\DF\ls\" -Include $json|ForEach Object{$_} -Recurse){
Write-Output $file.BaseName
Write-Output $file.FullName
Set-AzureRmDataFactoryV2LinkedService -DataFactoryName "adfg1" - ResourceGroupName "bgc" -Name $file.BaseName -DefinitionFile $file.FullName -Force
}
Json I am using test.json:
{
"parameters":
{
"FileArray": [
"ABC.json",
"DEF.json"]
}
}
Exception I am getting is:
ForEach-Object : Cannot bind parameter 'RemainingScripts'. Cannot convert
the "-Recurse" value of type "System.String" to
type "System.Management.Automation.ScriptBlock".
What I am expecting(Names of files):
ABC.json
DEF.json
Any help how it can be handled.
How I can iterate over array values from json.
P.S: I am beginner in powershell
foreach($file in (Get-ChildItem "D:\A\DF\ls\" -Include $json -Recurse)) {
$file.BaseName
$file.FullName
}
I don't see why you would need ForEach Object{$_} , the -include accepts an array
Example code:
$jsonfile = '{"parameters":
{ "FileArray": [ "ABC.json", "DEF.json"] } }' | ConvertFrom-Json
$json = $jsonfile.parameters.FileArray
foreach($file in (Get-ChildItem "c:\temp" -Include $json -Recurse)) {
$file.BaseName
$file.FullName
}
Example output:
ABC
C:\temp\example-folder\ABC.json
DEF
C:\temp\example-folder\DEF.json

Add firewall rule to Azure Database for MySQL server from powershell

I have deployed Azure Database for MySQL server and I want to add a firewall rule to it. I need to do it from PowerShell because this step is part of the greater solution. I tried the following code:
$resource = Get-AzureRmResource -ResourceGroupName $ResourceGroup.Variables.ResourceGroup `
-ResourceType "Microsoft.DBforMySQL/servers" -ResourceName $MySQLServer.ResourceName
$props = $resource.Properties
$props | Add-Member #{ipV4FirewallSettings = [ordered] #{ "firewallRules" = #() } }
$props.ipV4FirewallSettings.firewallRules = $MySQLServer.FirewallRules
$props | Add-Member #{administratorLoginPassword = "Qwerty123!" }
Set-AzureRmResource -PropertyObject $props -ResourceGroupName $ResourceGroup.Variables.ResourceGroup `
-ResourceType "Microsoft.DBforMySQL/servers" -ResourceName $MySQLServer.ResourceName -Force
Where $MySQLServer.FirewallRules are from json file in the following format:
"FirewallRules" : [
{ "firewallRuleName" : "test", "rangeStart": "0.0.0.0", "rangeEnd": "0.0.0.0" },
{ "firewallRuleName" : "test2", "rangeStart": "0.0.0.1", "rangeEnd": "255.255.255.255" }
],
This code does not throw any error, but it's not adding rules to the resource.
I need a pointer to where I made a mistake or some documentation, how to handle such task properly.
You can use New-AzureRmResource command to add Mysql firewall rules:
PS C:\Users\jason> $b = New-Object Psobject -Property #{startIpAddress="172.0.0.1" ; endIpAddress="172.0.0.8"}
PS C:\Users\jason> $b
startIpAddress endIpAddress
-------------- ------------
172.0.0.1 172.0.0.8
PS C:\Users\jason> New-AzureRmResource -ResourceId "/subscriptions/b83c1ed3-xxxx-xxxx-xxxx-2b83a074c23f/resourceGroups/jasonmysql/providers/Microsoft.DBforMySQL/servers/jasonmysql/firewallRules/rule2" -Properties $b -ApiVer
sion 2017-04-30-preview -Force
Name : rule2
ResourceId : /subscriptions/b83c1ed3-xxxx-xxxx-xxxx-2b83a074c23f/resourceGroups/jasonmysql/providers/Microsoft.DBforMySQL/servers/jasonmysql/firewallRules/rule2
ResourceName : jasonmysql/rule2
ResourceType : Microsoft.DBforMySQL/servers/firewallRules
ResourceGroupName : jasonmysql
SubscriptionId : b83c1ed3-xxxx-xxxx-xxxx-2b83a074c23f
Properties : #{startIpAddress=172.0.0.1; endIpAddress=172.0.0.8}

Looping through JSON file with PowerShell

How do I loop through all items in a JSON file? The current code just writes all names on one big line:
Get-Content -Raw -Path c:\temp\Environments.Generic.json | ConvertFrom-Json | ForEach-Object {
Write-Host $_.Name
}
json file:
[
{
"Name":"EnableRetry",
"Description":"Enable retry for Webservice Task",
"Type":"Boolean",
"Sensitive":false,
"Value":true
},
{
"Name":"FolderStageFiles",
"Description":"Location of stage files",
"Type":"String",
"Sensitive":false,
"Value":"d:\\sources\\"
},
{
"Name":"FtpPassword",
"Description":"Secret FTP password",
"Type":"String",
"Sensitive":true,
"Value":"Welcome1"
}
]
I ended up Select-Object and a ForEach-Object:
$JSON = Get-Content -Raw -Path c:\temp\Environments.Generic.json | ConvertFrom-Json
$JSON | Select-Object -Property Name,Description,Type,Sensitive,Value | ForEach-Object {
Write-Host $_.Name $_.Value
}
If you do this:
$JSON = Get-Content -Raw -Path c:\temp\Environments.Generic.json | ConvertFrom-Json
$JSON will be a PowerShell object that contains a collection of objects with all of the properties defined in your JSON file.
Enter $JSON at the console and you'll see the contents of this object.
To access specific properties for specific items in the collection you could do (for example):
$JSON | Where {$_.Name -eq 'FolderStageFiles'} | Select -ExpandProperty Value