简体   繁体   中英

Powershell and json

Back story I have never coded in powershell or json before. I am porting SQL to our API in batchs. The Batchs are layed out on a json file and they are called through script 1 for script 2. There is a Json file that looked like this.

{
"GroupA":[
{
"SQLConn": 'ConnectionString',
"SQLQur": "Select stuff From dbo.table where things",
}
]
}

Everything works the way it is coded but I want to clean up my json powershell code. Here is the working script1 Powershell code. $pram Is called in when the task runs through task manager. That way It can call a group at a time. Groups range from being called every 15 minutes to once day.

$array = (gc $json -Raw | convertfrom-json).$pram
for ($i=0; $i -lt $array.length; $i++) 
{   
$SQLConn = (gc $json -Raw | convertfrom-json).$pram[$i].SQLConn
$SQLQur = (gc $json -Raw | convertfrom-json).$pram[$i].SQLQur
powershell -file c:\Scipt2.ps1 $SQLConn $SQLQur
}

I do not think I need to call the json file a 2nd and 3rd time. I thought I could do something like this.

$array = (gc $json -Raw | convertfrom-json).$pram
for ($i=0; $i -lt $array.length; $i++) 
{   
$SQLConn = $pram[$i].SQLConn
$SQLQur = $pram[$i].SQLQur
powershell -file c:\Scipt2.ps1 $SQLConn $SQLQur
}

Or like this

$array = (gc $json -Raw | convertfrom-json).$pram
for ($i=0; $i -lt $array.length; $i++) 
{   
powershell -file c:\Scipt2.ps1 $pram[$i].SQLConn $pram[$i].SQLQur
}

I tried a few others however none of them worked. The messy way works for what I need now. I don't want to spend extra time calling the json file for when this scales up. I did look around that is where I got the idea for the 2 I tried up there.

Thank you.

You're close, but instead of just calling $param[$i].SQLConn you want to call $Array[$i].SQLConn (and similarly for .SQLQur).

You have set $array to (gc $json -Raw | convertfrom-json).$pram already, so it has already handled the $param portion of that, you don't need to reference it again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM