Powershell Invoke-Webrequest "No file part in file" CURL to Powershell - powershell

I'm trying to convert this working request done in Cygwin to Powershell:
Cygwin (Working):
curl -k -u curl:Password -X PUT -F "file=$($_)" https://$($appliance)/wse/customblockpage/file/en
Powershell (not working):
Invoke-Webrequest -Uri "https://$($appliance)/wse/customblockpage/file/en" -Method Put -Infile "$homePath\$($_)" -Credential $cred
Here is the error I get:
Invoke-Webrequest : { "Error": "No file part in file", "Result": "Failure" }
At line:1 char:1
+ Invoke-Webrequest https://{IP Address Masked}/wse/customblockpage/file/en ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

The { "Error": "No file part in file", "Result": "Failure" } is actually the error response from the web server and not a specific PowerShell error message.
In your cURL invocation, you are specifying form data with the -F flag, yet you don't appear to be doing the same in PowerShell.
In PowerShell, you can specify form data using the -Body flag like this:
Invoke-Webrequest -Uri "https://example.com/" -Method Put -Body #{ "file" = "hello.txt" }
If you need to send the actual content of the file, then you can use this as your -Body argument:
-Body #{ "file" = (Get-Content hello.txt) }

Related

powershell invoke rest api toward AWX

I'm struggling for last week or more with sending rest api command from powershell to add host in AWX(from curl is working). When I sent one parameter is worki but I need to send also variables
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Basic $VfAwxTokenX")
$Headers.Add('Content-Type', 'application/json')
$body = #{
name = '$vmname'
variables = 'test'
}| ConvertTo-Json
write-output $body
$response = Invoke-RestMethod 'https://awx/api/v2/inventories/2/hosts/' -Method 'POST' -Headers $headers -UseBasicParsing -Body $body
and error what i get:
{
"name": "wewewe",
"variables": "test" } Invoke-RestMethod : {"variables":["Cannot parse as JSON (error: Expecting value: line 1 column 1 (char 0)) or
YAML (error: Input type str is not a dictionary)."]} At line:32
char:13
$response = Invoke-RestMethod 'https://awx/api ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod],
WebException
FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Maybe any one of users had that issue and now how to overcome it?
According to my research, the parameter variables should be defined as JSON or YAML format. For more details, please refer to here.
For more details about how to call the API, please refer to the blog.
the problem was prosaic
variables = 'test'
if i put anything else then test is working :/

Powershell - Scripts runs in ISE as expected. When calling from command line it errors

I have a script that calls an internal API. It gets passed a token and a json body.
When I hard code the parameters (token and json_body) in ISE, it runs great. As soon as I run from the command line, it bombs. I get an error "Can't process argument because the argument "name" is not valid."
Just a note. The param $json_body can be very large.
Here is my script. Super simple and works as expected
PARAM($json_body, $token)
$json_body =
'{
"field1" : "1",
"field2" : "2",
"data" : [{<json data here>}]
}'
$header = #{'Token' = '1234567890* '}
Invoke-WebRequest -Uri <uri-here> -Method POST -ContentType "application/json" -Headers $header -Body $json_body
Here's the command I'm using
powershell.exe -executionpolicy bypass -inputformat none -file "C:\PowerShell\Call_Rest_API_And_Post.ps1" -token <token_text> -json_body <json_body_text>
I'm passing data from an ETL process to push data to parameters, but if I run this directly from PowerShell (not ISE) I get this error:
Invoke-WebRequest : An unknown error occurred. Please see server logs for details.
At C:\PowerShell\Call_Rest_API_And_Post.ps1:5 char:1
+ Invoke-WebRequest -Uri <uri-here> ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Any pointers?

Using power shell to right a put method for SSRS API deployment for setting shareddataset

I want to use PowerShell to set shareddataset for a report using SSRS API.
I have already tried to use PowerShell to get shareddataset using SSRS API successfully. But failed to use put method.
Success using get method:
$Cred = Get-Credential
$Url = "http://localhost/Reports/api/v2.0/DataSets"
`
`$Body = #{
Path ="/Shared_data_sets/P_Calculate_date_Default_key";
output_mode = "csv";
earliest_time = "-2d#d";
latest_time = "-1d#d";
}
Invoke-RestMethod -Method 'GET' -Uri $url -Credential $Cred -Body $body -OutFile output.csv
failed using put method:
$Cred = Get-Credential
$Url = "http://localhost/Reports/api/v2.0/Reports(23a6af79-9de3-49cb-b66b-625d3ff3909b)/SharedDataSets"
$Body = #{
Id = "935be257-5a65-4c0d-b372-d5a6a188daf6";
Name = "P_Calculate_Date_Default_Key";
Path = "/Shared_data_sets/P_Calculate_date_Default_key";
Type = "DataSet" ;
}
Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method 'PUT'
Error returned is
The remote server returned an error: (400) Bad Request
detailed error:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request. At line:12 char:1 + Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method 'PU ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I hope the put method could be working. I thought I was using the same way as the get method but it still failed.
I tried another way but still failed :
$Cred = Get-Credential
$Url = "http://localhost/Reports/api/v2.0/Reports(23a6af79-9de3-49cb-b66b-625d3ff3909b)/SharedDataSets"
$Body = #{
Id = "935be257-5a65-4c0d-b372-d5a6a188daf6"
Name = "P_Calculate_Date_Default_Key"
Path = "/Shared_data_sets/P_Calculate_date_Default_key"
Type = "DataSet"
}| ConvertTo-Json
Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method PUT -ContentType "application/json" | Out-Null
Just for you to know that for the put method, i have already tested on postman and it works. So I guess currently it is only due to some logic in powershell side inconsistent.
in postman I put the link as :
http://localhost/Reports/api/v2.0/Reports(23a6af79-9de3-49cb-b66b-625d3ff3909b)/SharedDataSets
Body as :
[
{
"Id": "935be257-5a65-4c0d-b372-d5a6a188daf6",
"Name": "P_Calculate_Date_Default_Key",
"Path": "/Shared_data_sets/P_Calculate_date_Default_key",
"Type": "DataSet"
}
]
I tried your recommendation and it shows below , I have added it below all:
PS C:\Users\dkx42a8adm> $Cred = Get-Credential
$Url = "http://localhost/Reports/api/v2.0/Reports(23a6af79-9de3-49cb-b66b-625d3ff3909b)/SharedDataSets"
$Body = #{
Id = "935be257-5a65-4c0d-b372-d5a6a188daf6"
Name = "P_Calculate_Date_Default_Key"
Path = "/Shared_data_sets/P_Calculate_date_Default_key"
Type = "DataSet"
}| ConvertTo-Json
Write-Output $Body
Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method PUT -ContentType "application/json"
$error[0]|format-list -force
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
{
"Path": "/Shared_data_sets/P_Calculate_date_Default_key",
"Name": "P_Calculate_Date_Default_Key",
"Id": "935be257-5a65-4c0d-b372-d5a6a188daf6",
"Type": "DataSet"
}
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At line:14 char:1
+ Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method PUT ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Exception : System.Net.WebException: The remote server returned an error: (400) Bad Request.
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
TargetObject : System.Net.HttpWebRequest
CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at , : line 14
PipelineIterationInfo : {}
PSMessageDetails :

Invoke-WebRequest command fails only when run as script

I have this function in a powershell script to deploy a war file to a tomcat server. Similar functions for the other tomcat commands (stop, undeploy, list, etc) work fine. When I run the script from a shell it works. When I run the script from the Jenkins Powershell plugin it fails.
Function DeployTomcatWebApp([PSCredential]$cred, [string]$server, [string]$app)
{
Write-Host "Deploying $app"
$uri = $server+"/manager/text/deploy?path=/$app&update=true"
$warpath = ($pwd).path + "/$app/build/dev/$app.war"
$r = Invoke-WebRequest -Uri $uri -Credential $cred -InFile $warpath -UseBasicParsing -Verbose -Debug -Method PUT -TimeoutSec 30000 -DisableKeepAlive
Write-Host $r.Content
Return $r
}
The Console Log shows
Deploying DERF
D:\Jenkins\workspace\JenkinsTest_2_AD_DERF\DERF\build\dev\DERF.war
http://mytomcat:8080/manager/text/deploy?path=/DERF&update=true
VERBOSE: PUT http://mytomcat:8080/manager/text/deploy?path=/DERF&update=true with -1-byte payload
Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At C:\Users\<jenkinsuser>\AppData\Local\Temp\jenkins1024175502034764284.ps1:49 char:10
+ $r = Invoke-WebRequest -Uri $uri -Credential $cred -InFile $warpa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
The Jenkins Powershell plugin extracts the script from the jenkins job and create the .ps1 file in Local/Temp and executes the script by calling
powershell -NonInteractive -ExecutionPolicy Bypass <tempscriptname>
I am stumped and looking for any insight to debugging this.

Running PowerShell code in powershell works, executing as .ps1 doesn't

I wrote some code which tries to Get a value from one Rest API and post it to another.
I have the code saves in a .ps1 file. If I edit it and run it (or just copy and paste it into an empty PowerShell terminal) it does what I expect. However when I try to run the same .ps1 file directly I get an error on the 2nd Invoke-RestMethod.
Don't understand why I'm getting a different result and the error message not giving me many clues.
What am I doing wrong?
The code I am using is (with modified API key):
$encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($APIkey+":"))
$headers = #{"Content-Type" = "application/json"; "AUTHORIZATION" = "Basic $encoded"}
$APIkey = "123456789"
$metricId = "123"
$r = Invoke-RestMethod -Uri https://coinbase.com/api/v1/currencies/exchange_rates
$metric = [PSCustomObject]#{
value = [Math]::Round($r.btc_to_eur, 2)
}
$baseuri = "https://api.numerousapp.com/v1/metrics/$metricId/events"
$data = ConvertTo-Json $metric
Invoke-RestMethod -Uri $baseuri -Body $data -Headers $headers -Method Post
And the error message I get when running the .ps1 file is:
Invoke-RestMethod : :
At C:\NumerousBitcoinEur.ps1:13 char:1
+ Invoke-RestMethod -Uri $baseuri -Body $data -Headers $headers -Method Post
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I'm using PowerShell 4.0
$APIkey is being set after it is being used, which must be wrong. It probably works in the console because $APIkey happens to already be set.
If you like (I think it's a good idea), you can add the following to the top of your scripts to catch errors like this one.
Set-StrictMode -Version Latest