in Powershell I have an object from query response, and it contains multiple members. I have to add some strings before and after every member of the object, and then send the produced json as query to create similar rules for different service. What happens is that $l_rules_json = $l_rules | ConvertTo-Jsondoes not access single member of the object but all members. How do I access members one by one in the cycle?
$l_rules |
ForEach-Object {
write-host("Output from rules objects in a cycle")
$l_rules_json = $l_rules | ConvertTo-Json
$l_rules_json_ext = "'{ `"rule`": { $l_rules_json }'"
write-host("Actual json BODY:")
write-host($l_rules_json_ext)
$response_t = Invoke-Restmethod -Uri $api_uri_t -Method POST -Headers $headers -ContentType 'application/json' -UseBasicParsing -Body $l_rules_json_ext
}
Related
I'm trying to copy Horizon application pools that exist on a source Horizon connection server (HCS) to another one. In my homelab that works perfectly, in another environment on "invoke-restmethod" I run into the error above.
First I get an auth token and the applications on the source HCS:
$horizonApps_source = Invoke-RestMethod -Method Get -uri "$RESTurl_source/rest/inventory/v2/application-pools" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken_source)`
Then I loop through them and create the copies on the target HCS (also exporting a .json-File for every app and removing unique values that the POST "inventory/v2/application-pools" will not accept):
If ($horizonApps_source -ne $null) {
ForEach ($item in $horizonApps_source) {
$jsonFile = $fileLoc + $item.Display_Name + ".json"
$item = $item | Select-Object * -ExcludeProperty Id, access_group_id, icon_ids, customized_icon_ids
$item.farm_id = $farmID_target
$item | ConvertTo-Json -Depth 100 | Out-File $jsonFile
$appJson = $item | ConvertTo-Json -Depth 100
$app_target = Invoke-RestMethod -Method Post -uri "$RESTurl_target/rest/inventory/v2/application-pools" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken_target) -body $appJson -SkipCertificateCheck
}
}
In one environment everything works, in another no chance...this is the error I get, .json-files are written and look okay, but no apps are created on the target HCS:
Line |
8 | … pp_target = Invoke-RestMethod -Method Post -uri "$RESTurl_target/rest …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| {"status":"BAD_REQUEST","timestamp":1670869477302,"error_message":"The input request cannot be parsed."}
Powershell 7.3.0, PowerCLI 13, Horizon 2111 everywhere. Any ideas? Any suggestion how I could catch the error in more detail to find the issue's source?
Tried to google problems with invoke-restmethod using a json-body. Sadly I'm not a Powershell pro...
Solved with help of a great colleague!
In my test enwironment I used two Horizon installations on Windows Server 2022 in an ENGLISH install. The other environment uses a source Horizon installation on a GERMAN server OS, but the target Horizon connection server runs on an ENGLISH OS. on the German based source install the admins made use of German special characters "äÄöÖüÜ".
In result the character set hast to be fixed to UTF-8 for the REST invocation:
$app_target = Invoke-RestMethod -Method Post -uri "$RESTurl_target/rest/inventory/v2/application-pools" -ContentType "application/json; charset=utf-8" -Headers (Get-HRHeader -accessToken $accessToken_target) -body $appJson
The part "application/json" has to become "application/json; charset=utf-8".
And that's it.
I'm using Powershell to automate a survey creation, adding a collector, and sending the survey invitation - a pretty common use case. I was able to create a survey but I'm running into an issue in creating the collector. I created a collector via Postman but I get the error "1001 - The body provided was not a property JSON string" when using Powershell. I've tried everything I can think of but continue to get the error no matter how I create the JSON. Here is the code I'm using:
$SurveyCollector = [PSCustomObject]#{ type = 'email' }
$BodyText = $SurveyCollector | Select-Object -Property type |ConvertTo-Json -Depth 100 -Compress
$Results = Invoke-RestMethod -Uri $uri -StatusCodeVariable "ExtIDscv" -SkipHttpErrorChe -Method
Post -ContentType "application/json" -Authentication Bearer -Token $SecureToken -body -$BodyText
I'm sure I'm missing something simple. I'd appreciate any help.
The answer was more simple than what tripleee suggested. I had introduced a -$BodyText into the call and didn't catch it. I removed it and it works just fine.
$Results = Invoke-RestMethod -Uri $uri -StatusCodeVariable "ExtIDscv" -SkipHttpErrorChe -Method
Post -ContentType "application/json" -Authentication Bearer -Token $SecureToken -body -$BodyText
I am trying to request information from one of our APIs using JSON however there is a lot which needs to be filtered out.
According to our API documentation, we have an "IncludeFields" query. How can I make it so when the information is requested, only information with "CS505MA001" is returned instead of the 100s of objects I'm getting.
$CommcellInfo = Invoke-RestMethod -Method Get -Uri $URL -Headers #{ "X- Auth-Token" = $Global:AuthToken; "includeFields" = "CS505MA001" }
$Include_Query = #{"includeFields"="CS505MA001"}
$ConvertedInclude_Query = ConvertTo-Json $Include_Query
$CommcellInfo = Invoke-RestMethod -Method Get -Uri $URL -Headers #{ "X-Auth-Token" = $Global:AuthToken }
I am trying to only show the returned information which contains certain text, how would I go about achieving this?
I am returning a web service call that supposedly comes back in json format, and it does indeed appear to be valid json. As a string, it looks like this:
{"total":10,"rows":[{"process":"VISIO.EXE","computer_id":57,"last_used":"2016-04-20T01:34:09Z"},{"process":"VISIO.EXE","computer_id":64,"last_used":"2016-04-01T04:09:35Z"},{"process":"VISIO.EXE","computer_id":181,"last_used":"2016-03-10T23:02:53Z"},{"process":"VISIO.EXE","computer_id":230,"last_used":"2016-04-19T05:31:32Z"},{"process":"VISIO.EXE","computer_id":237,"last_used":"2016-04-04T10:23:23Z"},{"process":"VISIO.EXE","computer_id":284,"last_used":"2016-04-15T10:54:29Z"},{"process":"VISIO.EXE","computer_id":8401,"last_used":"2016-05-12T21:55:39Z"},{"process":"VISIO.EXE","computer_id":9045,"last_used":"2016-05-12T08:10:40Z"},{"process":"VISIO.EXE","computer_id":9527,"last_used":"2016-05-11T00:49:11Z"},{"process":"VISIO.EXE","computer_id":10198,"last_used":"2016-05-06T06:59:29Z"}]}
I am trying to enumerate through the results, using the following script. I have tried all of the listed options 1-4 by uncommenting them out one at a time, but I cannot get more than one result to return.
Any ideas as to what I'm doing wrong?
$url = 'https://servername:port/api/sam/raw_app_usage_property_values?criteria={"and":[["process","=","visio.exe"]]}&limit=100&columns[]=process&columns[]=computer_id&columns[]=last_used'
# option 1. get all results, we see a full list of processes, full string returned
#$results = Invoke-WebRequest -Uri $url -Method GET -Headers $headers
#write-host $results
# option 2. get all results but break them down as part of the request. Only one result returned - #{total=10; rows=System.Object[]}
#$results = Invoke-WebRequest -Uri $url -Method GET -Headers $headers | ConvertFrom-Json
#write-host $results
# option 3. use a different method, which supposedly breaks down the request natively. Only one result returned - #{total=10; rows=System.Object[]}
#$results = Invoke-RestMethod -Uri $url -Method GET -Headers $headers
#write-host $results
# option 4. get content directly from file, only one result returned - #{total=10; rows=System.Object[]}
#$results = (Get-Content -path "C:\temp\raw_app_usage_property_values.json" -raw)
# is there anything in the array?
foreach ($result in $results) {
write-host $result
}
You seem to be getting the data back. Remember that the returned object has two properties, "total" and "rows".
Try:
foreach ($result in $results.rows) {
write-host $result
}
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.