I'm not able to understand why my code is failing.
$Param = #{
Uri = ("https://api.crowdstrike.com/policy/combined/reveal-uninstall-token/v1")
Method = 'post'
Headers = #{
'Content-type' = 'application/json'
authorization = "$($Token.token_type) $($Token.access_token)"
}
}
$data = #{
audit_message="test api"
device_id='111111111111111111111111111'
}
$json = $data | ConvertTo-Json
$uninstall = Invoke-RestMethod #Param -Body #json
Error:
Invoke-RestMethod : A positional parameter cannot be found that accepts argument ''.
At line:48 char:14
+ $uninstall = Invoke-RestMethod #Param -Body #json
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-RestMethod], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I'm passing the data as JSON (as required per the below screen shot):
[![enter image description here][1]][1]
Any hints please ?
Thank you !
[1]: https://i.stack.imgur.com/eeRaj.png
Related
Problem
I am unable to use an Environment Variable as a token in an Invoke-RestMethod
I have the following code, that does work:
$props = #{
Uri = $my_url
Method = "POST"
ContentType = "application/json"
Headers = #{ Authorization = "Bearer Token123456789" }
}
$payload = Invoke-RestMethod #props
But I don't want the token hard-coded here.
However, if I replace Token123456789 with the environment variable $env:token which contains the identical token, it fails.
$props = #{
Uri = $my_url
Method = "POST"
ContentType = "application/json"
Headers = #{ Authorization = "Bearer $env:token" }
}
$payload = Invoke-RestMethod #props
The error message is
Invoke-RestMethod : Specified value has invalid Control characters.
Parameter name: value
At C:\Temp\test.ps1:29 char:12
$payload = Invoke-RestMethod #props
CategoryInfo : NotSpecified: (:) [Invoke-RestMethod], ArgumentException
FullyQualifiedErrorId :
System.ArgumentException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
What I have tried
I have tried comparing them directly, like this
$bearer1 = "$env:token"
$bearer2 = "Token123456789"
echo $bearer1
echo $bearer2
echo ($bearer1 -eq $bearer2)
The first two echo's output the same results.
However, the last one returns False
Conclusion
The Environment Variable for some reason does not equal its string equivalent.
How do I turn the environment variable into this identical string so that it will work in my Invoke-RestMethod?
I have been working with Powershell all day, playing with proxy settings and related. A POST request that once worked earlier in the day, is now stating a very bizarre error:
The request:
$tenantId = '8331e1..........'
$client_id = 'a3b869ef................
$client_secret = '0w;m$................'
#************ GET AAD TOKEN ************
$url = "https://login.microsoftonline.com/" + $tenantId + "/oauth2/token"
$body = #{
grant_type = 'client_credentials'
client_id = $client_id
client_secret = $client_secret
resource = 'https://dev.azuresynapse.net'
}
$GetAADResult = Invoke-WebRequest -Method 'Post' -Uri $url -Body $body
$GetAAD_Content_JSON = $GetAADResult.Content | ConvertFrom-Json
$access_token = $GetAAD_Content_JSON.access_token
# print access_token
$access_token
This used to provide a simple token as a response, but now it is returning the error:
Invoke-WebRequest : The remote name could not be resolved: 'http'
At line:24 char:17
+ ... GetAADResult = Invoke-WebRequest -Method 'Post' -Uri $url -Body $body
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : System.Net.WebException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
ConvertFrom-Json : Cannot bind argument to parameter 'InputObject' because it is null.
At line:26 char:48
+ $GetAAD_Content_JSON = $GetAADResult.Content | ConvertFrom-Json
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [ConvertFrom-Json], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
I do not know what needs to change to get this functionating again, it appears PowerShell is looking for a proxy setting in every request...? Anny ideas?
I ended up undoing these steps: https://spaghettidba.com/2017/12/19/recovering-the-psgallery-repository-behind-a-corporate-proxy/
Goal: I want to send a POST API request to JIRA with irm (Invoke-RestMethod).
Environment:
OS: Windows 10 64 bit
Powershell 5 (I think it's 5, it's the default that comes with Windows)
Script:
$Body = #{
'fields' = #{
'project' = #{'key' = 'ABC'}
'summary' = "summary"
'description' = "desc"
'issuetype' = #{'name' = 'Test'}
'assignee' = 'user'
}
}
$JsonBody = ($Body | ConvertTo-Json)
$params = #{
Uri = "https://jira.myjira.co.uk/rest/api/latest/issue"
Headers = #{ "Authorization" = "Basic myToken" }
Method = "POST"
Body = $JsonBody
ContentType = "application/json"
}
$response = irm $params
$response | Out-File test.txt
When I execute it, I get the message below. Powershell is complaining but I don't know what is wrong with my parameters.
Invoke-RestMethod : Cannot bind parameter 'Uri'. Cannot convert the "System.Collections.Hashtable" value of type
"System.Collections.Hashtable" to type "System.Uri".
At C:\Users\User\Downloads\MyScript.ps1:64 char:17
+ $response = irm $params
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-RestMethod], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
What I've tried:
Executed it in ISE and it does the same thing
I used the #params format for another script and it was fine. I wonder if the issue is with the Uri part...
Googling and looking at stackoverflow, there was similar matches but doesn't fit my scenario
Any help is appreciated, I've been banging my head against a wall for an hour.
Simply change the $params to #params, this is called splatting.
"Splatting is a method of passing a collection of parameter values to a command as a unit."
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-7.1
$response = irm #params
I would like to use an POST request with powershell but am getting the following errormessage. I have searched many hours, but can't find the problem. The json body seems also to be correct(?).
Thanks in advance for every help!
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
(New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$body = #{
"client"="myKey"
"request-type"="authentication"
"username"="myUsr"
"password"="myPwd"
} | ConvertTo-Json -Depth 10
$header = #{
"Content-Type"="application/x-www-form-urlencoded"
}
$res = Invoke-RestMethod -Uri "https://myUrl:4000/abc" -Method 'POST' -Body $body -Headers $header
Invoke-RestMethod :
Error
Cannot POST /abc
In Zeile:1 Zeichen:8
+ $res = Invoke-RestMethod -Uri "https://myUrl:400 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Edit:
I have edited my code but get the same error:
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
(New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$body = #{
"client"="mykey"
"request-type"="authentication"
"username"="myusr"
"password"="mypw"
}
$res = Invoke-RestMethod -Uri "https://myUrl:4000/abc" -Method 'POST' -Body $body
And the 400 error is'nt a error code, I think it's the port.
Invoke-RestMethod :
Error
Cannot POST /abc
In Zeile:1 Zeichen:8
+ $res = Invoke-RestMethod -Uri "https://myUrl:400 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
The request should look like the following:
client=sadsda42424242&request-type=authentication&username=extern&password=geheim
Also I have to use the content type „application/x-www-form-urlencoded“.
I have killed 3 hours today and don't understand why?
I have easy script:
$user = 'icm'
$pass = 'icm'
$pair = "$($user):$($pass)"
$url = 'http://####:15672/api/queues/%2f/ICM.Payments.Host.1'
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$headers = #{
Authorization = $basicAuthValue
}
$request = Invoke-WebRequest -Uri $url -Headers $headers -ContentType "application/json"
$messages = ($request.Content | ConvertFrom-Json | Select -ExpandProperty messages)
$messages
So, via PS ISE it works perfectly, but via powershell.exe I see an error below.
Invoke-WebRequest : {"error":"Object Not Found","reason":"\"Not Found\"\n"}
At C:\Temp\Untitled1.ps1:16 char:12
+ $request = Invoke-WebRequest -Uri $url -Headers $headers -ContentType ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
ConvertFrom-Json : Cannot bind argument to parameter 'InputObject' because it is null.
At C:\Temp\Untitled1.ps1:17 char:33
+ $messages = ($request.Content | ConvertFrom-Json | Select -ExpandProp ...
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [ConvertFrom-Json], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
Proof attached.
I had also the same problem with RabbitMQ, the cause is the escaping of %2f in URL.
See Percent-encoded slash (“/”) is decoded before the request dispatch
With the tricks of the above answer, it works both in ISE and console :
$urlFixSrc = #"
using System;
using System.Reflection;
public static class URLFix
{
public static void ForceCanonicalPathAndQuery(Uri uri)
{
string paq = uri.PathAndQuery;
FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
ulong flags = (ulong) flagsFieldInfo.GetValue(uri);
flags &= ~((ulong) 0x30);
flagsFieldInfo.SetValue(uri, flags);
}
}
"#
Add-Type -TypeDefinition $urlFixSrc -Language CSharp
$url = [URI]$url
Invoke-WebRequest -Uri $url -Headers $headers -ContentType "application/json"