Unpacking Software Livestream

Join our monthly Unpacking Software livestream to hear about the latest news, chat and opinion on packaging, software deployment and lifecycle management!

Learn More

Chocolatey Product Spotlight

Join the Chocolatey Team on our regular monthly stream where we put a spotlight on the most recent Chocolatey product releases. You'll have a chance to have your questions answered in a live Ask Me Anything format.

Learn More

Chocolatey Coding Livestream

Join us for the Chocolatey Coding Livestream, where members of our team dive into the heart of open source development by coding live on various Chocolatey projects. Tune in to witness real-time coding, ask questions, and gain insights into the world of package management. Don't miss this opportunity to engage with our team and contribute to the future of Chocolatey!

Learn More

Calling All Chocolatiers! Whipping Up Windows Automation with Chocolatey Central Management

Webinar from
Wednesday, 17 January 2024

We are delighted to announce the release of Chocolatey Central Management v0.12.0, featuring seamless Deployment Plan creation, time-saving duplications, insightful Group Details, an upgraded Dashboard, bug fixes, user interface polishing, and refined documentation. As an added bonus we'll have members of our Solutions Engineering team on-hand to dive into some interesting ways you can leverage the new features available!

Watch On-Demand
Chocolatey Community Coffee Break

Join the Chocolatey Team as we discuss all things Community, what we do, how you can get involved and answer your Chocolatey questions.

Watch The Replays
Chocolatey and Intune Overview

Webinar Replay from
Wednesday, 30 March 2022

At Chocolatey Software we strive for simple, and teaching others. Let us teach you just how simple it could be to keep your 3rd party applications updated across your devices, all with Intune!

Watch On-Demand
Chocolatey For Business. In Azure. In One Click.

Livestream from
Thursday, 9 June 2022

Join James and Josh to show you how you can get the Chocolatey For Business recommended infrastructure and workflow, created, in Azure, in around 20 minutes.

Watch On-Demand
The Future of Chocolatey CLI

Livestream from
Thursday, 04 August 2022

Join Paul and Gary to hear more about the plans for the Chocolatey CLI in the not so distant future. We'll talk about some cool new features, long term asks from Customers and Community and how you can get involved!

Watch On-Demand
Hacktoberfest Tuesdays 2022

Livestreams from
October 2022

For Hacktoberfest, Chocolatey ran a livestream every Tuesday! Re-watch Cory, James, Gary, and Rain as they share knowledge on how to contribute to open-source projects such as Chocolatey CLI.

Watch On-Demand

Downloads:

1,588

Downloads of v 1.0.0:

1,588

Last Update:

12 Mar 2016

Package Maintainer(s):

Software Author(s):

  • Matthew Manela

Tags:

powershell vso vsts tfs git build workitem

PsVsts

  • 1
  • 2
  • 3

1.0.0 | Updated: 12 Mar 2016

Downloads:

1,588

Downloads of v 1.0.0:

1,588

Maintainer(s):

Software Author(s):

  • Matthew Manela

PsVsts 1.0.0

  • 1
  • 2
  • 3

All Checks are Passing

3 Passing Tests


Validation Testing Passed


Verification Testing Passed

Details

Scan Testing Successful:

No detections found in any package files

Details
Learn More

Deployment Method: Individual Install, Upgrade, & Uninstall

To install PsVsts, run the following command from the command line or from PowerShell:

>

To upgrade PsVsts, run the following command from the command line or from PowerShell:

>

To uninstall PsVsts, run the following command from the command line or from PowerShell:

>

Deployment Method:

NOTE

This applies to both open source and commercial editions of Chocolatey.

1. Enter Your Internal Repository Url

(this should look similar to https://community.chocolatey.org/api/v2/)


2. Setup Your Environment

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

2. Get the package into your environment

  • Open Source or Commercial:
    • Proxy Repository - Create a proxy nuget repository on Nexus, Artifactory Pro, or a proxy Chocolatey repository on ProGet. Point your upstream to https://community.chocolatey.org/api/v2/. Packages cache on first access automatically. Make sure your choco clients are using your proxy repository as a source and NOT the default community repository. See source command for more information.
    • You can also just download the package and push it to a repository Download

3. Copy Your Script

choco upgrade psvsts -y --source="'INTERNAL REPO URL'" [other options]

See options you can pass to upgrade.

See best practices for scripting.

Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.

If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:


choco upgrade psvsts -y --source="'INTERNAL REPO URL'" 
$exitCode = $LASTEXITCODE

Write-Verbose "Exit code was $exitCode"
$validExitCodes = @(0, 1605, 1614, 1641, 3010)
if ($validExitCodes -contains $exitCode) {
  Exit 0
}

Exit $exitCode

- name: Install psvsts
  win_chocolatey:
    name: psvsts
    version: '1.0.0'
    source: INTERNAL REPO URL
    state: present

See docs at https://docs.ansible.com/ansible/latest/modules/win_chocolatey_module.html.


chocolatey_package 'psvsts' do
  action    :install
  source   'INTERNAL REPO URL'
  version  '1.0.0'
end

See docs at https://docs.chef.io/resource_chocolatey_package.html.


cChocoPackageInstaller psvsts
{
    Name     = "psvsts"
    Version  = "1.0.0"
    Source   = "INTERNAL REPO URL"
}

Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.


package { 'psvsts':
  ensure   => '1.0.0',
  provider => 'chocolatey',
  source   => 'INTERNAL REPO URL',
}

Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.


4. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

Package Approved

This package was approved by moderator ferventcoder on 18 Aug 2020.

Description

PsVsts provides a suite of PowerShell functions that help automate interaction with VisualStudio Online. Some of the functions include Push-ToVsts (quickly take a local git repo and host it in a VSTS project), Submit-PullRequest (submits a pull request), Get-Builds and Get-WorkItems.

This module requires PowersShell version 3 or greater. No explicit dependency is taken to not force a user to upgrade unknowingly.


tools\Build.Format.ps1xml
 
tools\chocolateyinstall.ps1
$tools = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
. (Join-Path $tools Setup.ps1)
try { 
    Install-PsVsts "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
} catch {
    Write-ChocolateyFailure "PsVsts" "$($_.Exception.Message)"
    throw 
}
tools\cmdlets\Get-Builds.ps1

function Get-Builds {
<#
.SYNOPSIS
Gets builds

.DESCRIPTION
Get-Builds will query your VSTS project to get the recent builds

.PARAMETER BuildDefinition
The name of the build definition.  Can be inherited from a config file.

.PARAMETER Take
The number of builds to show. Defaults to the 5.

.PARAMETER Account
The acount name to use. Can be inherited from a config file.
If your VSTS url is hello.visualstudio.com then this value should be hello.

.PARAMETER Project
The project name to use. Can be inherited from a config file.

.Example
Get-Builds -BuildDefinition myBuildDef -Account myAccount -Project myProject

.LINK
about_PsVsts

#>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false)]
        [string]$BuildDefinition,
        [Parameter(Mandatory = $false)]
        [int]$Take = 5,
        [Parameter(Mandatory = $false)]
        [string]$Account,
        [Parameter(Mandatory = $false)]
        [string]$Project,
        [Parameter(Mandatory = $false)]
        [ValidateSet('build','xaml')]
        [string]$Type = "build"
    )

    refreshCachedConfig

    $definitionName = getFromValueOrConfig $BuildDefinition $script:config_buildDefinitionKey
    $accountName    = getFromValueOrConfig $Account $script:config_accountKey
    $projectName    = getFromValueOrConfig $Project $script:config_projectKey

    $buildResults = getBuilds $accountName $projectName $definitionName $Type $Take

    $buildResults = formatBuilds $buildResults

    return $buildResults

}
tools\cmdlets\Get-MyWorkItems.ps1

function Get-MyWorkItems {
<#
.SYNOPSIS
Queries the work items connected to you

.DESCRIPTION
Get-MyWorkItems queries for the open work items that are created by or assigned
to you. By default it will include just items updated in the last 30 days and 
filter out any work items that are in a "finished" state according to the
agile, scrum or cmmi templates. 

Items are considered "finished" if State is any of the following values
  Done
  Removed
  Resolved
  Closed
  Cut
  Completed

.PARAMETER OrderBy
The field to order by. By default this is System.ChangedDate

.PARAMETER Take
The number of work items to show. Defaults to the 200. Max is 200.

.PARAMETER AssignedToMe
Show work items that are assigned to the current user. 
By default Get-MyWorkItems shows both work items created by you and assigned to you. 
However, if you specify -AssignedToMe and don't specify -CreatedByMe then you
will only see items assigned to you

.PARAMETER CreatedByMe
Show work items that are created by the current user. 
By default Get-MyWorkItems shows both work items created by you and assigned to you. 
However, if you specify -CreatedByMe and don't specify -AssignedToMe then you
will only see items created by you

.PARAMETER IncludeAllStates
By default Get-MyWorkItems trys to filter out "finished" items. This property
prevents this behavior.

.PARAMETER IncludedStates
By default Get-MyWorkItems trys to filter out "finished" items. This property
prevents this behavior and lets you specify just the states you want.

.PARAMETER Account
The acount name to use. Can be inherited from a config file.
If your VSTS url is hello.visualstudio.com then this value should be hello.

.PARAMETER Project
The project name to use. Can be inherited from a config file.

.Example
Get-MyWorkItems

Gets work items assigned to current user

.Example
Get-WorkItems -Take 10 -OrderBy System.AssignedTo

Gets the first 10 work items assigned to or created by the current user ordered by assignedto name


.LINK
about_PsVsts

#>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false)]
        [switch]$AssignedToMe,
        [Parameter(Mandatory = $false)]
        [switch]$CreatedByMe,
        [Parameter(Mandatory = $false)]
        [string]$OrderBy,
        [Parameter(Mandatory = $false)]
        [int]$Take = 200,
        [Parameter(Mandatory = $false)]
        [switch]$IncludeAllStates,
        [Parameter(Mandatory = $false)]
        [string[]]$IncludedStates,
        [Parameter(Mandatory = $false)]
        [string]$Account,
        [Parameter(Mandatory = $false)]
        [string]$Project
    )

    refreshCachedConfig

    $accountName    = getFromValueOrConfig $Account $script:config_accountKey
    $projectName    = getFromValueOrConfig $Project $script:config_projectKey

    $fromDate = (Get-Date).AddDays(-30).ToShortDateString()


    $identityFilterFields = @()
    # If the user didn't set either filter then assume both are true
    if(-not $CreatedByMe -and -not $AssignedToMe) {
        $CreatedByMe = $true
        $AssignedToMe = $true
    }

    if($CreatedByMe) {
        $identityFilterFields += [System.String]::Format($script:identityFilterQueryPart, "System.CreatedBy")
    }
    if($AssignedToMe) {
        $identityFilterFields += [System.String]::Format($script:identityFilterQueryPart, "System.AssignedTo")
    }

    $identityFilterString = $identityFilterFields -join " OR "

    if(-not $OrderBy) {
        $OrderBy = "System.ChangedDate"
    }

    if($IncludeAllStates) {
        $excludedStates = @()
        $stateFilterPart = ""
    }
    elseif($IncludedStates) {
        $excludedStatesString = ($IncludedStates | ForEach-Object { "`"$_`""}) -join ","
        $stateFilterPart = [System.String]::Format($script:stateIncludeFilterQueryPart, $excludedStatesString)    
    }
    else {
        $excludedStates = @("Done", "Removed", "Closed", "Resolved", "Completed", "Cut")
        $excludedStatesString = ($excludedStates | ForEach-Object { "`"$_`""}) -join ","
        $stateFilterPart = [System.String]::Format($script:stateExcludeFilterQueryPart, $excludedStatesString)         
    }

    $query = [System.String]::Format($script:getMyWorkItemsQuery, $fromDate, $stateFilterPart, $identityFilterString, $OrderBy)

    $workItems = getWorkItemsFromQuery $accountName $projectName $query $Take

    # Transform some properties to make them easily formatted
    $workItems = formatWorkItems $workItems

    return $workItems
}
tools\cmdlets\Get-VstsConfig.ps1

function Get-VstsConfig
{
<#
.SYNOPSIS
Get the values stored in the config files

.DESCRIPTION
Get-VstsConfig gets the values in the active config files. You can choose to see values 
defined in the local config file, global config file, or both.

By default a combined result is shown which shows all config values that are 
currently applied. This is computed by combine the local and global config.


.PARAMETER Local
Flag indicates you want to see the local config values

.PARAMETER Global
Flag indicates you want to see the global config values

.Example
Get-VstsConfig 

Gets all the config values by take the global config and overriding matching properties 
with local config values

.Example
Get-VstsConfig -Global

Gets all the global config values.

.LINK
about_PsVsts

#>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [switch]
        $Local,
        [Parameter(Mandatory = $false)]
        [switch]
        $Global   
    )

    # Gets the global config from the known location
    $globalConfig = readConfigFile $script:globalConfigPath

    # Get the local config path
    $localConfigPath = getLocalConfigPath
    $localConfig = readConfigFile $localConfigPath

    if($Local -and -not $Global) {
        return $localConfig
    }
    elseif($Global -and -not $Local) {
        return $globalConfig
    }
    else {
        return mergeHashTables $globalConfig $localConfig
    }
}
tools\cmdlets\Get-WorkItems.ps1

function Get-WorkItems {
<#
.SYNOPSIS
Gets workitems given a query

.DESCRIPTION
Get-WorkItems by running a query and returning the results

.PARAMETER Query
The query to run

.PARAMETER Take
The number of work items to show. Defaults to the 200. Max is 200.

.PARAMETER Account
The acount name to use. Can be inherited from a config file.
If your VSTS url is hello.visualstudio.com then this value should be hello.

.PARAMETER Project
The project name to use. Can be inherited from a config file.

.Example
Get-WorkItems -Query  "SELECT [System.Id], [System.Title] FROM WorkItems WHERE [System.TeamProject] = @project AND [System.AssignedTo] = 'Joe Smith'"

Gets work items assigned to current user

.Example
Get-WorkItems -Query  "SELECT [System.Id], [System.Title] FROM WorkItems WHERE [System.TeamProject] = @project AND [System.AssignedTo] = 'Joe Smith'" -Take 10


.LINK
about_PsVsts

#>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Query,
        [Parameter(Mandatory = $false)]
        [int]$Take = 200,
        [Parameter(Mandatory = $false)]
        [string]$Account,
        [Parameter(Mandatory = $false)]
        [string]$Project
    )

    refreshCachedConfig

    $accountName    = getFromValueOrConfig $Account $script:config_accountKey
    $projectName    = getFromValueOrConfig $Project $script:config_projectKey

   
    $workItems = getWorkItemsFromQuery $accountName $projectName $Query $Take

    # Transform some properties to make them easily formatted
    $workItems = formatWorkItems $workItems

    return $workItems
}
tools\cmdlets\Open-WorkItems.ps1

function Open-WorkItems {
<#
.SYNOPSIS
Opens the given work item ids in your default web browser

.DESCRIPTION
Open-WorkItems will open the web viewer for the given work item ids


.PARAMETER WorkItemIds
One or more work item ids to open in the browser

.PARAMETER WorkItems
One or more work item objects (e.g. returned by Get-MyWorkItems) to open in the browser

.PARAMETER Account
The acount name to use. Can be inherited from a config file.
If your VSTS url is hello.visualstudio.com then this value should be hello.


.Example
Open-WorkitemIds 2

Opens work item 2 in a browser. The account is inherited from config.

.Example
Get-WorkItems -WorkItemIds 1,2,3 -Account MyAccount

Open work items 1, 2 and 3 in the MyAccount project.

.Example 
Get-MyWorkItems -Take 2 | Open-WorkItems

Open the two most recently changes work items created by or assigned to you

.LINK
about_PsVsts

#>
    [CmdletBinding(DefaultParameterSetName="WorkItemId")]
    param(
        [Parameter(Position=0, ValueFromPipeline=$True, Mandatory = $true, ParameterSetName="WorkItemId")]
        [int[]]$WorkItemIds,
        [Parameter(Position=0, ValueFromPipeline=$True, Mandatory = $true, ParameterSetName="WorkItem")]
        [object[]]$WorkItems,
        [Parameter(Mandatory = $false)]
        [string]$Account
    )

    Begin {
        refreshCachedConfig
    }

    Process {
        
        if($PsCmdlet.ParameterSetName -eq "WorkItem"){
            $WorkItemIds = $WorkItems.Id
        }

        $accountName  = getFromValueOrConfig $Account $script:config_accountKey

        $WorkItemIds | ForEach-Object { openWorkItemInBrowser $accountName $_}
    }
}
tools\cmdlets\Push-ToVsts.ps1

function Push-ToVsts {
<#
.SYNOPSIS
Clones the current git repo to a VSTS project.

.DESCRIPTION
Calling Push-ToVsts will clone your git repo to a VSTS project. If you don't specify a project it will try to use the default one.
If no default project is configure it will error. You must run this command from inside of your git repo folder.

.PARAMETER Repository
The repository name to use. Can be inherited from a config file.

.PARAMETER Account
The acount name to use. Can be inherited from a config file.
If your VSTS url is hello.visualstudio.com then this value should be hello.

.PARAMETER Project
The project name to use. Can be inherited from a config file.

.Example
Push-ToVsts 

This will look for a git repo in the current directory and try to find an already configured project/account. 
It will then create a repo in that project and push to it. 

.Example
Push-ToVsts -Project MyProject -Account MyAccount

Finds a git repo in current directory and adds it to the given account/project

.LINK
about_PsVsts

#>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false)]
        [string]$Repository,
        [Parameter(Mandatory = $false)]
        [string]$Account,
        [Parameter(Mandatory = $false)]
        [string]$Project
    )

    if( -not (testForGit)) {
        throw "Could not find the git exe in the path"
    }

   refreshCachedConfig
   
   $accountName = getFromValueOrConfig $Account $script:config_accountKey
   $projectName = getFromValueOrConfig $Project $script:config_projectKey
   $repoName    = getFromValueOrConfig $Repository $script:config_repoKey

   # Create this repo online
   $repoResult = createRepo $accountName $projectName $repoName
   $remoteUrl = $repoResult.remoteUrl

   # Figure out if origin is already defined
   # if so we try to use the PsVsts remote name
   $currentRemotes = git remote
   $remoteName = "origin"
   if($currentRemotes -and $currentRemotes.Contains("origin")) {
    Write-Host "origin remote already exists so create PsVsts remote"
    $remoteName = "PsVsts"
   }

    Write-Host "Add remote $remoteName $remoteUrl"
    git remote add $remoteName $remoteUrl

    Write-Host "Pushing repository"
    git push -u $remoteName --all 
}




function testForGit() {

    $hasGit = $false
    
    try {
        git --version | Out-Null
        $hasGit = $true
    } catch {
        $hasGit = $false
        $ErrorCount -= 1
    }

    return $hasGit
}
tools\cmdlets\Set-VstsConfig.ps1

function Set-VstsConfig
{
<#
.SYNOPSIS
Sets values in a (local or global) config file.

.DESCRIPTION
Set-VstsConfig lets you set the value for certain properties of 
cmdlets. By setting these in the config file you no longer need to pass them
to the functions. You can set a value in either a local or global config. 
This lets you put local configs file in your projects and store more global 
values like account centrally.

.PARAMETER Name
The name of the property you want to set

.PARAMETER Value
The value to set the property.

.PARAMETER Local
Flag indicates you want to set value in a local config file.
The file will be created in the current directory if it doesn't exist.
This is the default.

.PARAMETER Global
Flag indicates you want to set value in the global config file.

.Example
Set-VstsConfig -Name Project -Value MyProject

Sets the property Project to the value MyProject in the global config

.Example
Set-VstsConfig -Name Project -Value MyProject -Local

Sets the property Project to the value MyProject in a local config

.LINK
about_PsVsts

#>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$Name,
        [Parameter(Mandatory = $true)]
        [string]$Value,
        [Parameter(Mandatory = $false)]
        [switch]
        $Local = $true,
        [Parameter(Mandatory = $false)]
        [switch]
        $Global

    )

    if((-not $Local) -and (-not $Global)) {
        throw "You must specify Local or Global"
    }


    $configObject = @{}
    $configPath = ""

    if($Local -and -not $Global) {
        $configPath = getLocalConfigPath
        if(-not $configPath) {
            $configPath = Join-Path (Get-Location) $configFileName
        }

        $configObject = Get-VstsConfig -Local
    }
    else {
        $configPath = $script:globalConfigPath
        $configObject = Get-VstsConfig -Global
    }

    if(-not (Test-Path $configPath)) {
        Write-Host "Creating config file at $configPath"
    }

    $configObject[$Name] = $Value

    $configJson = ConvertTo-Json $configObject
    Set-Content -Path $configPath -Value $configJson


    traceMessage "Wrote to config file at $configPath"

}
tools\cmdlets\Submit-PullRequest.ps1

function Submit-PullRequest {
<#
.SYNOPSIS
Submits a pull request to Visual Studio Online

.DESCRIPTION
Calling Submit-PullRequest will create a pull request between the configured branches in your Visual Studio Online project.
If succesfull will launch the pull request in a browser.


.PARAMETER Title
The title of the pull request.

.PARAMETER Description
The description of the pull request.

.PARAMETER SourceBranch
The branch you want to merge from. Can be inherited from a config file.

.PARAMETER TargetBranch
The branch you want to merge to. Can be inherited from a config file.

.PARAMETER Reviewers
The list of people to add to the PR. This should be their display name or email address.

.PARAMETER Repository
The repository name to use. Can be inherited from a config file.

.PARAMETER Account
The acount name to use. Can be inherited from a config file.
If your VSTS url is hello.visualstudio.com then this value should be hello.

.PARAMETER Project
The project name to use. Can be inherited from a config file.

.Example
Submit-PullRequest -Title "This is good"  -Reviewers "Matthew Manela", "[email protected]"  -Repository someRepo -SourceBranch someBranch -TargetBranch master -Account myAccount -Project myProject

.LINK
about_PsVsts

#>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Title,
        [Parameter(Mandatory = $false)]
        [string]$Description,
        [Parameter(Mandatory = $false)]
        [string]$SourceBranch,
        [Parameter(Mandatory = $false)]
        [string]$TargetBranch,
        [Parameter(Mandatory = $false)]
        [string[]]$Reviewers,
        [Parameter(Mandatory = $false)]
        [string]$Repository,
        [Parameter(Mandatory = $false)]
        [string]$Account,
        [Parameter(Mandatory = $false)]
        [string]$Project
    )

    refreshCachedConfig

    $accountName         = getFromValueOrConfig $Account $script:config_accountKey
    $projectName         = getFromValueOrConfig $Project $script:config_projectKey
    $repoName            = getFromValueOrConfig $Repository $script:config_repoKey
    $sourceBranchName    = getFromValueOrConfig $SourceBranch $script:config_sourceBranch
    $targetBranchName    = getFromValueOrConfig $TargetBranch $script:config_targetBranch

    $reviewerIds = @()
    if($Reviewers) {
        $reviewerIds = $Reviewers | ForEach-Object { getIdentityId $accountName $_ } | Where-Object { $_ -ne $null }
    }

    $refPrefix = "refs/heads/"
    if(-not $sourceBranchName.ToLower().StartsWith("$refPrefix")) {
        $sourceBranchName = $refPrefix + $sourceBranchName
    }   

    if(-not $targetBranchName.ToLower().StartsWith("$refPrefix")) {
        $targetBranchName = $refPrefix + $targetBranchName
    }

    $payload = @{
        "sourceRefName" = $sourceBranchName
        "targetRefName" = $targetBranchName
        "title"= $Title
        "description" = $Description
        "reviewers" = @($reviewerIds | ForEach-Object { @{ "id" = $_ } })
    }

    $repoId = getRepoId $accountName $projectName $repoName

    
    $url = [System.String]::Format($script:pullRequestUrl, $accountName, $repoId)
    $prResults = postUrl $url $payload

     if($prResults) {
        $webUrl = [System.String]::Format($script:openPullRequestUrl, $accountName, $projectName, $repoName, $prResults.pullRequestId)
        Write-Host "Pull request created at $webUrl"
        Start-Process $webUrl
    }

}
tools\en-US\about_PsVso.help.txt
TOPIC
	PsVsts

SYNOPSIS
  PsVsts provides a suite of PowerShell functions that help automate interaction 
  with  VisualStudio Online.

DESCRIPTION
	PsVsts helps make it so you never need to leave your command prompt.
tools\functions\config.ps1
# Functions and variables used for the config related operations

$script:configFileName = "PsVsts.json"
$script:globalConfigPath = Join-Path ([System.Environment]::ExpandEnvironmentVariables("%userprofile%")) $configFileName


$script:cached_config = @{}
$script:config_projectKey           = "project"
$script:config_accountKey           = "account"
$script:config_repoKey              = "repository"
$script:config_buildDefinitionKey   = "builddefinition"
$script:config_sourceBranch         = "sourceBranch"
$script:config_targetBranch         = "targetBranch"

function refreshCachedConfig() {
    $script:cached_config = Get-VstsConfig
}

# Checks a given value and if it is not empty return it 
# otherwise look up a value from the cached config
function getFromValueOrConfig($value, $keyName, [hashtable] $config) {


    # If passed in value is empty then check the config
    if(-not $value) {
        $value = $script:cached_config[$keyName]
    }

    # If we can't find a value throw
    if(-not $value) {
        throw "The $keyName name must be specified as an argument or in the config"
    }

    return $value
}


function mergeHashTables ([hashtable] $first, [hashtable] $second) {

    $result = @{}

    # Apply the first hash table
    $first.GetEnumerator() | ForEach-Object { $result[$_.Name] = $_.Value }

    # Apply the second hash table possibly overwriting values
    $second.GetEnumerator() | ForEach-Object { $result[$_.Name] = $_.Value }

    # union both sets
    return $result;
}


# Get the local config which is found by probing form the current directory up
function getLocalConfigPath {

    $directory = Get-Location
    $localConfigPath = Join-Path $directory $configFileName
    while ($localConfigPath -and -not (Test-Path $localConfigPath)) {
       
       $directory = Split-Path -Parent $directory

        if($directory) {
            $localConfigPath = Join-Path $directory $configFileName 
        }
        else {
            $localConfigPath = $null
        }
    }

    return $localConfigPath
}

function readConfigFile($filePath) {

    $configHash = @{}
    if($filePath -and (Test-Path $filePath)) {
        $content = Get-Content $filePath -Raw

        if($content) {
            $jsonObject = ConvertFrom-Json $content
            $jsonObject.psobject.Properties | ForEach-Object { $configHash[$_.Name] = $_.Value }
        }
    }

    return $configHash
}
tools\functions\format.ps1

# Format work items to make them easily display
# But we still persist the raw field data in the Fields property
function formatWorkItems($workItems) {
	$workItems = $workItems.fields | 
	    ForEach-Object { 
	            [PSCustomObject]@{
	                Id=$_.'System.Id'
	                Title=$_.'System.Title'
	                WorkItemType=$_.'System.WorkItemType'
	                AssignedTo=$_.'System.AssignedTo'
	                CreatedBy=$_.'System.CreatedBy'
	                CreatedDate=$_.'System.CreatedDate'
	                ChangedDate=$_.'System.ChangedDate'
	                State=$_.'System.State'
	                Fields=$_
	            } 
	        }


    # Add type name
    $workItems | ForEach-Object { $_.PSObject.TypeNames.Insert(0,'WorkItem') }
	
	return $workItems
}

function formatBuilds($builds) {
    
    # Add type name
    $builds | ForEach-Object { $_.PSObject.TypeNames.Insert(0,'Build') }
	
	return $builds
}
tools\functions\trace.ps1
function traceMessage($message) {
    if($PsVsts.EnableLogging) {
        Write-Host $message
    }
}
tools\functions\vsts.ps1
# Functions and variables used for communication with VSTS


$script:cached_HttpClient = $null
$script:cached_accountProjectMap = @{}

$script:projectsUrl =         "https://{0}.visualstudio.com/defaultcollection/_apis/projects?api-version=1.0"
$script:gitReposUrl =         "https://{0}.visualstudio.com/defaultcollection/{1}/_apis/git/repositories?api-version=1.0"
$script:identityUrl =         "https://{0}.visualstudio.com/defaultcollection/_api/_identity/CheckName?name={1}"
$script:pullRequestUrl =      "https://{0}.visualstudio.com/defaultcollection/_apis/git/repositories/{1}/pullRequests?api-version=1.0-preview.1"
$script:openPullRequestUrl =  "https://{0}.visualstudio.com/defaultcollection/{1}/_git/{2}/pullrequest/{3}"
$script:buildDefinitionsUrl = "https://{0}.visualstudio.com/defaultcollection/{1}/_apis/build/definitions?name={2}&type={3}&`$top=1&api-version=2.0"
$script:buildsUrl =           "https://{0}.visualstudio.com/defaultcollection/{1}/_apis/build/builds?definitions={2}&type={3}&`$top={4}&api-version=2.0"
$script:runQueryUrl =         "https://{0}.visualstudio.com/defaultcollection/{1}/_apis/wit/wiql?api-version=1.0"
$script:getWorkItemsUrl =     "https://{0}.visualstudio.com/defaultcollection/_apis/wit/workitems?ids={1}&fields=System.Id,System.Title,System.WorkItemType,System.AssignedTo,System.CreatedBy,System.ChangedBy,System.CreatedDate,System.ChangedDate,System.State&api-version=1.0"
$script:openWorkItemUrl=      "https://{0}.visualstudio.com/defaultcollection/_workitems/edit/{1}"

# Override urls to run against a local TFS server
if($PsVsts.OnPremiseMode) {
    $script:projectsUrl =         "http://{0}:8080/tfs/defaultcollection/_apis/projects?api-version=1.0"
    $script:gitReposUrl =         "http://{0}:8080/tfs/defaultcollection/{1}/_apis/git/repositories?api-version=1.0"
    $script:identityUrl =         "http://{0}:8080/tfs/defaultcollection/_api/_identity/CheckName?name={1}"
    $script:pullRequestUrl =      "http://{0}:8080/tfs/defaultcollection/_apis/git/repositories/{1}/pullRequests?api-version=1.0-preview.1"
    $script:openPullRequestUrl =  "http://{0}:8080/tfs/defaultcollection/{1}/_git/{2}/pullrequest/{3}"
    $script:buildDefinitionsUrl = "http://{0}:8080/tfs/defaultcollection/{1}/_apis/build/definitions?name={2}&type={3}&`$top=1&api-version=2.0"
    $script:buildsUrl =           "http://{0}:8080/tfs/defaultcollection/{1}/_apis/build/builds?definitions={2}&type={3}&`$top={4}&api-version=2.0"
    $script:runQueryUrl =         "http://{0}:8080/tfs/defaultcollection/{1}/_apis/wit/wiql?api-version=1.0"
    $script:getWorkItemsUrl=      "http://{0}:8080/tfs/defaultcollection/_apis/wit/workitems?ids={1}&fields=System.Id,System.Title,System.WorkItemType,System.AssignedTo,System.CreatedBy,System.ChangedBy,System.CreatedDate,System.ChangedDate,System.State&api-version=1.0"
    $script:openWorkItemUrl=      "http://{0}:8080/tfs/defaultcollection/_workitems/edit/{1}"
}

$script:stateExcludeFilterQueryPart = "AND ([System.State] NOT IN ({0}))"
$script:stateIncludeFilterQueryPart = "AND ([System.State] IN ({0}))"
$script:identityFilterQueryPart = " [{0}] = @me "
$script:getMyWorkItemsQuery  = "SELECT [System.Id]  
                               FROM WorkItems 
                               WHERE ([System.TeamProject] = @project)
                                     AND ([System.ChangedDate] > '{0}')  
                                     {1} 
                                     AND ({2}) 
                               ORDER BY [{3}] DESC,[System.Id] DESC"



function openWorkItemInBrowser($account, $workItemId) {
    $webWorkItemUrl = [System.String]::Format($script:openWorkItemUrl, $account, $workItemId)

    Start-Process $webWorkItemUrl
}

function getWorkItemsFromIds($account, $wiIds) {
    
    $wiIdString = $wiIds -join ","
    $workItemsUrl = [System.String]::Format($script:getWorkItemsUrl, $account, $wiIdString)
    $workItemsResult = getUrl $workItemsUrl    
    
    if($workItemsResult){
        return $workItemsResult.value
    }
}

function getWorkItemsFromQuery($account, $project, $query, $take) {

    $queryUrl = [System.String]::Format($script:runQueryUrl, $account, $project)

    $payload = @{
        "query" = $query
    }

    $queryResults = postUrl $queryUrl $payload

    if(-not $queryResults) {
        return $null
    }
    # The ids of the workitems in sorted order
    $resultIds = $queryResults.workItems.id | Select-Object -First $take

    if($resultIds) {
        $workItems = getWorkItemsFromIds $account $resultIds
         
        if($workItems) {

            # We need to sort the results by the query results since
            # work items rest call doesn't honor order
            $workItemMap = @{}
            $workItems | ForEach-Object { $workItemMap[$_.Id] = $_ }

            $sortedWorkItems = $resultIds | ForEach-Object { $workItemMap[$_] }
            return $sortedWorkItems

        }
    }

}

function getBuilds($account, $project, $definition, $type, $take) {
    
    $getBuildDefinitionUrl = [System.String]::Format($script:buildDefinitionsUrl, $account, $project, $definition, $type)
    $definitionResult = getUrl $getBuildDefinitionUrl
    if($definitionResult.value) {
        $getBuildUrl = [System.String]::Format($script:buildsUrl, $account, $project, $definitionResult.value.id, $type, $take)
        $buildResults = getUrl $getBuildUrl

        if($buildResults) {
            return $buildResults.value
        }
    }

    return $null
}

function createRepo($account, $project, $repo) {
   $projectId = getProjectId $account $project
   $payload = @{
    "name" = $repoName
    "project" = @{ "id" = $projectId }
   }

    $url = [System.String]::Format($script:gitReposUrl, $account, $project)
    $repoResults = postUrl $url $payload

    if($repoResults) {
        return $repoResults
    }
}


function getRepos($account, $project) {

    $url = [System.String]::Format($script:gitReposUrl, $account, $project)
    $repoResults = getUrl $url

    if($repoResults) {
        return $repoResults.value
    }
    else {
        return $null
    }
}

function getRepoId($account, $project, $repository) {
    
    $repos = getRepos $account $project
    $repos = @($repos | Where-Object { $_.name -eq $repository })

    if($repos.Count -le 0){
        throw "Unable to find repository id for a repository named $repository"
    }

    return $repos[0].id
}


function getProjectId($account, $project) {
    
    # Check in the cache first for this account/project
    $projectId = getProjectIdFromCache $account $project

    # Check if a cache miss call the service and try again
    if(-not $projectId) {
        buildProjectMap $account
        $projectId = getProjectIdFromCache $account $project
    }

    if(-not $projectId) {
        throw "Unable to find the project $project in account $account"
    }

    return $projectId
}

function getProjectIdFromCache($account, $project) {
    
    # Check in the cache first for this account/project
    $projectId = $null
    $projectIdMap = $script:cached_accountProjectMap[$account]
    if($projectIdMap) {
        $projectId = $projectIdMap[$project]
    }

    return $projectId
}


function getProjects($account) {

    $url = [System.String]::Format($script:projectsUrl, $account)
    $projectResults = getUrl $url

    if($projectResults) {
        return $projectResults.value
    }
    else {
        return $null
    }
}

function getIdentityId($account, $name) {

    $url = [System.String]::Format($script:identityUrl, $account, $name)
    
    try {
        $identityResult = getUrl $url
    } catch {

    }

    if($identityResult -and $identityResult.Identity.TeamFoundationId) {
        return $identityResult.Identity.TeamFoundationId
    }
    else {
        Write-Warning "Unable to resolve the name $name"
        return $null
    }
}

function buildProjectMap($account) {
    
    $projectResults = getProjects $account

    if($projectResults) {
        $projectIdMap = @{}

        $projectResults | ForEach-Object { $projectIdMap[$_.name] = $_.id }

        $script:cached_accountProjectMap[$account] = $projectIdMap    
    }
    else {
        Write-Error "Unable to get projects for $account"
    }
}

function postUrl($urlStr, $payload) {
    
    Write-Progress -Activity "Making REST Call" -Status "POST $urlStr"
    
    traceMessage "POST $urlStr"

    $payloadString = ConvertTo-Json $payload
    traceMessage "payload: $payloadString"

    $content = New-Object System.Net.Http.StringContent($payloadString, [System.Text.Encoding]::UTF8, "application/json")

    $httpClient = getHttpClient
    $url = New-Object System.Uri($urlStr)
    $response = $httpClient.PostAsync($urlStr, $content).Result
    
    return processRestReponse $response
}

function getUrl($urlStr) {
    
    Write-Progress -Activity "Making REST Call" -Status "GET $urlStr"
    traceMessage "GET $urlStr"
    

    $httpClient = getHttpClient
    $url = New-Object System.Uri($urlStr)
    $response = $httpClient.GetAsync($urlStr).Result
    return processRestReponse $response
}

function processRestReponse($response) {
    
    $result = $response.Content.ReadAsStringAsync().Result


    try {
        if($result){
            $obj = ConvertFrom-Json $result


            traceMessage "REST RESPONSE: $obj"
        }
    }
    catch {

    }

    if($response.IsSuccessStatusCode) {
        return $obj
    }
    else {
        # TODO: Handle errors from the server
        throw "Recieved an error code of $($response.StatusCode) from the server"
    } 
}


function getHttpClient() {

    if($script:cached_HttpClient){
        return $script:cached_HttpClient;
    }

    $credentials = New-Object Microsoft.VisualStudio.Services.Client.VssClientCredentials
    $credentials.Storage = New-Object Microsoft.VisualStudio.Services.Client.VssClientCredentialStorage("VssApp", "VisualStudio")
    $requestSettings = New-Object Microsoft.VisualStudio.Services.Common.VssHttpRequestSettings
    $messageHandler = New-Object Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler($credentials, $requestSettings)
    $httpClient = New-Object System.Net.Http.HttpClient($messageHandler)
    $httpClient.Timeout = [System.TimeSpan]::FromSeconds($PsVsts.TimeoutInSeconds)
    $httpClient.DefaultRequestHeaders.Add("User-Agent", "PsVsts/1.0");
    
    $script:cached_HttpClient = $httpClient

    return $httpClient
}

tools\lib\VstsOM\Microsoft.VisualStudio.Services.Client.dll
md5: 2A5FFB6A9A0EF9341D9D46948B25AC82 | sha1: 20B2CC0D47E5A63CDE6322E56AA7C5B2BEDAF462 | sha256: D19245E711CD3A1237CC156E7172AC70B5F69C079159BA1B22DBC754E0371F15 | sha512: 86F98F48B884C456835CD36723957E7B5491339E3EA468D84840EEAA41D95D01CD706E3F6D033EB37DCE9B4E0A92D125E06B13967C3C68729F5F8B0D0D34882B
tools\lib\VstsOM\Microsoft.VisualStudio.Services.Common.dll
md5: 4BAE707A37BECC29C1B4101EEE19D479 | sha1: 7DC49E5E8D3623E23887CB2ABE0F0B5E6BA3E5BD | sha256: 24CE38FBEB4FC0976CF63352A6F9FDFCABEE00059D3CF3CF136AADFE24437A65 | sha512: 239DE7FF763E45873BA7C9EBF163EB4581ABC6C81CF87C019AD42EE56460BC6E26761268577EF5446ED96FD44CA40239C94B46262121B80178A3163AF82EE632
tools\lib\VstsOM\Microsoft.VisualStudio.Services.WebApi.dll
md5: 5688E0B8686BE0D926AD0707D2FE7FBF | sha1: 9B9C1B249D36D771978FE0FD121B85CD0FC6BFD0 | sha256: FB93781C64C2F628C5EAC24B4B4319C9DCD9A72AA4D43E14290A7705E70E0CF8 | sha512: 49FB3990E4FF6845CB832C1A90B365DD5416A0ED02BB297184F51FEC886B142D9BD2CCB235B66F087B69F3C8D2671B2083147A5B9F64F7274CEB1E3C34D081B5
tools\PsVsts.psd1
 
tools\PsVsts.psm1
# PsVsts

$ErrorActionPreference = "Stop"

$moduleRoot = Split-Path -Path $MyInvocation.MyCommand.Path
if(-not $Global:PsVsts) { 
    $Global:PsVsts = @{} 
    $PsVsts.EnableLogging=$false
    $PsVsts.OnPremiseMode=$false
    $PsVsts.TimeoutInSeconds=30
}

"$moduleRoot\functions\*.ps1", "$moduleRoot\cmdlets\*.ps1" |
Resolve-Path |
Where-Object { -not ($_.ProviderPath.Contains(".Tests.")) } |
ForEach-Object { . $_.ProviderPath }



Update-FormatData -PrependPath "$moduleRoot\WorkItem.Format.ps1xml"
Update-FormatData -PrependPath "$moduleRoot\Build.Format.ps1xml"`


Export-ModuleMember Push-ToVsts, 
                    Submit-PullRequest,
                    Get-Builds, 
                    Get-VstsConfig, 
                    Set-VstsConfig, 
                    Get-MyWorkItems,
                    Get-WorkItems, 
                    Open-WorkItems 
                    #,getUrl, postUrl, getProjects, getRepos, getProjectId, getIdentityId, getRepoId,getWorkItemsFromQuery

Export-ModuleMember -Variable PsVsts
tools\setup.ps1
function Install-PsVsts($here) {


    $ModulePaths = @($env:PSModulePath -split ';')

    $ExpectedUserModulePath = Join-Path -Path ([Environment]::GetFolderPath('MyDocuments')) -ChildPath WindowsPowerShell\Modules
    $Destination = $ModulePaths | Where-Object { $_ -eq $ExpectedUserModulePath}

    if (-not $Destination) {
        $Destination = $ModulePaths | Select-Object -Index 0
    }

    if (-not (Test-Path $Destination)) {
        New-Item $Destination -ItemType Directory -Force | Out-Null
    } elseif (Test-Path (Join-Path $Destination "PsVsts")) {
        Remove-Item (Join-Path $Destination "PsVsts") -Recurse -Force
    }

    $PsVstsPath=Join-Path $Destination "PsVsts"
    if(!(test-Path $PsVstsPath)){
        mkdir $PsVstsPath
    }

    Copy-Item "$here/*" $PsVstsPath -Recurse -Force -Exclude ChocolateyInstall.ps1, Setup.*

    $successMsg = @"
The PsVsts Module has been copied to $PsVstsPath and added to your Module path. 

To find more info visit https://github.com/mmanela/PsVsts or use:
PS:>Get-Help PsVsts
"@
    Write-Host $successMsg

}
tools\WorkItem.Format.ps1xml
 

Log in or click on link to see number of positives.

In cases where actual malware is found, the packages are subject to removal. Software sometimes has false positives. Moderators do not necessarily validate the safety of the underlying software, only that a package retrieves software from the official distribution point and/or validate embedded software against official distribution point (where distribution rights allow redistribution).

Chocolatey Pro provides runtime protection from possible malware.

Add to Builder Version Downloads Last Updated Status

  • Clean up cmdlet definitions

This package has no dependencies.

Discussion for the PsVsts Package

Ground Rules:

  • This discussion is only about PsVsts and the PsVsts package. If you have feedback for Chocolatey, please contact the Google Group.
  • This discussion will carry over multiple versions. If you have a comment about a particular version, please note that in your comments.
  • The maintainers of this Chocolatey Package will be notified about new comments that are posted to this Disqus thread, however, it is NOT a guarantee that you will get a response. If you do not hear back from the maintainers after posting a message below, please follow up by using the link on the left side of this page or follow this link to contact maintainers. If you still hear nothing back, please follow the package triage process.
  • Tell us what you love about the package or PsVsts, or tell us what needs improvement.
  • Share your experiences with the package, or extra configuration or gotchas that you've found.
  • If you use a url, the comment will be flagged for moderation until you've been whitelisted. Disqus moderated comments are approved on a weekly schedule if not sooner. It could take between 1-5 days for your comment to show up.
comments powered by Disqus