I am using power shell code as:
$web_client = new-object system.net.webclient
$build_info=web_client.DownloadString("http://<URL>")
$suitevm_build_number=
$suitevmCLN=
$webapp_build=
$stats_build=
Output in browser while hitting http:// is:
{"message":null,"changeset":"340718","branch":"main","product":"productname","buildNumber":"1775951","todaysDate":"28-4-2014"}
What should I write the power shell code to get:
$suitevm_build_number=
$suitevmCLN=
$webapp_build=
$stats_build=
Your question is very unclear. If you have Powershell 3 or later, you can use ConvertFrom-JSON to convert the JSON response to an object.
$build_info=$web_client.DownloadString("http://<URL>") | ConvertFrom-Json
Ex of output:
$build_info
message :
changeset : 340718
branch : main
product : productname
buildNumber : 1775951
todaysDate : 28-4-2014
With PS 3+ you could also replace the WebClient with Invoke-RestMethod as shown by #RickH.
$build_info = Invoke-RestMethod -Uri "http://<URL>"
Related
I'm using the following Powershell to call a URL that returns a JSON file. (If you were to paste the URL into the browser it would download a file, rather than display the raw JSON):
$fileName = "output.json"
$url = "https://some-url-that-returns-a-json-file-byte-stream"
$jsonFileResponse = Invoke-WebRequest -Method GET -Uri $url -UseDefaultCredentials -OutFile "output.json"
$parsedData = Get-Content -Path $fileName | ConvertFrom-Json
This works fine, and I get my parsed data at the end.
I was wondering, is there a way of doing this without involving the file system, i.e. without having the step of outputting to output.json first, and instead handling this in-memory and without any disk i/o?
The question is less one of converting to 'JSON' and more of just converting to text.
Using [System.Text.Encoding]::ASCII.GetString seems to do the trick.
$url = "https://some-url-that-returns-a-json-file-byte-stream"
$jsonFileResponse = Invoke-WebRequest -Method GET -Uri $url -UseDefaultCredentials
$parsedData = [System.Text.Encoding]::ASCII.GetString($jsonFileResponse.Content) | ConvertFrom-Json
Thought this would be pretty simple, but alas, I can't figure it out. It appears that PowerShell will prettify JSON with a single cmdlet.
Goal: Prettify JSON using a PowerShell Azure Function app
Using Microsoft Flow, send an HTTP request (POST) to an Azure Function w/ "ugly", serialized JSON file in body
Azure Function reads file in (then uses ConvertToJson cmdlet to prettify?) and outputs the file back to Flow
Questions:
What do I put in the run.ps1 area of the Azure Function to make this happen?
What do I put in the functions.json area of the Azure Function to make this happen?
I have taken below serialize string
'{ "baz": "quuz", "cow": [ "moo", "cud" ], "foo": "bar" }'
which was mentioned in Prettify json in powershell 3
Here is my function which i used with HttpPost and send the request:
using namespace System.Net
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."
# Interact with query parameters or the body of the request.
$name = $Request.Query.baz
if (-not $name) {
$name = $Request.Body.baz
}
if ($name) {
$status = [HttpStatusCode]::OK
$body = "Hello $name"
}
else {
$status = [HttpStatusCode]::BadRequest
$body = "Please pass a name on the query string or in the request body."
}
# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]#{
StatusCode = $status
Body = $body
})
and below you can see , i am able to read it from the string which i posted.
You can use ConvertFrom-Json to convert it but i wondering if you even need it as you can access it by doing below:
$name = $Request.Query.baz
my binding is same as yours. Hope it helps.
Let me know if you still need any help.
Are you looking for something like this?
using namespace System.Net
param($Request, $TriggerMetadata)
Push-OutputBinding -Name Response -Value ([HttpResponseContext]#{
StatusCode = [HttpStatusCode]::OK
Body = $Request.RawBody | ConvertFrom-Json | ConvertTo-Json
})
looked at a few examples of how to execute a webhook with parameters but can't seem to make the connection on what I am missing. Any advice on what I am doing wrong would be appreciated.
please consider:
my Powershell runbook
[CmdletBinding()]
Param([object]$WebhookData) #this parameter name needs to be called
WebHookData otherwise the webhook does not work as expected.
$VerbosePreference = 'continue'
Write-Output "hello"
"in the inline"
if($WebhookData -ne $null)
{
"using webhookdata"
$WebhookName = $WebhookData.WebhookName
$WebhookBody = $WebhookData.RequestBody
$webhookBodyObject = $WebhookBody | ConvertFrom-JSON
line 15 'The parameter created was ' $webhookBodyObject.strYear
My httpclient post request looks like this (warning..its vb)
dim WebHookData as new StringContent("{'strYear'='2018'}",Encoding.UTF8,"application/json")
Dim resp as Task(Of HttpResponseMessage)
resp = _client.PostAsync(webhook,WebHookData)
status = resp.Result.Content.ReadAsStringAsync().Result
if(status.Contains("JobId"))
status = "Scheduled!"
End If
My Webhook data is being posted to my webhook as this.
{"WebhookName":"myimportjob","RequestBody":"{'strYear'='2018'}","RequestHeader":{"Connection":"Keep-Alive","Expect":"100-continue","Host":"xxx.azure-automation.net","x-ms-request-id":"xxx"}}
I am getting this error
At line:15 char:42
+ 'The parameter created was ' $webhookBodyObject.strYear
+ ~~~~~~~~~~~~~~~~~~ Unexpected token '$webhookBodyObject' in expression or
statement.
I discovered the devil is in the details.
Firstly I had
$webhookBodyObject = $WebhookBody | ConvertFrom-JSON
which is not the same as
$webhookBodyObject = $WebhookBody | ConvertFrom-Json <---this is the correct syntax
The other was that the json I was sending had a single quote like this '{"key":"value"}'
For some reason, even though it passed regular powershell, the runbook didn't like it. It wants it's Json like this {"key":"value"}. I never tested complex objects so I can't speak to that.
Using Jira API 2 and PowerShell 5 Invoke-RestMethod I can successfully execute GET, but I keep getting a (400) Bad Request when attempting POST method to create an issue in my project.
$user = [System.Text.Encoding]::UTF8.GetBytes("me:mypassword")
$headers = #{Authorization = "Basic " + [System.Convert]::ToBase64String($user)}
$data = Get-Content D:\scripts\powershell\issue.txt
Invoke-RestMethod -Uri "https://agile.mycompany.com/rest/api/2/issue/" -Method POST -Headers $headers -ContentType "application/json" -Body $data
$data variable is well-formed JSON for Jira:
{
"fields":
{
"project":{"Key": "ITS"},
"summary":"Rest Test 1",
"issuetype":{"name": "Task"},
"assignee":{"key": "myusername"},
"priority":{"id": "3"},
"description":
"||Host Name||IP Address||Comments||
|some-pc|192.168.1.1| |",
"duedate": "2016-09-11"
}
}
I am the project owner, so this isn't a permissions issue.
Get-content is tricky, because it will actually result in a array of strings, where each line in your text file is an object in that array. The best way to get around that is probably using .Net's file read methods instead:
$data = [System.IO.File]::ReadAllText("D:\scripts\powershell\issue.txt")
btw, you can use a regular ps credential object instead of manually building your request header.
On a side note, it's always a good idea to test your api out using a tool such as postman. That will let you verify that you're posting valid json while not having to worry about your code doing strange things.
Problem solved. The issue was that I was CAPITALIZING the first letter of the field names. Apparently, Jira is very sensitive to CASE. Trondh - thank you for the recommendation to use postman. The errors that were getting generated by postman from the failed API calls were very concise.
I am trying to get JSON details from an api using powershell.
I do not have any expereince with power shell, but I guess Invoke-RestMethod would be helpful.
the api I am trying to use is :
api.spotcrime.com/crimes.json?lat=30.639155&lon=-96.3647937&radius=0.02&key=spotcrime-private-api-key
Please read the online documentation: Invoke-RestMethod
Here is a sample showing how to access the data returned from this API:
$uri = 'api.spotcrime.com/crimes.json'
$params = #{
lat = '30.639155'
lon = '-96.3647937'
radius = '0.02'
key = 'spotcrime-private-api-key'
}
$crimes = Invoke-RestMethod -Uri $uri -Body $params |
Select-Object -ExpandProperty crimes
$crimes | Format-Table -AutoSize
In this dataset we have an object named crimes which contains an array of records. Expanding the crimes object and storing it to a $crimes variable will allow us to work with the records more easily.
Notice how Invoke-RestMethod automatically detects and converts JSON into objects. No need to use ConvertFrom-Json.