I'm trying to pass an image in power shell replicating this cURL request
curl -u user:apikey -F ‘data=#1234.jpg’
https://denton.gradesfirst.com/api/users/pictures
I authenticate fine but don't know to replicate ‘data=#1234.jpg’ in powershell so the other system will know where the picture is.
$username = "username"
$password = "apikey"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
Invoke-RestMethod -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -uri "https://test.test.test.com/api/users/pictures" -Method Put -InFile "C:\Users\username\Downloads\pic-2017\210569.jpg" -ContentType 'image/jpg'
This is a common mis-nomer that you must use invoke-restmethod.
This should work for you. If you need to input the creds non-interactively, simply save them to a file and then pull them in to the same $cred variable - the commands remain the same.
$creds = Get-Credential
$url = "https://denton.gradesfirst.com/api/users/pictures"
Invoke-WebRequest -Credential $creds -Method Post -Uri $url -ContentType "application/x-www-form-urlencoded" -InFile "1234.jpg"
Related
Getting this error when trying to update a role to an endpoint using Powershell. It is crating the endpoints, just the roles update is giving error. same role update api call command works from postman.
$ApplyRole="https://Myorg/_apis/securityroles/scopes/distributedtask.serviceendpointrole/roleassignments/resources/72505f4d-564c-41cf-14508b977f52_f6a1c4f9-a043-4399-1aad7b5cf19c/?api-version=5.0-preview"
$ApplyRole = "https://Myorg/_apis/securityroles/scopes/distributedtask.serviceendpointrole/roleassignments/resources/72505f4d-564c-41cf-14508b977f52_f6a1c4f9-a043-4399-1aad7b5cf19c/?api-version=5.0-preview"
$Body1 = #{
roleName = "User"
userId = "f0e736e3-0e73-4fd2-8b7a-615126eac692"
}
$Bodyjson = $Body1 | ConvertTo-Json
Invoke-RestMethod -uri $ApplyRole -Method Put -Credential $mycreds -Body $Bodyjson -ContentType "application/json"
Error:
Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Object reference not set to an instance of an object.","typeName":"System.NullReferenceException,
mscorlib","typeKey":"NullReferenceException","errorCode":0,"eventId":0}
Thanks for the reply.
Actually it was an issue with the body syntax.
Added like this and it works.
$Body1 = #"
[{
"roleName":"User",
"userId":"f0e736e3-0e73-4fd2-8b7a-615126eac692"
}]"#
Open pipeline definition->click the tab variables->add variable pat and change variable type to secret.
Add task powershell and enter the script.
$connectionToken="$(pat)"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$ApplyRole = "https://Myorg/_apis/securityroles/scopes/distributedtask.serviceendpointrole/roleassignments/resources/{project id}_{endpoint id}/?api-version=5.0-preview"
$body ="[{
`"roleName`": `"User`",
`"userId`": `"{group or user id}`"
}]"
$Roles = Invoke-RestMethod -Uri $ApplyRole -ContentType "application/json" -Body $body -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method PUT
Result:
I'm using PowerShell inline task in the release pipeline to deploy the respective zip file to the Azure App Service, but im unable to achieve it due to the below error. Can you please let me know if there is any thing that im missing here.
I'm getting below error
Invoke-RestMethod : Path 'D:\a\r1\a_CI-VI-Maven/DeployPackages/marnet.zip' resolves to a directory. Specify a path including a file name, and then retry the command.
Below is the script that im using:
$username = "username"
$password = "pwd"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password)))
$userAgent = "powershell/1.0"
$apiUrl = "https://{appservice}.scm.azurewebsites.net/api/zip/site/wwwroot/webapps/"
$filePath = "$(System.DefaultWorkingDirectory)_CI-VI-Maven/DeployPackages/marnet.zip"
Invoke-RestMethod -Uri $apiUrl -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method POST -InFile $filePath -ContentType "multipart/form-data"
Check your folder structure, it seems that you have a folder named marnet.zip!
Your issue occurred since the $filePath = "$(System.DefaultWorkingDirectory)_CI-VI-Maven/DeployPackages/marnet.zip" is a path to folder marnet.zip instead of a real marnet.zip file.
My reproducible steps:
1.Everything works well when my s.zip file locates directly under build artifacts folder.
2.Change something in Build pipeline to create s.zip folder, and move the s.zip file to this folder.
3.Then, same issue occurs:
Looking here
$username = "`$website"
$password = "pwd"
# Note that the $username here should look like `SomeUserName`, and **not** `SomeSite\SomeUserName`
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password)))
$userAgent = "powershell/1.0"
# Example 1: call the zip controller API (which uses PUT)
$apiUrl = "https://{sitename}.scm.azurewebsites.net/api/zip/site/wwwroot/"
$filePath = "C:\Temp\books.zip"
Invoke-RestMethod -Uri $apiUrl -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method PUT -InFile $filePath -ContentType "multipart/form-data"
# Example 2: call the zipdeploy API (which uses POST)
$apiUrl = "https://{sitename}.scm.azurewebsites.net/api/zipdeploy"
$filePath = "C:\Temp\books.zip"
Invoke-RestMethod -Uri $apiUrl -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST -InFile $filePath -ContentType "multipart/form-data"
So if you want to use zip controller API please change your verb to PUT insted of POST.
Trying to connect to a REST-API via Powershell client. When testing the endpoint in Postman, I have no problems at all. Here's the main part of the function (I have a [pscredential]$Creds parameter that I use to get the username and password):
[string]$username = $Creds.UserName
[string]$password = (New-Object System.Net.NetworkCredential($Creds.UserName, $Creds.Password, 'Null')).Password
[string]$authorizationInfo= ([Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(('{0}:{1}' -f $username, $password))))
Invoke-WebRequest -Uri "https://$($HostName)/api/" -Method Get -Headers #{Authorization = ('Basic {0}' -f $authorizationInfo)}
For some reason the Authorization header is different in my script than in Postman. I can even copy the Authorization header out of Postman and paste it into the -Headers parameter and everything works fine. I just don't see where I'm getting this wrong.
I can't tell you why that's not working, but I can suggest something that works for me all the time with APIs:
$auth = $username + ':' + $upassword
$Encoded = [System.Text.Encoding]::UTF8.GetBytes($auth)
$authorizationInfo = [System.Convert]::ToBase64String($Encoded)
$headers = #{"Authorization"="Basic $($authorizationInfo)"}
Invoke-WebRequest -Uri "https://$($HostName)/api/" -Method GET -Headers $headers
If that doesn't work, try this subtle difference with Invoke-Restmethod:
Invoke-RestMethod -Uri "https://$($HostName)/api/" -Method GET -Headers $headers
Working with APIs is always an adventure. Keep trying. :)
I am trying to auto deploy build on azure. For this i use powershell script to upload zip on azure. There is two part of the script -> First to clean the wwwroot folder and second part is to upload zip to wwwroot. It runs successfully when i run script through Powershell exe but gives error when run through Jenkins. Strange thing is, it successfully runs first part but gives error on second part.
Powershell Script :
$username = "`$347testpass"
$password = "xyz"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password)))
$userAgent = "powershell/1.0"
#Clean wwwroot folder
$apiUrl1 = "https://347testpass.scm.azurewebsites.net/api/command"
$commandBody = #{
command = "rmdir D:\home\site\wwwroot /Q /S"
}
Invoke-RestMethod -Uri $apiUrl1 -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST ` -ContentType "application/json" -Body (ConvertTo-Json $commandBody) | Out-Null
#Upload zip file
$apiUrl = "https://347testpass.scm.azurewebsites.net/api/zip/site/wwwroot/"
$filePath = "D:\AzureWeb\Upload\qwerty.zip"
Invoke-RestMethod -Uri $apiUrl -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method PUT -InFile $filePath -ContentType "multipart/form-data"
Error display in Jenkins Console :
Invoke-RestMethod : The request was aborted: The request was canceled.
At C:\Users\Harsh.Sharma\AppData\Local\Temp\hudson8158442147919891501.ps1:34
char:1
+ Invoke-RestMethod -Uri $apiUrl -Headers #{Authorization=("Basic {0}" -f
$base64A ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-RestMethod], WebExcept
ion
+ FullyQualifiedErrorId : System.Net.WebException,Microsoft.PowerShell.Com
mands.InvokeRestMethodCommand
Finally it works after added couple of thing like timeout, change Method type, security protocol tls12.
$apiUrl = "https://347testpass.scm.azurewebsites.net/api/zipdeploy"
$filePath = "C:\BuildDeploymentAzureEnterprise3.4\Unzipped\AzureBuildFiles.zip"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-RestMethod -Uri $apiUrl -DisableKeepAlive -TimeoutSec 1000 -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -UserAgent $userAgent -Method POST -InFile $filePath -ContentType "multipart/form-data"
Try using -DisableKeepAlive with Invoke-RestMethod.
I'm trying to access a Swagger based API using powershell invoke-restmethod with websession to (hopefully) capture the cookies/session information I'd need to do a post method.
I start by requesting a CSRF
$CSRF = Invoke-RestMethod -Uri ($Uri+'csrf-token') -Method Get -Credential $Creds -ContentType 'application/json'-SessionVariable websession
and I can see the correct token value without any issues. Looking at the websession variable I do have some data, but I don't get any cookie values at all. Thus if I submit a second request using the session variable:
Invoke-RestMethod -Method Post -Uri ($Uri+'post') -Headers $Header -Body $Body -Credential $creds -WebSession $websession
it fails due to the missing cookie values. If I do a normal request via Firefox I see cookies with a jsessionid, etc but I don't know how to get these values somewhere where I can use them (please excuse me ignorance here- I'm relatively new to the invoke-restmethod in PS)
I've sussed it out (at last- very painful) - I had to build my own cookie:
$CSRF = Invoke-RestMethod -Uri ($Uri+'csrf-token') -Method Get -Credential $Creds -ContentType 'application/json' -SessionVariable websession -MaximumRedirection 0
$CSRFToken = $CSRF.tokenValue
# Capture cookie
$cookiejar = New-Object System.Net.CookieContainer
$cookieUrl = $uri +'csrf-token'
$cookieheader = ""
$webrequest = [System.Net.HTTPWebRequest]::Create($cookieUrl);
$webrequest.Credentials = $creds
$webrequest.CookieContainer = $cookiejar
$response = $webrequest.GetResponse()
$cookies = $cookiejar.GetCookies($cookieUrl)
# add cookie to websession
foreach ($cookie in $cookies) {$websession.Cookies.Add((Create-Cookie -name $($cookie.name) -value $($cookie.value) -domain $apiserverhost))}
# Finally, I can post:
Invoke-RestMethod -Method Post -Uri ($Uri+'versions/createVersionRequests') -Headers $Header -Body $Body -Credential $creds -WebSession $websession
Hope that helps someone else (I've spent hours pulling my hair out over this!)