$result = New-Object System.Collections.ArrayList
ForEach ($repoElement in $Repo.value)
{
$repoId = $repoElement.id
$BranchCreatorUrl = "https://dev.azure.com/xyz/_apis/git/repositories/$repoId/refs?api-version=6.1-preview.1"
$CreateorInfo = (Invoke-RestMethod -Uri $BranchCreatorUrl -Method Get -UseDefaultCredential -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)})
$url1= "https://dev.azure.com/xyz/_apis/policy/configurations?api-version=4.1"
$response = (Invoke-RestMethod -Uri $url1 -Method Get -UseDefaultCredential -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)})
$obj=[pscustomobject]#{
RepositoryName = $repoElement.name
RepositoryId = $repoId
BranchName = $CreateorInfo.value.name
PolicyName = $response.value.type.displayname
}
$result += $obj
}
Write-Output $result
The above code gives an output
I want to show all the branch name as string and not in the form of object ie this way {..,...,...,..}
If this is just about for-display formatting, i.e. what is shown in the implicitly table-formatted display output, you can call Format-Table explicitly and use a calculated column to apply custom formatting to the BranchName column:
# Sample result.
$result = [pscustomobject]#{
RepositoryName = 'name'
RepositoryId = 'id'
BranchName = 'branch1', 'branch2', 'branch3'
PolicyName = 'policy'
}
# Use explicit Format-Table formatting with custom formatting of the
# 'BranchName' column.
$result | Format-Table RepositoryName,
RepositoryId,
#{ n='BranchName'; e={ $_.BranchName -join ', ' } },
PolicyName
The above yields a tabular display whose BranchName column doesn't have the enclosing { ... }, which PowerShell uses to indicate that the column value is an array (perhaps confusingly, because it looks like a script block):
RepositoryName RepositoryId BranchName PolicyName
-------------- ------------ ---------- ----------
name id branch1, branch2, branch3 policy
Related
Trying to make a powershell script that tracks link clicks.
I have three goals:
change destination to name
Filter out destinations that are not a file type
Only display name of file, not the URL or extension
# Set the API key and endpoint
$apiKey = "API-KEY"
$endpoint = "https://api.rebrandly.com/v1/links?&limit=100"
# Make the API call and store the response
$response = Invoke-RestMethod -Method GET -Uri $endpoint -Headers #{ "apikey" = $apiKey } | Format-Table -Property clicks, destination
$response
clicks destination
------ -----------
11 https://github.com/file1.ps1
4 https://github.com/file2.ps1
2 https://github.com/main.zip
1 https://www.instagram.com
Desired Result
clicks destination
------ -----------
11 file1
4 file2
2 main
Format-Table doesn't perform collection filtering hence is not the right cmdlet for this use case. Also, for 2 property objects, it is not needed at all since default formatting output will be a table by default for objects with 4 properties or less.
Invoke-RestMethod -Method GET -Uri $endpoint -Headers #{ "apikey" = $apiKey } | ForEach-Object {
$lastSegment = ($_.destination -as [uri]).Segments | Select-Object -Last 1
if([System.IO.Path]::GetExtension($lastSegment)) {
[pscustomobject]#{
Clicks = $_.Clicks
Name = [System.IO.Path]::GetFileNameWithoutExtension($lastSegment)
}
}
}
This is a modification of Santiagos answer.
I couldn't quite get his to work.
I'm sure this can be optimized however.
$apiKey = "API-KEY"
$endpoint = "https://api.rebrandly.com/v1/links?&limit=100"
$r = Invoke-RestMethod -Method GET -Uri $endpoint -Headers #{ "apikey" = $apiKey }
ForEach($l in $r){$s = ($l.destination -as [uri]).Segments[-1]
if([System.IO.Path]::GetExtension($s)) {
[pscustomobject]#{
Clicks = $l.Clicks
Name = [System.IO.Path]::GetFileNameWithoutExtension($s)
}
}
}
I am trying to fetch asset data from the Fresh client with Powershell. I am able to get any asset by typing it's name but I want to save some of the variables it returns so I can use it further.
$naam = Read-Host "Voer product naam in"
# Set global variables
$APIKey = 'Myapikey'
$EncodedCredentials = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $APIKey,$null)))
$HTTPHeaders = #{ "X-ApiKey" = $APIKey}
$HTTPHeaders.Add('Authorization', ("Basic {0}" -f $EncodedCredentials))
$HTTPHeaders.Add('Content-Type', 'application/json')
$URL = 'https://helpdesk.company.nl/cmdb/items/list.json?field=name&q='+$naam
(Invoke-WebRequest -Method Get -Uri $URL -Headers $HTTPHeaders ).content
The following are some of the values that return after I run the above
{"config_items":[{"id":25000477949,"name":"SYS-MB1334","description":null,"ci_type_id":25000015988,"impact":1,"created_at":"2020-03-12T10:14:40+01:00","updated_at":"2020-04-24T16:42:42+02:00"
I would like to save the name and id variable for example
Unfortunately, the JSON you show is invalid.
Suppose the json returned from
$output = (Invoke-WebRequest -Method Get -Uri $URL -Headers $HTTPHeaders ).Content
looks like:
{"config_items":
[{"id":25000477949,"name":"SYS-MB1334","description":null,"ci_type_id":25000015988,"impact":1,"created_at":"2020-03-12T10:14:40+01:00","updated_at":"2020-04-24T16:42:42+02:00"},
{"id":12345678901,"name":"SYS-MB9876","description":null,"ci_type_id":12358745896,"impact":1,"created_at":"2020-03-12T10:14:40+01:00","updated_at":"2020-04-24T16:42:42+02:00"}]
}
Then you can collect the properties you need from the config_items using:
$result = ($output | ConvertFrom-Json).config_items |
Select-Object #{Name = 'Id'; Expression = {$_.id}},
#{Name = 'Name'; Expression = {$_.name}}
# output on screen
$result
# output to CSV file
$result | Export-Csv -Path 'X:\TheOutput.csv' -NoTypeInformation
Output on screen would look like
Id Name
-- ----
25000477949 SYS-MB1334
12345678901 SYS-MB9876
Hope that helps
I try to create a powershell script which can help us to create a release on our private gitlab server.
I found this tutorial
How to create releases in GitLab?
I'm not able to figure out how I can replace the curl command with the powershell invoke-webrequest command.
I already tried multiple concepts for this. In our case we have some code files and create the package in the same repository. The package is included in the gitignore file. (That's fine for us)
Now I tried to do this
$body = #{'form'='file=#/our awesome app.app'}
Invoke-RestMethod -Headers #{ 'PRIVATE-TOKEN'='<mytoeken>' } -Uri https://scm.domain.net/api/v4/projects/19/uploads -Body $Body
Result:
Invoke-RestMethod : {"error":"file is invalid"}
Does anyone have a script for creating a gitlab release page with download and changelog with powershell.
I also tried release it but I'm not able to configure it for gitlab.
https://www.npmjs.com/package/release-it#gitlab-releases
Below is a collection of some PowerShell snippets I have written or used for this purpose. Maybe this can help some people. Can you not create the $Body in the script also - it looks like it fails create the content from the file?
# Provides code snippets for Windows Powershell to use Gitlabs API to do various tasks
# for example [ Issue management, Release creation etc.]
# https://docs.gitlab.com/ee/api/
# Variables
# modify with you own content
$glUrl = "http://<your-gitlab-url>"
$p = "3" # Project ID
$tag = "1.3" # Modify this to create/delete release ...
$token = "<EDIT_ME>" # Your access token (http://<your-gitlab-url>/profile/personal_access_tokens)
$projectsUrl = "$glUrl/api/v4/projects" # i.e. http://<your-gitlab-url>/api/v4/projects
$pUrl = "$projectsUrl/$p" # i.e. http://<your-gitlab-url>/api/v4/projects/3
$releaseUrl = "$pUrl/releases" # i.e. http://<your-gitlab-url>/api/v4/projects/3/releases
$artifactsUrl = "$pUrl/jobs/artifacts/$tag/download?job=build-standard" # i.e. Build artifacts created for $tag and the relevant job ("build-standard"; can be modified)
# Project List
$r = Invoke-RestMethod -Headers #{ 'PRIVATE-TOKEN'="$token" } -Uri $projectsUrl
$r | Sort-Object -Property id | Format-Table -Property id, name
# Issues List
$r = Invoke-RestMethod -Headers #{ 'PRIVATE-TOKEN'="$token" } -Uri $pUrl/issues
$r | Sort-Object -Property id | Format-Table -Property id, state, title
# New Issue
Invoke-RestMethod -Method Post -Headers #{ 'PRIVATE-TOKEN'="$token" } -Uri "$pUrl/issues?title=Hello from PS&labels=test"
# Comment on the Issue
Invoke-RestMethod -Method Post -Headers #{ 'PRIVATE-TOKEN'="$token" } -Uri "$pUrl/issues/3/notes?body=Hello PowerShell"
function Register-NewIssue {
param(
[string]$title,
[string]$desc = '',
[string]$uri = '$projectUrl/issues'
)
$title = [System.Web.HttpUtility]::UrlEncode($title)
$desc = [System.Web.HttpUtility]::UrlEncode($desc)
$u = "$uri`?title=$title&description=$desc"
$r = Invoke-RestMethod -Method Post -Headers #{ 'PRIVATE-TOKEN'= "$token" } -Uri $u
$r | Format-List -Property iid, state, title, description
}
# Get list of Releases
Invoke-RestMethod -Method Get -Headers #{ 'PRIVATE-TOKEN'="$token" } -Uri $releaseUrl
# Create a Release
$JSON = #"
{
"name": "New release",
"tag_name": $tag,
"ref": "master",
"description": "FromPS",
"assets":{
"links":[
{
"name":"Executables",
"url":"$artifactsUrl"
}
]
}
}
"#
Invoke-RestMethod -Method Post -Headers #{ 'PRIVATE-TOKEN'="$token"; 'Content-Type'='application/json' } -Body $JSON -Uri "$releaseUrl"
Read-Host -Prompt "Press Enter to continue"
# Adds only a link to this Release manually
$JSONLINK = #'
{"name":"awesome-exec",
"url":"$artifactsUrl"
}
'#
Invoke-RestMethod -Method Post -Headers #{ 'PRIVATE-TOKEN'= "$token"; 'Content-Type'='application/json' } -Body $JSONLINK -Uri "$releaseUrl/$tag/assets/links"
# Delete a Release
Invoke-RestMethod -Method Delete -Headers #{ 'PRIVATE-TOKEN'= "$token" } -Uri "$releaseUrl/$tag"
I am trying to change a value - specifically a variable - of one of my TFS 2017 builds. To my understanding, Patch is not supported at all. I can successfully queue a build with the Post method and I am trying to use the same command change a value as well.
When I run the Get method, I have:
*A bunch of text*
"variables": {
"system.debug": {
"value": "false",
"allowOverride": true
},
"BuildVersion": {
"value": "ValueIWantToChange"
}
},
*A bunch of text*
I need to change the Build Version and everything else will stay the same. My body in Postman looks like:
{
"Variables":
{
"BuildVersion":
{
"value": NewValue
}
}
}
When I run this in Postman, I get this error:
"Value cannot be null.\r\nParameter name: definition.Repository"
Could anyone tell me where I am going wrong or if this is possible using another method?
Seems you want to update the build definition base on you description.
To update the build definition with the REST API you need to use PUT method, please see Definitions - Update Definition for details.
Get the build definition first:
GET http://server:8080/tfs/DefaultCollection/ScrumProject/_apis/build/definitions/6?api-version=3.2
Copy all the json response from the first step as the request body,
then change the value of the specific variable which you want to be
modified.
PUT http://SERVER:8080/tfs/DefaultCollection/ScrumProject/_apis/build/definitions/6?api-version=3.2
Content-Type: application/json
Note that you need to provide the latest revision in request body:
UPDATE:
You can also use PowerShell by calling the REST API to update the specific variable value, just try below sample: (the variable name is lctest in below sample, you just need to replace it with your own variable name.)
Param(
[string]$collectionurl = "http://server:8080/tfs/DefaultCollection",
[string]$project = "ProjectName",
[string]$definitionid = "6",
[string]$user = "username",
[string]$token = "password"
)
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
#Get build definition
$defurl = "$collectionurl/$project/_apis/build/definitions/$($definitionid)?api-version=3.2"
$definition = Invoke-RestMethod -Uri $defurl -Method Get -UseDefaultCredential -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
#Set new value for the specific variable
$definition.variables.lctest.value = "1.0.0.4"
$json = #($definition) | ConvertTo-Json -Depth 99
#Update the definition
$updatedef = Invoke-RestMethod -Uri $defurl -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
write-host $definition.variables.lctest.value
I figured out my problem awhile back and forgot to update. My initial task was to get the API for octopus so this is the long version. If youre only interested in the REST commands, refer to the last section of code. Just wanted to add the rest in for extra context.
#Create a folder
if(test-Path C:\Test){}
else{
new-item -path "C:\" -name "Test" -ItemType "directory"}
$encodedPAT = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$TFSAPIKeyForAutomatedBuild"))
$GetURI = "$MyURI"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Basic $encodedPAT")
[string]$Global:ChangeVersion = [version]$OctopusParameters["Octopus.Action[Deploy Package].Package.NuGetPackageVersion"]
write-host $ChangeVersion
$GetBuildresponse = Invoke-RestMethod -Method Get -header $headers -ContentType "application/json" -Uri $GetUri
write-host $GetBuildResponse
$y = convertTo-json $GetBuildresponse -depth 99 | Out-file -FilePath "C:\test\FromPostmanCopy.json"
$z = (get-content "C:\test\FromPostmanCopy.json") | select-string -pattern '(?<=value": "2.)(.*)(?=")' | % { $_.Matches} | % { $_.value }
Write-Host $z
$Content = (Get-Content "C:\Test\FromPostmanCopy.json")
$content -replace "2.$z", $changeVersion | out-file "C:\Test\FromPostmanCopy.json"
$Content = (Get-Content "C:\Test\FromPostmanCopy.json")
$Buildresponse = Invoke-RestMethod -URI $GetURI -Method Put -header $headers -Body $content -ContentType application/json
I'm attempting to use the Test -> Runs -> Query endpoint to return a list of test runs for a particular release, as detailed here
Unfortunately whatever I put in as a query parameter (with the exception of $top which does appear to filter), I appear to get every test run returned against the project.
For example, I know there are 14 test runs against a particular release.
I can get my release id with the following query...
https://smartassessor.vsrm.visualstudio.com/Smart End Point Assessment/_apis/release/releases?searchText=Release-103
If I then try to use that id in the test run query like this...
https://smartassessor.visualstudio.com/Smart End Point Assessment/_apis/test/runs?releaseIds=1678&api-version=5.0-preview.2
I get 529 results, which looks like most of the test runs agains the project.
Are the filters working against this endpoint? If so, how should I tweak my request to utilize the releaseIds parameter.
Thanks
I can reproduce this issue. Seems the APIs are not available for now.
There is an issue submitted here for tracking this. You can also track the updates on it.
As a workaround, you can use below PowerShell script to filter the test runs by Release ID: (Alternately you can export the result to a *.CSV file)
Param(
[string]$collectionurl = "https://{account}.visualstudio.com",
[string]$project = "ProjectName",
[string]$releaseid = "1",
[string]$user = "username",
[string]$token = "password"
)
#Set the path and name for the output csv file
$path = "D:\temp"
$filename = "ReleaseTestRun" + "-" + $releaseid
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
$baseUrl = "$collectionurl/$project/_apis/test/runs"
$response = Invoke-RestMethod -Uri $baseUrl -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$testruns = $response.value
Write-Host $results
$Releaseruns = #()
foreach ($testrun in $testruns)
{
$testrunID = $testrun.id
$runbaseUrl = "$collectionurl/$project/_apis/test/runs/$testrunID"
$runresponse = Invoke-RestMethod -Uri $runbaseUrl -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} | Where {$_.release.id -eq $releaseid} #| Filter the test run by Release ID
$customObject = new-object PSObject -property #{
"id" = $runresponse.id
"name" = $runresponse.name
"url" = $runresponse.url
"isAutomated" = $runresponse.isAutomated
"state" = $runresponse.state
"totalTests" = $runresponse.totalTests
"incompleteTests" = $runresponse.incompleteTests
"notApplicableTests" = $runresponse.notApplicableTests
"passedTests" = $runresponse.passedTests
"unanalyzedTests" = $runresponse.unanalyzedTests
"revision" = $runresponse.revision
"webAccessUrl" = $runresponse.webAccessUrl
}
$Releaseruns += $customObject
}
$Releaseruns | Select `
id,
name,
url,
isAutomated,
state,
totalTests,
incompleteTests,
notApplicableTests,
passedTests,
unanalyzedTests,
revision,
webAccessUrl | where {$_.id -ne $Null} #|export-csv -Path $path\$filename.csv -NoTypeInformation # Filter non-empty values and export to csv file.