Powershell API Data Extraction - powershell

I'm getting data back from an API for a system of ours using Powershell but it doesn't quite return it correctly. It is putting the data all under one header as seen below. I'm trying to extract the downloadLink part only
Tried converting to JSON to see if I could get anywhere else with it.
$token = ".."
$web = Invoke-RestMethod -uri $url -Method Get -Headers #{'Authorization' = $token}
echo $web
I get this as the outcome:
documents
---------
{#{documentName=Name.docx.pdf; downloadLink=https://app.xxx.com/api/docs/employees/111/shared/111}, {#{documentName=Name.docx.pdf; downloadLink=https://app.xxx.com/api/docs/employees/111/shared/111} ...
What I need to get is the downloadLink, but as it's all coming under the documents header I can't do a simple select or get on it.

Have you tried converting the results from JSON using ConvertFrom-Json? See the code example below.
Please note the change I made to the ContentType to the Invoke-RestMethod as well.
$token = ".."
$web = Invoke-RestMethod -uri $url -Method Get -ContentType "application/json" -Headers #{'Authorization' = $token}
$webResults = $web | ConvertFrom-Json
echo ($json | ConvertFrom-Json).downloadLink

Related

Issue with for each loop with Invoke-RestMethod

I am currently having issues creating a powershell script that taks to an api with Invoke-RestMethod and a loop, I have spent all day trying to figure out where i am going wrong but i have not managed to come up with something.
Here is the code that i am trying to make
$url = "/api/Rest/v1"
$Body = #{
Username = ""
Password = ""
Privatekey = ""
}
$apikey = Invoke-RestMethod -Method 'Post' -Uri $url/Authenticate -Body $body
$headers = #{
'Authorization' = $apikey
}
$allusers = Invoke-RestMethod -Uri $url/Users -Method Get -Headers $headers | ft -HideTableHeaders Id
foreach ($userid in $allusers)
{
echo $userid
Invoke-RestMethod -Uri $url/Users/$userid -Method Get -Headers $headers
echo "test"
}
I am not having issues with the veriables $apikey and $allusers as they seem to output what i need but i think my issue is to do with the outbut being in format table but i have tried other methods for the for each and i have no clue where i am going wrong
So i have tested the Invoke-RestMethod commands on there own and they work as exspected but when i try the script above i get the following.
Invoke-RestMethod : {"Message":"User with specified id was not found."}
the output of $allusers displays something like the following for the user ID
dce502ed-e4b6-4b5e-a047-0bf3b34e98c6
dc1e60c1-99a7-479a-a7d6-0dc618c8dd5e
1bd98bb0-a9ee-46b5-8e2e-0e3146aab6b3
AKA the following work with no issues and outputs what i need
Invoke-RestMethod -Uri $url/Users/1bd98bb0-a9ee-46b5-8e2e-0e3146aab6b3 -Method Get -Headers $headers
I would really appreciate some kind of guidance on this.
The standard advice applies:
Format-* cmdlets (such as Format-Table, whose built-in alias is ft) emit output objects whose sole purpose is to provide formatting instructions to PowerShell's for-display output-formatting system.
In short: only ever use Format-* cmdlets to format data for display, never for subsequent programmatic processing - see this answer for more information.
Therefore, remove the | ft -HideTableHeaders Id pipeline segment and use member-access enumeration to extract all .Id property values as data.
$allusers = (Invoke-RestMethod -Uri $url/Users -Method Get -Headers $headers).Id

Extract releases from azure DevOps projects organization

I have an Azure DevOps organization with more 300 project and I want to extract release from the org for all DevOps project. I have tried using below PowerShell script but it is just giving 100 record at a time. and also it is saying that extracted json file is not in valid format.
Here is my PowerShell script.
$token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
$url = "https://dev.azure.com/{orgnization}/_apis/projects?api-version=6.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token" } -Method Get -ContentType application/json
Foreach ($projectName in $response.value.name) {
$url1 = "https://vsrm.dev.azure.com/{orgnization}/$($projectname)/_apis/release/releases?api-version=6.0"
$response = Invoke-RestMethod -Uri $url1 -Headers #{Authorization = "Basic $token" } -Method Get -ContentType application/json-patch
echo $response | ConvertTo-Json -Depth 99 | Out-File "D:\\file.json" -Append
}
I tried adding $top parameter with first API call which works fine if I am trying in browser but in PowerShell it is not working.
https://dev.azure.com/uniperteamservices/_apis/projects?api-version=6.0&$top=500
How can I accomplish my below two requirement?
How can extract all record, not just 100
Why extracted json file is showing as invalid format when I am converting to excel?
If you can modify above PowerShell script for my requirement, it will be appreciated.
Thanks
Step through your code in a debugger.
$top wrapped in double quotes will try to interpolate a variable named $top. You need to escape the $ with a ` character. i.e.
`$top

Azure devops Work Item types API returns string instead of JSON

When I try to get work item types via PowerShell, I get a string instead of the expected JSON.
This is my PowerShell code:
$Token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PAT)"))
$JsonContentType = 'application/json-patch+json'
$Header = #{Authorization = 'Basic ' + $Token;accept=$JsonContentType}
$BaseUri = "https://dev.azure.com/$($Organisation)/"
$Uri = $BaseUri + "$Project/_apis/wit/workitemtypes?api-version=5.1"
$Result = Invoke-RestMethod -Uri $uri -Method GET -Headers $Header
$Result
I also tried with the newer version 6.0, but it also returns a string instead of JSON.
Other responses are fine, for example:
$Uri = "https://dev.azure.com/$($Organisation)/_apis/projects?api-version=5.1"
$Projects = Invoke-RestMethod -Uri $Uri -Method get -Headers $Header
This correctly returns JSON, or if I request a work item, I also get JSON.
I cannot figure out why this is...
Any ideas anyone?
The Invoke-Rest-Method tries to return a PSCustomObject, which does not support properties without names and thus the conversion fail and you get the plain string back:
From Invoke-RestMethod fails to parse JSON response
The problem is that by default, Invoke-RestMethod tries to convert the
json to a PSCustomObject. However, PSCustomObject doesn't support a
property without a name. In your script, add -AsHashTable to get an
object that supports this.
However, I think that a warning instead of an error may be better here
and have the resulting object not contain that property by default.
Solution for Powershell 6 and above
You can convert the string yourself to a data structure that supports empty properties (like a hashtable). This can be done using the ConvertFrom-Json method as shown below
$Token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PAT)"))
$Header = #{Authorization = 'Basic ' + $Token}
$BaseUri = "https://dev.azure.com/$($Organization)/"
$Project = "test"
$Uri = $BaseUri + "$Project/_apis/wit/workitemtypes?api-version=5.1"
$Result = Invoke-RestMethod -Uri $uri -Method GET -Headers $Header
# Check if type is string, then convert to a hashtable
if ($Result.GetType().Name -eq "String") {
$jsonRes = ConvertFrom-Json -AsHashtable -InputObject $Result
} else {
$jsonRes = $Result
}
$jsonRes
Solution for Powershell 5 and below
If you are using an older verison of powershell you will need to parse the string into a hashmap yourself or using a thrid party tool. (I am not aware of any built in cmdlet that does this at least).
One option could be to use the JavaScriptSerializer .NET class, which is done in the Poshstache module. The code is available on the link so you should be able to review it and possibly customize it to fit your needs

IBM Urbancode AddVersionStatus API call from Powershell How?

https://www.ibm.com/support/knowledgecenter/en/SS4GSP_6.2.7/com.ibm.udeploy.api.doc/topics/udclient_addversionstatus.html
How to make this PUT call using Powershell please?. I am using Powershell 5.
I came across this post while trying to do the same thing. The problem for me was in knowing what exactly the correct URL was (see Adam Parsons' answer):
$URL = "url-goes-here"
After a lot of searching (IBM's documentation was not worth much in this effort), I was able to identify the correct URL by way of watching traffic in Chrome developer tools (thanks to Darrell Schrag's blog post: https://drschrag.wordpress.com/2013/10/03/the-udeploy-rest-api).
For those searching for this, my PowerShell REST call sequence now looks like this (and executes successfully):
$tokenEncoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes( "PasswordIsAuthToken:{"token":"$authToken"}" ))
$headers = #{Authorization = "Basic "+$tokenEncoded}
# 1. Get component version ID
$uri = "$uDeployServer:8443/cli/version/getVersionId`?component=$componentName&version=$versionName"
$versionId=Invoke-RestMethod -Uri $uri -Method GET -Headers $headers
# 2. Add component version status
$uri = "$uDeployServer:8443/rest/deploy/version/$versionId/status/$versionStatus"
Invoke-RestMethod -Uri $uri -Method PUT -Headers $headers
Probably something like this...
$Hash = #{
Component="StringValue"
Version="StringValue"
Status="StringValue"
}
$Json = $Hash | ConvertTo-Json
$URL = "url-goes-here"
$Cred = Get-Credential
Invoke-RestMethod -Method "POST" -Uri $url -Credential $Cred -Body $Json

Powershell: Uploading file to Docparser API using Invoke-RestMethod

$header = #{'Authorization'='Basic <auth code value>'}
$ping = Invoke-RestMethod -Uri "https://api.docparser.com/v1/ping" -Headers $header
ping works fine...returns "pong". I then make a request for the Parser ID which is needed for uploading documents. I am able to retrieve this value successfully.
$parser = Invoke-RestMethod -Uri "https://api.docparser.com/v1/parsers" -Headers $header
$parserID = $parser.id
Now here is where I try to upload a pdf, which fails.
$fileToParse = "C:\test.pdf"
$body = #{'file'=$fileToParse}
$uploadDoc = Invoke-RestMethod -Uri "https://api.docparser.com/v1/document/upload/$parserID" -Method Post -Headers $header -ContentType 'multipart/form-data' -Body $body
API response keeps saying "Error: input empty"
This is the documentation from Docparser on how to upload pdfs:
Any thoughts on what I'm doing wrong here? Thanks in advance,
Eric
The problem is that your body currently just contains the path to your local file. Docparser expects however the content of the file as multipart/form-data.
I never worked with PowerShell, but I think something like this should work for you:
$body = #{
"file" = Get-Content($fileToParse) -Raw
}
I got the code from this answer: How to send multipart/form-data with PowerShell Invoke-RestMethod