Get Value of JSON Sting in PowerShell - json
First of all thank you in advance. I am trying to retrieve the following values from the JSON string below using PowerShell but am having issues.
ScheduleTitle,
Title,
Environment and Title
Resolution,
Width,
Height
JSON:
{"Id":"d52fb00e-8736-448c-a496-96db6bc2eb43","ScheduleId":"275726dc-09f2-4869-b1a0-54c71ef6a093","ScheduleTitle":"Resolution Testing","RunType":"RunNow","Timestamp":"2017-08-01T04:52:19.2039685","AutomationRunItems":[{"Id":"f7b731fb-cd96-4003-b95c-ef1594f1c86e","AutomationRunId":"d52fb00e-8736-448c-a496-96db6bc2eb43","Status":"Done","Case":{"Id":"c8a0b939-54ba-4b98-8ca9-101093aec26f","Title":"Resolution Test"},"Environment":{"Id":"e1783fb5-4001-45d0-9971-b49c31b374ab","Title":"Se Chrome"},"Keyframes":[{"Timestamp":"2017-08-01T04:52:03.0685609","Elapsed":"00:00:00","Level":"Info","Status":"Connecting","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Connecting to Se Chrome: Selenium Grid (localhost:5559) on Chrome with size 1280x1024"},{"Timestamp":"2017-08-01T04:52:03.0685609","Elapsed":"00:00:00.0000003","Level":"Info","Status":"Connected","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Connected"},{"Timestamp":"2017-08-01T04:52:03.0685609","Elapsed":"00:00:00.0000015","Level":"Info","Status":"Running","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Running"},{"Timestamp":"2017-08-01T04:52:03.0695642","Elapsed":"00:00:00.0003729","Level":"Trace","Status":"Running","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Block is executing."},{"Timestamp":"2017-08-01T04:52:03.5713896","Elapsed":"00:00:00.5020154","Level":"Trace","Status":"Running","BlockId":"78c198ac-b61f-40eb-b1d9-e706546f2be3","LogMessage":"Block is executed."},{"Timestamp":"2017-08-01T04:52:03.5713896","Elapsed":"00:00:00.5021370","Level":"Trace","Status":"Running","BlockId":"302f21b8-a279-48ce-9338-580a97c930fd","LogMessage":"Block is executing."},{"Timestamp":"2017-08-01T04:52:06.9793063","Elapsed":"00:00:03.9107459","Level":"Info","Status":"Running","BlockId":"302f21b8-a279-48ce-9338-580a97c930fd","LogMessage":"Chrome was successfully started"},{"Timestamp":"2017-08-01T04:52:09.4641639","Elapsed":"00:00:06.3955903","Level":"Info","Status":"Running","BlockId":"302f21b8-a279-48ce-9338-580a97c930fd","LogMessage":"Chrome loaded url https://dev.bamapplication.com/app/starke/npr/3BF6DA09C1/wizard"},{"Timestamp":"2017-08-01T04:52:09.7604882","Elapsed":"00:00:06.6925088","Level":"Trace","Status":"Running","BlockId":"302f21b8-a279-48ce-9338-580a97c930fd","LogMessage":"Block is executed."},{"Timestamp":"2017-08-01T04:52:09.7604882","Elapsed":"00:00:06.6926471","Level":"Trace","Status":"Running","BlockId":"26382d5d-60a6-4343-b934-265c4e97186d","LogMessage":"Block is executing."},{"Timestamp":"2017-08-01T04:52:10.4639126","Elapsed":"00:00:07.3954580","Level":"Warning","Status":"Running","BlockId":"26382d5d-60a6-4343-b934-265c4e97186d","LogMessage":"Web screenshot is saved"},{"Timestamp":"2017-08-01T04:52:10.7666916","Elapsed":"00:00:07.6982198","Level":"Trace","Status":"Running","BlockId":"26382d5d-60a6-4343-b934-265c4e97186d","LogMessage":"Block is executed."},{"Timestamp":"2017-08-01T04:52:10.7666916","Elapsed":"00:00:07.6983727","Level":"Trace","Status":"Running","BlockId":"161e621f-bb7a-4f42-a5f1-67e07d1432f4","LogMessage":"Block is executing."},{"Timestamp":"2017-08-01T04:52:11.7677637","Elapsed":"00:00:08.6992111","Level":"Info","Status":"Done","BlockId":"161e621f-bb7a-4f42-a5f1-67e07d1432f4","LogMessage":"Case is stopped."}],"Resolution":{"Width":1280,"Height":1024},"Elapsed":"00:00:08.6992111","CreatedAt":"2017-08-01T04:52:19.2039685","ModifiedAt":"2017-08-01T04:52:19.2039685"}],"ProjectId":"275726dc-09f2-4869-b1a0-54c71ef6a093","ExecutionTotalTime":"00:00:08.6992111","FailedCount":0,"PassedCount":0,"DoneCount":1,"CreatedAt":"2017-08-01T04:52:03.0685609"}
Code:
Param( [string]$result, [string]$rootPath )
try{
$json = $result
$parsed = $json | ConvertFrom-Json
$output= ''
foreach ($line in $parsed | Get-Member) {
Write-Output $parsed.$($line.Resolution).property1
Write-Output $parsed.$($line.Resolution).property2
$output += $parsed.$($line.Resolution).property1 + " " + $parsed.$($line.Resolution).property1
}
}
With your $parsed data you can extract all the information you need.
For example to extract the width:
echo $parsed.AutomationRunItems.Resolution.Width
should print: 1280
I think these are all the fields you need extracted. Note, since you did not specify the output precisely I have simply used comma-delimited strings:
$output= ''
$output = $output + $parsed.ScheduleTitle + ','
$output = $output + $parsed.AutomationRunItems.Case.Title + ','
$output = $output + $parsed.AutomationRunItems.Environment.Title + ','
$output = $output + $parsed.AutomationRunItems.Resolution.Width + ','
$output = $output + $parsed.AutomationRunItems.Resolution.Height
Should Print: Resolution Testing,Resolution Test,Se Chrome,1280,1024
Related
Powershell using "at-run" parameters to call functions based on which parameter is called
How to use the "at-run" parameters as parameters within the function. Right now my code is returning all data/value regardless of what is enter for the "at-run" parameters. For example, I will like to match the $Server_Name from the "at-run" parameters with the foreach loop, so that only data with the matching $Server_Name is return. function StartServer{ Param ( [Parameter (Mandatory=$true)] [STRING] $Region, [Parameter (Mandatory=$true)] [STRING] $Env, #[STRING] $Env, [Parameter (Mandatory=$true)] [STRING] $ScriptName, #$ScriptName [Parameter (Mandatory=$true)] [STRING] $Server_Name #[STRING] $Server, #[STRING] $Services ) #Write-Output ("Region: "+ $Region + " Env: " + $Env + " ScriptName: " + $ScriptName + " Server_Name: " + $Server) #$startDate = Get-Date; $Sourcefile = "C:\Users\ Scripts\CLEAN10182019.csv" $StartProperties = (Import-Csv $Sourcefile) $Sorted = $StartProperties |select Server_Name,Service_Name, Start_Order, Start_Flag, Start_Wait | Sort-Object -Property Server_Name, {[int]$_.Start_Order}|Format-Table #$Sorted foreach($line in $StartProperties) { $Server_Name = [string]$line.'Server_Name' $Service_Name = [string]$line.'Service_Name' $Start_Order = [string]$line.'Start_Order' $Start_Wait= [string]$line.'Start_Wait' $file = #"Matches? " + $Server_Name "Start " + $Service_Name + " " + " Timeout " + $Start_Wait Write-Output $file } } StartServer
The quickest and easiest way I can think of might be to only execute the code if the service name is passed in- foreach($line in $StartProperties) { if ([string]$line.'Server_Name' -eq $Server_Name) { $Server_Name = [string]$line.'Server_Name' $Service_Name = [string]$line.'Service_Name' $Start_Order = [string]$line.'Start_Order' $Start_Wait= [string]$line.'Start_Wait' $file = #"Matches? " + $Server_Name "Start " + $Service_Name + " " + " Timeout " + $Start_Wait Write-Output $file } } Does that look like what you're looking for?
If I understand you correctly, you want match only those CSV rows whose Server_Name column matches the $Server_Name parameter value: Import-Csv $Sourcefile | Where-Object Server_Name -eq $Server_Name | ForEach-Object { # Synthesize and output a filename. "Start " + $_.Service_Name + " " + " Timeout " + $_.Start_Wait } If you want to output the synthesized string as part of an object, to be presented in tabular form on output, do something like the following: Import-Csv $Sourcefile | Where-Object Server_Name -eq $Server_Name | ForEach-Object { # Create a custom object with the properties of interest: [pscustomobject] #{ # Other properties Server_Name = $_.Server_Name # ... FileName = "Start " + $_.Service_Name + " " + " Timeout " + $_.Start_Wait } } If your output objects have 4 or fewer properties, they automatically print as if they had been piped to Format-Table, so you'll get something like the following: Server_Name FileName ----------- -------- server1 Start service1 Timeout 20 server2 Start service2 Timeout 10 ...
itunes search store api
I want to get data from the API iTunes Store to my PHP file. In the search form you can fill the artist and title of the song. I want to show only the data from the song. This is my code: $title = $_POST["title"]; $artist = $_POST["artist"]; $query_string = urlencode($title); $query_string2 = urlencode($artist); $json = file_get_contents('https://itunes.apple.com/search?term=$query_string&term=$query_string2'); // this WILL do an http request for you $data = json_decode($json); echo "<div class='container' id='movies'>"; echo "<div class='col-md-4' id='movie'>"; echo "<img src='" .$data->artworkUrl60. "' width='200'>"; echo "<h4>" .$data->artistName. " - " .$data->trackName. "</h4>"; i get this error: Notice: Undefined property: stdClass::$artworkUrl60 in.... Whats wrong with my code?
Because your $data Object doesn't contain an attribute named $artworkUrl60. Your HTTP query doesn't not work correctly, you should use double quote instead of single quote. // For limit you can add 'limit' parameter $json = file_get_contents("https://itunes.apple.com/search?term=$query_string&term=$query_string2&limit=20"); // OR concatenation // $json = file_get_contents('https://itunes.apple.com/search?term='.$query_string.'&term='.$query_string2); $data = json_decode($json); if (0 == $data->resultCount) { echo 'No result found ! '; } else { foreach ($data->results as $row){ echo "<div class='container' id='movies'>"; echo "<div class='col-md-4' id='movie'>"; echo "<img src='" .$row->artworkUrl60. "' width='200'>"; echo "<h4>" .$row->artistName. " - " .$row->trackName. "</h4>"; } } https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/#searchexamples
Leading zero is dropped when using ExportTo-Csv cmdlet
Below is the script I am running. The script is working fine. It is giving proper output, however it is removing leading zeros from couple of columns. Please suggest how to retain leading zero for the integer fields. I am using $res.data.Tables[0] | ConvertTo-Csv -NoType | ForEach-Object {$_.Replace('"','')} | Out-file $fileName -Force" for exporting data to the CSV file. Please suggest how to retain the leading zeros (at least 2 decimal places). param([int]$accountingDay = 1, [string]$outputFolder) $server = "ADMSQL01" $db = "cc111db" function exec-storedprocedure($storedProcName, [hashtable] $parameters=#{}, [hashtable] $outparams=#{}, $conn) { function put-outputparameters($cmd, $outparams) { foreach ($outp in $outparams.Keys) { $p = $cmd.Parameters.Add("#$outp", (get-paramtype $outparams[$outp])) $p.Direction=[System.Data.ParameterDirection]::Output $p.Size=4 } } function get-outputparameters($cmd,$outparams){ foreach ($p in $cmd.Parameters) { if ($p.Direction -eq [System.Data.ParameterDirection]::Output) { $outparams[$p.ParameterName.Replace("#","")]=$p.Value } } } function get-paramtype($typename) { switch ($typename) { 'uniqueidentifier' {[System.Data.SqlDbType]::UniqueIdentifier} 'int' {[System.Data.SqlDbType]::Int} 'xml' {[System.Data.SqlDbType]::Xml} 'nvarchar' {[System.Data.SqlDbType]::NVarchar} default {[System.Data.SqlDbType]::Varchar} } } $close = ($conn.State -eq [System.Data.ConnectionState]'Closed') if ($close) { $conn.Open() } $cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn) $cmd.CommandType = [System.Data.CommandType]'StoredProcedure' $cmd.CommandText = $storedProcName foreach ($p in $parameters.Keys) { $cmd.Parameters.AddWithValue("#$p",[string]$parameters[$p]).Direction = [System.Data.ParameterDirection]::Input } put-outputparameters $cmd $outparams $ds = New-Object System.Data.DataSet $da = New-Object System.Data.SqlClient.SqlDataAdapter($cmd) [Void]$da.fill($ds) if ($close) { $conn.Close() } get-outputparameters $cmd $outparams return #{data=$ds;outputparams=$outparams} } # setup the 'framework' to use PowerShell with SQL $sqlConnection = New-Object System.Data.SqlClient.SqlConnection # SQL Server connection string $sqlConnection.ConnectionString = $sqlConnection.ConnectionString = 'server=' + $server + ';integrated security=TRUE;database=' + $db # execute stored procedure $res=exec-storedprocedure -storedProcName 'sp_OPTUS_summary' -parameters #{inAccountFieldValues=$null;inAccountViewID=1;inAccountLevel=4;inAccountingDay=$accountingDay;inAccountPeriod=3;inUserGroupID=2} -outparams #{} $sqlConnection if ($res.data.Tables.Count) { # store results in file $curYear = Get-Date -Format yyyy $curMonth = Get-Date -Format MMM $curTime = (Get-Date -Format s).Replace(':', ' ') $fileName = $outputFolder + '\scheduled-' + $curYear + '-' + $curMonth + '-' + $accountingDay + '-' + $curTime + '.csv' $res.data.Tables[0] | ConvertTo-Csv -NoType | ForEach-Object {$_.Replace('"','')} | Out-File $fileName -Force }
Integers don't have "leading zeroes". If you want to export formatted output you need to convert the respective fields to formatted strings, e.g. like this: $res.data.Tables[0] | Select-Object FieldA, FieldB, #{n='FieldC';e={'{0:d2}' -f $_.FieldC}}, #{n='FieldD';e={'{0:d2}' -f $_.FieldD}}, FieldE, ... | ConvertTo-Csv -NoType | ...
Get location (lat/long) from googlemap with address - Using powershell
I would like to create a script that allow myself to get the coordinates of some locations on Google map using their addresses. To do this I use powershell code: clear-host $address = "Place+de+la+concorde" $city = "Paris" $cp = "75000" $country = "France" $url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + $address + "+" + $city + "+" + $cp + "+" + $country $result = Invoke-WebRequest -Uri $url Write-Host = $result Unfortunately I can not retrieve rows interesting to me, ie: results> geometry> location> lat and results> geometry> location> lng Any idea for getting a specific line information, considering that the number of lines could change ? Thank you !
ConvertFrom-JSON is the cmdlet you need. $json = Invoke-WebRequest $url | ConvertFrom-JSON $json.results.geometry.location.lat $json.results.geometry.location.lng Now you are looking at a JSON object (as intended) rather than lines so you won't have to worry about line position, etc.
How to include folder name from list dynamically into mailto URL?
I have this script. It scans a folder location and maps the names of folders to that of the folder owners which is pulled from a CSV file it then gets the users email address from AD and adds it to a new column as a clickable mailto: link. This is then all output in a table on a HTML page. Gone through a few iterations of this and now at the final stage. My issue now is how to pull in the folder name to the mailto body HTML. Import-Module ActiveDirectory function Encode($str) { return ( $str -replace ' ', '%20' -replace '\n', '%0A%0D' ) } function name($filename, $folderowners, $directory, $output){ $subject = Encode("Folder Access Request") $body = Encode("Please can I have access to the following folder $directory") $server = hostname $date = Get-Date -format "dd-MMM-yyyy HH:mm" $a = "<style>" $a = $a + "TABLE{border-width: 1px;border-style: solid;border-color:black;}" $a = $a + "Table{background-color:#ffffff;border-collapse: collapse;}" $a = $a + "TH{border-width:1px;padding:0px;border-style:solid;border-color:black;}" $a = $a + "TR{border-width:1px;padding-left:5px;border-style:solid;border-color:black;}" $a = $a + "TD{border-width:1px;padding-left:5px;border-style:solid;border-color:black;}" $a = $a + "body{ font-family:Calibri; font-size:11pt;}" $a = $a + "</style>" $c = " <br></br> Content" $c = $c +"<p>More Content</p>" $x = "" $b = Import-Csv $folderowners $mappings = #{} $b | % { $mappings.Add($_.FolderName, $_.Owner) } Get-ChildItem $directory | where {$_.PSIsContainer -eq $True} | select Name, Path, #{n="Owner";e={$mappings[$_.Name]}}, #{n="Email";e={"mailto:"+((Get-ADUser $mappings[$_.Name] -Properties mail).mail)}} | sort -property Name | ConvertTo-Html -head $a -PostContent $c | % { $body = Encode("Please can I have access to the following folder " + $_.Name) $_ -replace '(mailto:)([^<]*)', "`$2" } | Out-File $output } name "gdrive" "\\server\departmentfolders$\location\gdrive.csv" "x:" "\\server\departmentfolders$\location\gdrive.html" This now comes out and in the body of the email it shows the path but doesnt include the folder name just the path location \server\departmentfolders$ which is very nearly just need the folder name...
If you want to use variables in the replacement string you have to use double quotes instead of single quotes around the string: $_ -replace '...', "... $directory ..." In that case you have to escape other elements in the replacement string, though, namely inner double quotes and back-references ($1, $2) to groups ((...)) in the regular expression: $_ -replace '(...)(...)', "<a href=`"`$1`$2...`">..." Also you should encode spaces (%20) and line breaks (%0A%0D) in the URL. function Encode($str) { return ( $str -replace ' ', '%20' -replace '\n', '%0A%0D' ) } The whole thing might look like this: Import-Module ActiveDirectory function Encode($str) { return ( $str -replace ' ', '%20' -replace '\n', '%0A%0D' ) } function name($filename, $folderowners, $directory, $output) { $subject = Encode("Folder Access Request") ... Get-ChildItem $directory | ... | ConvertTo-Html -head $a -PostContent $c | % { if ( $_ -match '^<tr><td>([^<]*)' ) { $body = Encode("Please can I have access to the following folder " + "{0}\{1}" -f ($directory, $matches[1])) } $_ -replace '(mailto:)([^<]*)', "`$2" } | Out-File $output } ...