How to modify Json file from power shell script gcp output - json

I have a GCP script below mentioned, running in power shell
$cred = gcloud auth print-access-token
$headers = #{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://sqladmin.googleapis.com/v1/projects/source-project/instances/source-instance/backupRuns" | Select-Object -Expand Content
getting output from above script like below
C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\third_party\urllib3\connectionpool.py:979: InsecureRequestWarning: Unverified HTTPS request is being made to host 'oauth2.googleapis.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
warnings.warn(
{
"kind": "sql#backupRunsList",
"items": [
{
"kind": "sql#backupRun",
"status": "SUCCESSFUL",
"enqueuedTime": "2023-01-11T00:33:21.903Z",
"id": "1673391600000",
"startTime": "2023-01-11T00:33:21.949Z",
"endTime": "2023-01-11T00:38:47.459Z",
"type": "AUTOMATED",
"windowStartTime": "2023-01-10T23:00:00Z",
"instance": "instance",
"selfLink": "https://sqladmin.googleapis.com/v1/projects/project/instances/instance/backupRuns/1673391600000",
"location": "us",
"backupKind": "SNAPSHOT"
},
{
"kind": "sql#backupRun",
"status": "SUCCESSFUL",
"enqueuedTime": "2023-01-09T23:36:39.776Z",
"id": "1673305200000",
"startTime": "2023-01-09T23:36:39.826Z",
"endTime": "2023-01-09T23:42:05.542Z",
"type": "AUTOMATED",
"windowStartTime": "2023-01-09T23:00:00Z",
"instance": "instance ",
"selfLink": "https://sqladmin.googleapis.com/v1/projects/project/instances/instance/backupRuns/1673305200000",
"location": "us",
"backupKind": "SNAPSHOT"
},
And I have a JSON file in the same folder like below
{
"restoreBackupContext":
{
"backupRunId": 1673391600000,
"project": "project",
"instanceId": "instance"
}
}
I want to update " "id": " each time from output to json automatically while running first script
enter image description here
The " "id": " value each time getting new.
Let me know how to achieve it
thanks

Related

How can I parse nested JSON in PowerShell?

I'm trying to parse the results of a cURL command and the information I need is in a structure.
I tried getting to the data unsuccessfully and tried converting to PS Object but not sure how to access the structure as I'm new to PS.
Below is a sample of our cURL response.
I have a git commit hash ('c64a568399a572e82c223d55cb650b87ea1c22b8' matches latestCommit in fromRef for entry id 1101) and I need to find the corresponding displayId ('develop' in toRef)
I've done this in Linux using jq but need to replicate this in PS.
jq '.values | map(select(.fromRef.latestCommit=="'"$HASH"'")) | .[0].toRef.displayId'
I'm having 2 issues.
I can get to fromRef but it looks like #{id=refs/heads/feature/add-support; displayId=feature/add-support; latestCommit=c64a568399a572e82c223d55cb650b87ea1c22b8; repository=} and I cannot figure out how to parse
I'm not sure how to get the id so I can find the correct corresponding toRef
Any help would be greatly appreciated.
{
"size": 15,
"limit": 20,
"isLastPage": true,
"values": [
{
"id": 1101,
"version": 0,
"title": "Added header",
"description": "Added notes in header",
"state": "OPEN",
"open": true,
"closed": false,
"createdDate": 1595161367863,
"updatedDate": 1595161367863,
"fromRef": "#{id=refs/heads/feature/add-support; displayId=feature/add-support; latestCommit=c64a568399a572e82c223d55cb650b87ea1c22b8; repository=}",
"toRef": "#{id=refs/heads/develop; displayId=develop; latestCommit=58b3e3482bb35f3a735048849c2474cc676fbd9b; repository=}",
"locked": false,
"author": "#{user=; role=AUTHOR; approved=False; status=UNAPPROVED}",
"reviewers": " ",
"participants": "",
"properties": "#{mergeResult=; resolvedTaskCount=0; openTaskCount=0}",
"links": "#{self=System.Object[]}"
},
{
"id": 1053,
"version": 4,
"title": "Help with checking,",
"description": "fixed up code.",
"state": "OPEN",
"open": true,
"closed": false,
"createdDate": 1591826401310,
"updatedDate": 1595018917357,
"fromRef": "#{id=refs/heads/bugfix/checking-2.7; displayId=bugfix/checking-2.7; latestCommit=cf7d8860262c6a46b0b65ef5b6d66ae8cd698b75; repository=}",
"toRef": "#{id=refs/heads/hotfix/2.7_Improvements; displayId=hotfix/2.7_Improvements; latestCommit=01f1100c559ba41ec317421399c3bfb9a0aea91f; repository=}",
"locked": false,
"author": "#{user=; role=AUTHOR; approved=False; status=UNAPPROVED}",
"reviewers": " ",
"participants": "",
"properties": "#{mergeResult=; resolvedTaskCount=0; commentCount=4; openTaskCount=0}",
"links": "#{self=System.Object[]}"
}
],
"start": 0
}
Once you have converted the result with ConvertTo-Json and the correct -Depth parameter, you can get the values of the returned object quite easily in PowerShell.
Let's say you have used something like $json = $curlResult | ConvertTo-Json -Depth 100, then finding the displayId from the corresponding toRef can be done like this:
# this is the known hashvalue of the `fromRef` value to look for
$latestCommitHash = "c64a568399a572e82c223d55cb650b87ea1c22b8"
# get the value item. from here you can get all other properties belonging to that item
$valueItem = $json.values | Where-Object { $_.fromRef.latestCommit -eq $latestCommitHash }
# get the displayId value of the corresponding 'toRef' element:
$displayId = $valueItem.toRef.displayId
Returns
develop

How to select words after /slash from a json file in a powershell script

I've a json file from a az cli command, I want to deploy with a powershell script from a tool like jenkins or rundeck, I need to take the field "name" from json but not entirely only the word after forward slash
[
{
"Group": "KC-EMEA-RSGP-BPTRAINING-01",
"id": "/subscriptions/KC-EMEA-RSGP-BPTRAINING-01/providers/Microsoft.Sql/servers/",
"name": "kc-emea-sqsrv-bptraining-dev-01/master"
},
{
"Group": "KC-EMEA-RSGP-NAVISIONKM-DEV-01",
"id": "/subscriptions/KC-EMEA-RSGP-NAVISIONKM-DEV-01/providers/Microsoft.Sql/servers/",
"name": "km-emea-sqsrv-navision-tst-01/km-emea-sqdb-navision-tst-01"
},
{
"Group": "KC-EMEA-RSGP-NAVISIONKM-DEV-01",
"id": "/subscriptions/KC-EMEA-RSGP-NAVISIONKM-DEV-01/providers/Microsoft.Sql/servers/",
"name": "km-emea-sqsrv-navision-tst-01/master"
},
{
"Group": "KC-EMEA-RSGP-PROJECTS-DEV-01",
"id": "/subscriptions/KC-EMEA-RSGP-PROJECTS-DEV-01/providers/Microsoft.Sql/servers/",
"name": "kc-emea-sqsrv-projects-dev-01/KC-EMEA-SQDB-BPTRAINING-TRAINEE-01"
}
]
$file = "pathtojsonfile.json"
$jsonContent = Get-Content $file | ConvertFrom-Json;
$namedb = $jsonContent.name;
$value= $namedb.Substring($namedb.IndexOf('/')+1) --> this doesn't work.
Try
$namedb[0].Substring($namedb[0].IndexOf('/')+1)
And for all of them:
foreach($name in $namedb) {$name.Substring($name.IndexOf('/')+1)}

How to form a "GET :urn/manifest/:derivativeurn" request?

I don't get how to download a created derivative from Forge.
Here is what I get from the "GET :urn/manifest" request:
{
"type": "manifest",
"hasThumbnail": "false",
"status": "success",
"progress": "complete",
"region": "US",
"urn": "dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6ZGVyaXZhdGV0bXAvU3QlQzMlQTRuZGVyX1lfT2JlbiUyMHYxLmYzZA",
"version": "1.0",
"derivatives": [
{
"name": "Ständer_Y_Oben v1.f3d",
"hasThumbnail": "false",
"status": "success",
"progress": "complete",
"outputType": "obj",
"children": [
{
"guid": "4064073b-a56c-4007-8b87-3cf87c821361",
"type": "resource",
"role": "obj",
"status": "success",
"progress": "complete",
"mime": "application/octet-stream",
"urn": "urn:adsk.viewing:fs.file:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6ZGVyaXZhdGV0bXAvU3QlQzMlQTRuZGVyX1lfT2JlbiUyMHYxLmYzZA/output/files/6f7db9b2-925f-44b3-92e8-a5aeeb3954d2/Ständer_Y_Oben v1.obj"
}
]
}
]
So how to form a valid "GET :urn/manifest/:derivativeurn" request with that? The docs say "urn should be The Base64 (URL Safe) encoded design URN" and "derivativeurn should be The URL-encoded URN of the derivatives.".
For me this results in:
https://developer.api.autodesk.com/modelderivative/v2/designdata/dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6ZGVyaXZhdGV0bXAvU3QlQzMlQTRuZGVyX1lfT2JlbiUyMHYxLmYzZA/manifest/urn:adsk.viewing:fs.file:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6ZGVyaXZhdGV0bXAvU3QlQzMlQTRuZGVyX1lfT2JlbiUyMHYxLmYzZA/output/files/6f7db9b2-925f-44b3-92e8-a5aeeb3954d2/St%C3%A4nder_Y_Oben%20v1.obj
But the result always is the message "The requested derivative is not belongs to the design data.".
So what is wrong? The docs or me?
Regards,
Michael
According to documentation of GET :urn/manifest/:derivativeurn, the derivativeurn should be escaped into a URL safe form since there are some reserved and unsafe keywords ( i.e. :, ., ? and = ) in this parameter. They will invalid your request to the Forge service. (Ref)
Your file urn is:
urn:adsk.viewing:fs.file:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6ZGVyaXZhdGV0bXAvU3QlQzMlQTRuZGVyX1lfT2JlbiUyMHYxLmYzZA/output/files/6f7db9b2-925f-44b3-92e8-a5aeeb3954d2/Ständer_Y_Oben v1.obj
To download this file, you have to transform it into this form: urn%3Aadsk.viewing%3Afs.file%3AdXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6ZGVyaXZhdGV0bXAvU3QlQzMlQTRuZGVyX1lfT2JlbiUyMHYxLmYzZA%2Foutput%2Ffiles%2F6f7db9b2-925f-44b3-92e8-a5aeeb3954d2%2FSt%C3%A4nder_Y_Oben%20v1.obj
In JavaScript, the encodeURIComponent()(Ref) function can help you do this transformation. Here is a sample for you:
encodeURIComponent('urn:adsk.viewing:fs.file:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6ZGVyaXZhdGV0bXAvU3QlQzMlQTRuZGVyX1lfT2JlbiUyMHYxLmYzZA/output/files/6f7db9b2-925f-44b3-92e8-a5aeeb3954d2/Ständer_Y_Oben v1.obj')
If you are coding in C#, Uri.EscapeDataString() (Ref) can help you to archive the same goal.

"The validation of the PDF file failed." when trying to send signing request via email - docusign

****EDIT: Thanks for those links, #Hackerman. I was able to get it working in Postman and then in Powershell using the Docusign postman sample. However I cannot get it working with my own PDF documents. I suspect this is because I am not properly converting my PDFs to Base64. Anyone know how this can be done via Powershell?****
EDIT2: Was able to encode my PDFs to Base64 via powershell with this simple 1-liner
$docEncodedBase64 = [Convert]::ToBase64String((Get-Content $PDFPath -Encoding Byte))
We are trying to use Powershell 5.0 (and the invoke-restmethod cmdlet) to make requests to the docusign REST API in order to send a signing request via email.
In my tests I have been following this guide: https://docs.docusign.com/esign/guide/usage/request_a_signature.html#prepare-the-document-to-send-through-docusign but am getting an error when I send my POST request
We are going the route of a normal request (i.e., not multi-part request), and thus supplying the PDF document as bytes in base64-encoded format as the value of the documentBase64 property.
Here is my code to convert the PDF to base64 bytes:
# PDF document
$docContent = Get-Content 'Mutual_NDA.pdf'
# PDF as bytes
$docBytes = [System.Text.Encoding]::Unicode.GetBytes($docContent)
# PDF as Base-64 Encoded bytes
$docEncoded = [System.Convert]::ToBase64String($docBytes)
Then I define my JSON payload, which will be sent as the body in the POST request. In here I set the 'documentBase64' property to the base64 encoded string that I just converted above.
# JSON payload
$jsonPayload = #"
{
"documents": [
{
**"documentBase64": "$docEncoded"**,
"documentId": "1",
"fileExtension": "pdf",
"name": "Mutual_NDA.pdf"
}
],
"emailSubject": "Please sign the NDA",
"recipients": {
"signers": [
{
"email": "the_nda_signer#mailinator.com",
"name": "Tester test",
"recipientId": "1",
"routingOrder": "1",
"tabs": {
"dateSignedTabs": [
{
"anchorString": "signer1date",
"anchorYOffset": "-6",
"fontSize": "Size12",
"name": "Date Signed",
"recipientId": "1",
"tabLabel": "date_signed"
}
],
"fullNameTabs": [
{
"anchorString": "signer1name",
"anchorYOffset": "-6",
"fontSize": "Size12",
"name": "Full Name",
"recipientId": "1",
"tabLabel": "Full Name"
}
],
"signHereTabs": [
{
"anchorString": "signer1sig",
"anchorUnits": "mms",
"anchorXOffset": "0",
"anchorYOffset": "0",
"name": "Please sign here",
"optional": "false",
"recipientId": "1",
"scaleValue": 1,
"tabLabel": "signer1sig"
}
]
}
}
]
},
"status": "sent"
}
"#
And lastly, the HTTP request:
$Envelope = Invoke-RestMethod -uri ($BaseURL + '/envelopes') -Method Post -Body $jsonPayload -ContentType 'application/json' -Headers #{"X-Docusign-Authentication" = $XMLHeader}
Anyone have experience with this? Perhaps I am encoding the PDF as base64 incorrectly? I am truly stuck. Any help appreciated!
Thanks,
Eric
My PDF was not properly converting to Base64. Using this line of code in Powershell I was able to successfully create and send an envelope
$docEncodedBase64 = [Convert]::ToBase64String((Get-Content $PDFPath -Encoding Byte))
Thanks to #Hackerman for referencing Postman!

Zabbix Json Api get health of host or hostgroup

I am currently trying out Zabbix 2.4 json api and can connect get alerts and triggers but I'm having trouble finding a way to check if a given hostgroup contains no open errors and is thereby healthy. A simple way to check this doenst seem to exist? I have searched stackoverflow, google and Zabbix documentation. any clues as to tackeling this question? The following reuqest gives me errors but no way to tell if errors are still open.
{
"jsonrpc": "2.0",
"method": "alert.get",
"params": {
"output": "extend",
"groupids": "83",
"time_from": "1441065600"
},
"auth": "ZZZZZZZZZZZZZZZZZZZZZZZZZ",
"id": 1
}
Update: (solved)
$resource = "http://zabbix/api_jsonrpc.php"
$body = '
{
"jsonrpc": "2.0",
"method": "trigger.get",
"params": {
"active": 1,
"only_true": "1",
"monitord": 1,
"selectGroups": 1,
"output": "extend",
"expandDescription": "1",
"selectGroups": "1",
"groupids": 83, <---- this field changes :)
"filter": {
"value": 1,
"priority": [3,4,5] <----- filter off low prios
},
"sortfield": "priority",
"sortorder": "DESC"
},
"auth": "ZZZZZZZZZZZZZZZZZZZZZZZZZ",
"id": 1
}
'
$result = Invoke-RestMethod -Method Post -Uri $resource -Body $body -ContentType "application/json"
$result.result
Use active triggers of host/group. Some my code, which I use:
zapi.trigger.get(only_true=1,
skipDependent=1,
monitored=1,
active=1,
output='extend',
expandDescription=1,
selectGroups=1,
expandData='host',
hostids=<host_id>,
sortfield='priority',
sortorder='DESC',
filter={"value": 1, "priority": ['4','5']}
)
https://www.zabbix.com/documentation/2.4/manual/api/reference/trigger/get