Handling Forward Slashes ("//") In URL PowerShell - json

I have a script that successfully parses data from a URL featuring JSON data.
However, when I add a new URL, that includes a colon (":") followed by two forward slashes ("//"), the code errors out. I feel it's due to how the script is interpreting ("://") in the URL.
I tried to replace ("://") with (":%2F%2F") in the URL parameter but, that did not work either.
Here's the script:
$cred = "[MY TOKEN]"
$headers = #{ Authorization = "Bearer $cred"; Accept = "application/json" }
$Output = Invoke-RestMethod `
-Method Get `
-Headers $headers `
-ContentType: "application/json" `
-Uri "https://www.example.com/id_user://234kjh-2234jh-45645l"
$result = $Output | ConvertTo-Json
$result
The error is as follows:
Invoke-RestMethod : {"baseType":"error","code":"ServerError","message":"users.com
\"234kjh-2234jh-45645l\" not found","status":500,"type":"error"}
At line:4 char:13
+ $Output = Invoke-RestMethod `

Related

"Unexpected token" or "JSON parse error - trailing comma" when doing API call with PowerShell

I have the following PowerShell API script:
$VMname = "abcd"
$IP_address = '2.2.2.2'
$url = "https://ansibletower.xyz.com/api/v2/job_templates/12321/launch/"
$token = "9998980fsfdfsdfdf"
$headers = #{Authorization = "Bearer $token"}
$contentType = "application/json"
$method = "POST"
#### $body = '{"extra_vars": {"vm_name": "abc", "vm_ip_address": "2.2.2.2"}}'
$body = '{"extra_vars":{"vm_name":'$VMname', "vm_ip_address":'$IP_address'}}'
Invoke-RestMethod -ContentType "$contentType" -Uri $url -Method $method -Headers $headers -Body $body
When I try it with manually predefined values in the body (see the commented body line above) - it works. But when I try it with variables $VMname and $IP_address, I get the error:
Unexpected token '$VMname', "vm_ip_address":'$IP_address'}}''
expression or statement.
And if I remove single quotes before and after variables VMname and IP_address I get:
{"detail":"JSON parse error - Expecting value: line 1
column...Possible cause: trailing comma."}
It is obviously a problem with syntax and / or formatting but I cannot find the solution. Does anyone know?
Use ConvertTo-Json for this:
$VMname = "abcd"
$IP_address = '2.2.2.2'
$body = ConvertTo-Json -Compress -Depth 9 #{
extra_vars = #{
vm_name = $VMname
vm_ip_address = $IP_address
}
}
$Body
{"extra_vars":{"vm_name":"abcd","vm_ip_address":"2.2.2.2"}}
Btw, it is probably not even required to serialize your body to Json as Invoke-Restmethod is supposed to take care of that:
-body
When the input is a POST request and the body is a String, the value to the left of the first equals sign (=) is set as a key in the form data and the remaining text is set as the value. To specify multiple keys, use an IDictionary object, such as a hash table, for the Body.

MSGraph - Invoke-WebRequest (403) Forbidden

I have a delegate App with Directory.ReadWrite.All permissions and a PS script to auth users over the app. It works when I use GET but I'm getting Forbidden when try PATCH method
Here's the part of that script:
$uri = "https://graph.microsoft.com/v1.0/devices/1111-2222-3333-4444-5555"
$method = "PATCH"
$body = '{
"extensionAttributes": {
"extensionAttribute2": "text"
}
}'
Invoke-WebRequest -Method $method -Uri $uri -Body $body -ContentType "application/json" -Headers #{Authorization = "Bearer $token"} -UseBasicParsing -ErrorAction Stop
Another thing: when using device ObjectID to construct Uri I'm getting the 403 Forbidden but if I use a $filter over a DeviceID I get 405 Method not allowed. Does it mean it doesn't like a filter and have to stick with the ObjectID? Is there a way when I run the GET with $filter to save in a variable only ObjectID within JSON query?
Thanks
sorted it, I needed Directory.AccessAsUser.All and used this to get the objectId variable:
$DsregCmdStatus = dsregcmd /status
if($DsregCmdStatus -match "DeviceId")
{
$DeviceId = $DsregCmdStatus -match "DeviceID"
$DeviceId = ($DeviceId.Split(":").trim())
$DeviceId = $DeviceId[1]
}
# Find Id
$uri = "https://graph.microsoft.com/v1.0/devices?`$filter=deviceId eq '$DeviceId'"
$method = "GET"
# Run Graph API query
$query = Invoke-WebRequest -Method $method -Uri $uri -ContentType "application/json" -Headers #{Authorization = "Bearer $token"} -UseBasicParsing -ErrorAction Stop
$output = ConvertFrom-Json $query.Content
$id = $output.value
$id = $id.id
Write-Host "Machine ID is $id"

How to send UTF8 to the WordPress REST-API?

Malformed UTF-8 characters, possibly incorrectly encoded
Disclaimer: Character encodings confuse me a lot.
I want to create a lot of posts automated via the WordPress REST-API. I can create posts without an issue - unless I got special characters in my content. Emojis for example.
$params = #{
title = $Title
content = $Content # "foobar" would work just fine;
# "👎äöü" will give me an error
}
Invoke-RestMethod -Uri "https://my.blog.foo/wp-json/v2/posts" `
-Method POST `
-Headers #{ Authorization = ("Basic {0}" -f $ACCESS_TOKEN) } `
-ContentType "application/json" `
-UseBasicParsing `
-Body $($params | ConvertTo-Json)
I assume this actually isn't a WordPress related issue. Anyhow I'm fiddling aroundd for quite a while now and I just can't figure out a way to send my content without malforming ("ö" gets "?") it.
Use -ContentType "application/json; charset=utf-8"; instead.
If it doesn't work, You might also need to encode your body to UTF8 too.
$body = [System.Text.Encoding]::UTF8.GetBytes($body);
Complete example
$params = #{
title = $Title
content = $Content # "foobar" would work just fine;
# "👎äöü" will give me an error
}
$Body = $params | ConvertTo-Json
$Body = [System.Text.Encoding]::UTF8.GetBytes($body)
$Splat_Post= #{
ContentType = "application/json; charset=utf-8"
UseBasicParsing = $true
Method = 'POST'
Uri = "https://my.blog.foo/wp-json/v2/posts"
Headers = #{ Authorization = ("Basic {0}" -f $ACCESS_TOKEN) }
}
Invoke-RestMethod #Splat_Post-Body $Body
Note: I reworked the code to demonstrate splatting .
Should you need to call that method with all the same parameters each time except body, you could call it like that :
Invoke-RestMethod #Splat_Post -Body $Body then just changing the $Body to the content of your desires each time.
You could try and encode the body as UTF8 before posting it
-Body ([System.Text.Encoding]::UTF8.GetBytes(($params | ConvertTo-Json)))

Powershell Script to create user and add to servicedesk suddenly not working

last year I created a PS script, that took care of automatically creating users and adding them to our servicedesk, we use a special user creation account for this, the credentials are locally saved in a text file. It all worked fine, however the script doesn't seem to work anymore, did the JIRA API change?
I get following error message: Invoke-Rest-Method: The remote server returned an error (401) Unauthorized at response = Invoke-Rest-Method -Uri...etc
I checked and our user creation account still has all the permissions to create users, I can manually create them and the log shows that the user also logs in normally through the script.
Hopefully somebody can help with my problem!
Here's the code:
$jiraCredentials = Get-Content -Raw -Path "C:\PowerShellScripts\New-AdUser\credentials.json" |ConvertFrom-Json
$bytes = [System.Text.Encoding]::ASCII.GetBytes("${$jiraCredentials.username}:${$jiraCredentials.password}")
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.add("Authorization", $basicAuthValue)
$headers.add("X-Experimentalapi", "opt-in")
$headers.add("Content-Type", "application/json")
#$headers.add("X-Atlassian-Token", "nocheck")
$JSON = #"
{
"fullName": "$emailAddressClean",
"email": "$emailAddressClean"
}
"#
$response = Invoke-RestMethod -Uri https://jira.dilax.com/rest/servicedeskapi/customer -Method POST -Body $JSON -ContentType "application/json" -Headers $headers
#add customer to servicedesk
$JSON2 = #"
{
"usernames":[
"$emailAddressClean"
]
}
"#
$response2 = Invoke-RestMethod -Uri https://jira.dilax.com/rest/servicedeskapi/servicedesk/9/customer -Method POST -Body $JSON2 -ContentType "application/json" -Headers $headers
managed to fix it because the log in credentials didn't get transmitted correctly:
$jiraCredentials = Get-Content -Raw -Path "C:\PowerShellScripts\New-AdUser\credentials.json" |ConvertFrom-Json
$user = $jiraCredentials.username
$pass = $jiraCredentials.password
$pair = "${user}:${pass}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"

Invoke-RestMethod Powershell V3 Content-Type

I am able to use the JIRA rest API from powershell v5. However the same code throws the below error in powershell v3.
WARNING: Remote Server Response: The 'Content-Type' header must be modified using the appropriate property or method.
Source Code
$basicAuth = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Username):$Password"))
$headers = #{
"Authorization" = $basicAuth
"Content-Type"="application/json"
}
$response = Invoke-RestMethod -Uri $requestUri -Method POST -Headers $headers -Body $body
Invoke-Restmethod has a -ContentType parameter, so the error seems to be indicating you should use that to specify Content Type instead of passing it via the headers parameter:
$basicAuth = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Username):$Password"))
$headers = #{
"Authorization" = $basicAuth
}
$response = Invoke-RestMethod -Uri $requestUri -Method POST -Headers $headers -Body $body -ContentType 'application/json'