jenkins powershell plugin url encoding - powershell

I am trying to fetch gitlab project info using gitlab api. Below powershell script works perfectly fine in powershell ise
$projects = Invoke-WebRequest https://gitlab.mycompany.com/api/v4/projects/namespace%2fproject
But when using same script in jenkins powershell plugin, i always get error 404 Not found. I dont know if its an issue with url encoding or powershell script encoding.
I have tried below jenkins command with and without encoding
powershell (script:'''
$project = Invoke-WebRequest
https://gitlab.mycompany.com/api/v4/projects/namespace%2fproject
echo $project
''', encoding: 'UTF-8', returnStdout: true)
Any help will be appreciated

That's probably because your project is not public or requires authentication. Go to your account setting and then Access Token. Generate a new token, and then add it to your request header:
$gitUrl = "https://gitlab.mycompany.com/api/v4/projects/namespace%2fproject"
$head = #{'PRIVATE-TOKEN'= 'YourTokenHere'; 'Content-Type'='application/json'}
Invoke-WebRequest -Uri $gitUrl -headers $head
Also check Invoke-RestMethod, it will parse the response into psobject (very handy sometimes)

Related

How do I log on to JIRA in PowerShell using REST when basic authentication in plain text is blocked?

I've been trying to access our on-prem JIRA Server (configured with plain HTTP) using PowerShell Invoke-RestMethod, but I think I'm missing something.
The authentication header is created in base64
$cred = [convert]:.ToBase64String([text.encoding]::ASCII.GetBytes("account:password"))
$headers = #{Authorization = "Basic $cred"}
Using REST, I then ask for the issue (without posting any property filter to keep the request simple while I'm learning).
Invoke-RestMethod -Uri http://jiraserver:8080/jira-software/REST/agile/1.0/issue/test-1 `
-Headers $headers -ContentType "application/json" -AllowUnencryptedAuthentication
This obviously fails, as I get back a reply containing a login form
<form action="/login.jsp"
class="aui"
id="login-form"
method="post">
I do think I remember that basic authentication is no longer supported in JIRA.
How do I use OAuth in that case instead?
When working with another task that is well within the scope of AtlassianĀ“s PowerShell module JiraPS, I noticed a command called Invoke-JiraMethod.
It turns out that the module provides JIRA REST API access :)
So by setting up a JIRA session with the PowerShell module, I'll be able to use REST over an unencrypted connection.

why does API call not working in teamcity

I created a powershell script to call rest API. In powershell script I am calling post, get and put methods. script works fine in my machine and also works if I run powershell script directly on build agent machine.
But if I create a build step in team city and call .ps1 (powershell file) POST and GET methods are working but PUT method is not working. Build is failing with error :
"Invoke-RestMethod : {"code":404,"errors":[{}]}"
I used below syntax to call PUT API
Invoke-RestMethod -Uri $memberEditUrl -Method Put -Body $memberEditBody -ContentType "application/json"
I logged this command using Write-Host and after build run I went to build log and clicked on logged API URL and called in browser and it is working.
It's only team city where this is not working.
What could be the issue?
Try not to convert the forward slash "/" and colon ":" which I am replacing with %2F and %3A
Put api in single or double quotes "http://asd.com/abc:1234"
sample example for demo
$person = #{
first='joe'
lastname='doe'
}
$json = $person | ConvertTo-Json
$response = Invoke-RestMethod 'http://example.com/api/people/1' -Method Put -Body $json -ContentType 'application/json'
My problem was resolved by replacing slash ("/") with tilda "~" for parameter value. No change for colon ":" and it worked.

Getting a file from BitBucket Rest API v2.0

I have a script which grabs a file from GIT using the bitbucket REST API (1.0) however it has recently stopped working. I'm theorizing this may be due to the v1 REST API being depreciated but I'm not sure.
Anyway I am trying to retrieve the file using the new 2.0 REST API but I can't seem to get the syntax right as the request continually fails.
I'm starting out with curl since its easiest to test. This is what I'm trying:
curl -u myusername#mydomain.com "https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/downloads/Scripts/Environment Setup/test.txt"
Enter host password for user 'myusername#mydomain.com': redacted
{"type": "error", "error": {"message": "Resource not found", "detail": "There is no API hosted at this URL.\n\nFor information about our API's, please refer to the documentation at: https://developer.atlassian.com/bitbucket/api/2/reference/"}}
Here is the reference documentation I am using: https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/downloads/%7Bfilename%7D
Maybe I am using the wrong function? I'm not sure.
For posterities sake, you don't want to use the following to download an individual file from bitbucket:
https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/downloads/path/to/your/file.txt
("Downloads" is to download entire repo files like a .zip file)
Instead you want to do:
curl --user myuser#mydomain.com:password "https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/src/master/path/to/file.txt"
If you're trying to use Invoke-RestRequest (in powershell) note there are some extra steps. With the old 1.0 API you could do:
$cred = Get-Credential
$uri = "https://api.bitbucket.org/1.0/repositories/MyCompany/$($filepath)"
# Get the files from bitbucket (GIT)
Invoke-RestMethod -Credential $cred -Uri $uri -Proxy $proxyUri -OutFile $destination
With the new 2.0 API that no longer works. Powershell's Invoke-RestMethod waits for a 401 response before sending the credentials, and the new 2.0 bitbucket api never provides one, so credentials never get sent causing a 403 forbidden.
To work around that you have to use the following ugly hack to force Invoke-RestMethod to send the credentials immediately in an Authorization header:
$cred = Get-Credential
$uri = "https://api.bitbucket.org/2.0/repositories/MyCompany/$($filepath)"
$username = ($cred.GetNetworkCredential()).username
$password = ($cred.GetNetworkCredential()).password
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
# Get the files from bitbucket (GIT)
Invoke-RestMethod -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Uri $uri -Proxy $proxyUri -OutFile $destination
Hopefully that helps someone else out in the future!
Thanks #Jim Redmond for the help.
You can also use the PowerShell module BitbucketServerAutomation. There's not a ton of cmdlets, they do have Get-BBServerFile and Get-BBServerFileContent. I have found it is well written, very usable and being updated regularly. The Invoke-BBServerRestMethod cmdlet is available if you need a command it doesn't have.

What is the curl equivalent command in powershell for uploading the apk file?

I am trying to perform CI/CD using Perfecto and hence I am trying to upload a file to perfecto when my Bamboo build is finished.
I was trying with the following cURL command when we have a Linux server.
curl -X POST --upload-file test.apk 'https://****.perfectomobile.com/services/repositories/media/PRIVATE:test.apk?operation=upload&user=<email>&password=<password>&overwrite=true'
Now our server is changed to Windows and hence I want a powershell script which I can use as an Inline Scripts in Bamboo.
Can you please tell me what is an equivalent script in Powershell for windows.
Many thanks in advance.
# Gather your information.
$email = "myEmail#website.com";
$password = "powershellR0cks!";
$subDomain = "****";
$url = "https://$subDomain.perfectomobile.com/services/repositories/media/PRIVATE:test.apk?operation=upload&user=$email&password=$password&overwrite=true";
$filePath = ".\test.apk";
# Make the request.
$response = Invoke-WebRequest -Uri $URL -Method Post -InFile $filePath -ContentType "application/octet-stream";
# Check for success.
if (-not ($response.StatusCode -eq 200)) {
throw "There was an error uploading the APK manifest.";
}
You may want to check the value of -ContentType, but I think that's correct. You don't necessarily need to include the scheme (HTTPS) if you don't want to, and semicolons in PowerShell are optional, but you can include them if you want.
The $response variable is an HtmlWebResponseObject that has the content of the response, the status code, and a bunch of other useful info. You can check out the available properties and methods on the object by running $response | Get-Member.
Finally, the Invoke-WebRequest cmdlet also has other parameters that may be useful to you, such as -Credential, -Headers, and more.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-5.1
As a side-note, if you run Get-Alias -Name "curl", you can see that anytime you use curl in PowerShell, you're really just calling Invoke-WebRequest. You can use the curl alias if you want, but it's generally not a good idea to use aliases in automation since they can be modified or deleted.

Send login username with REST API + Powershell

I've got the following Powershell script:
$url = "http://somerandomapikeyhere#prestashop.dev/my-store/api"
$request = [System.Net.WebRequest]::Create($url)
$response = $request.GetResponse()
echo $response
which attempts to access my Prestashop API REST service.
I can access the URL from Chrome without a problem, but in PowerShell I get a 401 Unauthorized response, which is understandeable as the somerandomapikeyhere bit in the URL needs to get dealt with differently in PowerShell.
The question is, how? Any ideas / advice?
It's not powershel, but the .net class that is not able to take an url in that format. You need to provide the credentials seperate. See here or here.
But if you have powershell v3 you are better off using the build in commands for web requests or even REST requests.
Invoke-restmethod -uri 'prestashop.dev/my-store/api' -credential 'someapikey'