Downloads:

3,702

Downloads of v 0.5.0:

314

Last Update:

8/5/2015

Package Maintainer(s):

Software Author(s):

  • Matthew Manela

Tags:

powershell vso tfs git build workitem

PsVso

This is not the latest version of PsVso available.

0.5.0 | Updated: 8/5/2015

Downloads:

3,702

Downloads of v 0.5.0:

314

Maintainer(s):

Software Author(s):

  • Matthew Manela

PsVso 0.5.0

This is not the latest version of PsVso available.

Some Checks Have Failed or Are Not Yet Complete

1 Test Unknown and 1 Passing Test


Validation Testing Unknown


Verification Testing Passed

Details

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

>

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

>

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

>

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

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

  • 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://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. Enter your internal repository url

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

4. Choose your deployment method:


choco upgrade psvso -y --source="'STEP 3 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 psvso -y --source="'STEP 3 URL'" 
$exitCode = $LASTEXITCODE

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

Exit $exitCode

- name: Ensure psvso installed
  win_chocolatey:
    name: psvso
    state: present
    version: 0.5.0
    source: STEP 3 URL

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

Coming early 2020! Central Managment Reporting available now! More information...


chocolatey_package 'psvso' do
  action    :install
  version  '0.5.0'
  source   'STEP 3 URL'
end

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


Chocolatey::Ensure-Package
(
    Name: psvso,
    Version: 0.5.0,
    Source: STEP 3 URL
);

Requires Otter Chocolatey Extension. See docs at https://inedo.com/den/otter/chocolatey.


cChocoPackageInstaller psvso
{
   Name     = 'psvso'
   Ensure   = 'Present'
   Version  = '0.5.0'
   Source   = 'STEP 3 URL'
}

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


package { 'psvso':
  provider => 'chocolatey',
  ensure   => '0.5.0',
  source   => 'STEP 3 URL',
}

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


salt '*' chocolatey.install psvso version="0.5.0" source="STEP 3 URL"

See docs at https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.chocolatey.html.

5. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

This package was approved as a trusted package on 8/5/2015.

Description

PsVso provides a suite of PowerShell functions that help automate interaction with VisualStudio Online. Some of the functions include Push-ToVso (quickly take a local git repo and host it in a VSO project), Submit-PullRequest (submits a pull request), Get-XamlBuildStatus (gets the status of the last completed XAML build) and Get-MyWorkItems (lists work items created by or assigned to you).

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


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

function Get-BuildStatus {
<#
.SYNOPSIS
Gets the current status of the build

.DESCRIPTION
Get-BuildStatus will query your VSO project to see the status of the last build. This is usefull to make sure you don't push 
changes when the build is not green

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

.PARAMETER Account
The acount name to use. Can be inherited from a config file.
If your VSO 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-BuildStatus -BuildDefinition myBuildDef -Account myAccount -Project myProject

.LINK
about_PsVso

#>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false)]
        [string]$BuildDefinition,
        [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

    if($buildResults) {
        if(($buildResults[0].status -eq "succeeded") -or ($buildResults[0].status -eq "completed")) {
            Write-Host "Build $($buildResults[0].buildNumber) SUCCEEDED" -ForegroundColor Green
        }
        elseif($buildResults[0].status -eq "failed") {
            Write-Host "Build $($buildResults[0].buildNumber) FAILED" -ForegroundColor Red
        }
        else {
            Write-Host "Build $($buildResults[0].buildNumber) $($buildResults[0].status.ToUpper())"
        }
        
    }
    else {
        Write-Warning "Unable to find build for $definitionName"
    }

}
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 VSO 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_PsVso

#>
    [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).ToUniversalTime().Date.ToString("o")


    $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-VsoConfig.ps1

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

.DESCRIPTION
Get-VsoConfig 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-VsoConfig 

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

.Example
Get-VsoConfig -Global

Gets all the global config values.

.LINK
about_PsVso

#>
    [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\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 VSO 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_PsVso

#>
    [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-ToVso.ps1

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

.DESCRIPTION
Calling Push-ToVso will clone your git repo to a VSO 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 VSO 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-ToVso 

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-ToVso -Project MyProject -Account MyAccount

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

.LINK
about_PsVso

#>
    [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 psvso remote name
   $currentRemotes = git remote
   $remoteName = "origin"
   if($currentRemotes -and $currentRemotes.Contains("origin")) {
    Write-Host "origin remote already exists so create psvso remote"
    $remoteName = "psvso"
   }

    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\Query-WorkItems.ps1

function Query-WorkItems {
<#
.SYNOPSIS
Queries for work items given WIQL

.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. 

.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 VSO 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
Query-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
Query-WorkItems -Query  "SELECT [System.Id], [System.Title] FROM WorkItems WHERE [System.TeamProject] = @project AND [System.AssignedTo] = 'Joe Smith'" -Take 10


.LINK
about_PsVso

#>
    [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 = $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=$_
            } 
        }


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

    return $workItems
}
tools\cmdlets\Set-VsoConfig.ps1

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

.DESCRIPTION
Set-VsoConfig 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-VsoConfig -Name Project -Value MyProject

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

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

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

.LINK
about_PsVso

#>
    [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-VsoConfig -Local
    }
    else {
        $configPath = $script:globalConfigPath
        $configObject = Get-VsoConfig -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 VSO 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_PsVso

#>
    [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
	PsVso

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

DESCRIPTION
	PsVso 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 = "PsVso.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-VsoConfig
}

# 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
}
tools\functions\trace.ps1
function traceMessage($message) {
    if($PsVso.EnableLogging) {
        Write-Host $message
    }
}
tools\functions\vso.ps1
# Functions and variables used for communication with VSO


$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=1&resultFilter=Failed,PartiallySucceeded,Succeeded&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($PsVso.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=1&resultFilter=Failed,PartiallySucceeded,Succeeded&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 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) {
        $wiIds = $resultIds -join ","
        $workItemsUrl = [System.String]::Format($script:getWorkItemsUrl, $account, $wiIds)
        $workItemsResult = getUrl $workItemsUrl
         
        if($workItemsResult) {
            $workItems = $workItemsResult.value

            # 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) {
    
    $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)
        $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"

    $httpClient = getHttpClient
    $response = $httpClient.PostUrl($urlStr, $payloadString)
    
    return processRestReponse $response
}

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

    $httpClient = getHttpClient
    $response = $httpClient.GetUrl($urlStr)
    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;
    }

    $script:cached_HttpClient = new-object VsoRestProxy.VsoProxy("PsVso/1.0")

    return $script:cached_HttpClient
}

tools\PsVso.psm1
# PsVso

$ErrorActionPreference = "Stop"

$moduleRoot = Split-Path -Path $MyInvocation.MyCommand.Path
if(-not $Global:PsVso) { 
    $Global:PsVso = @{} 
    $PsVso.EnableLogging=$false
    $PsVso.OnPremiseMode=$false
    $PsVso.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"


Export-ModuleMember Push-ToVso, 
                    Submit-PullRequest,
                    Get-BuildStatus, 
                    Get-VsoConfig, 
                    Set-VsoConfig, 
                    Get-MyWorkItems,
                    Query-WorkItems, 
                    Open-WorkItems 
                    #,getUrl, postUrl, getProjects, getRepos, getProjectId, getIdentityId, getRepoId,getWorkItemsFromQuery

Export-ModuleMember -Variable PsVso
tools\setup.ps1
function Install-PsVso($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 "PsVso")) {
        Remove-Item (Join-Path $Destination "PsVso") -Recurse -Force
    }

    $PsVsoPath=Join-Path $Destination "PsVso"
    if(!(test-Path $PsVsoPath)){
        mkdir $PsVsoPath
    }

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

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

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

}

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.

Version Downloads Last Updated Status
PsVso 0.5.0 314 Wednesday, August 5, 2015 Approved
PsVso 0.4.0 267 Thursday, May 14, 2015 Approved
PsVso 0.3.1 331 Sunday, January 25, 2015 Approved
PsVso 0.3.0 399 Sunday, December 14, 2014 Approved
PsVso 0.2.17 313 Thursday, December 4, 2014 Approved
PsVso 0.2.16 277 Thursday, December 4, 2014 Approved
PsVso 0.2.13 251 Tuesday, December 2, 2014 Approved
PsVso 0.2.10 322 Tuesday, November 25, 2014 Approved
PsVso 0.2.6 282 Monday, November 24, 2014 Approved

  • Fix formatting on work item output
    * Open pull request after creating one
    * Allow SourceBranch and TargetBranch to be inherited from config

This package has no dependencies.

Discussion for the PsVso Package

Ground Rules:

  • This discussion is only about PsVso and the PsVso 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 PsVso, 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