Downloads:

3,716

Downloads of v 0.2.6:

282

Last Update:

11/24/2014

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.2.6 | Updated: 11/24/2014

Downloads:

3,716

Downloads of v 0.2.6:

282

Maintainer(s):

Software Author(s):

  • Matthew Manela

PsVso 0.2.6

This is not the latest version of PsVso available.

All Checks are Unknown

2 Test of Unknown Status


Validation Testing Unknown


Verification Testing Unknown

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.2.6
    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.2.6'
  source   'STEP 3 URL'
end

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


Chocolatey::Ensure-Package
(
    Name: psvso,
    Version: 0.2.6,
    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.2.6'
   Source   = 'STEP 3 URL'
}

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


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

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


salt '*' chocolatey.install psvso version="0.2.6" 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 by moderator gep13 on 11/24/2014.

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-BuildStatus (gets the status of the last completed 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)"
    Write-ChocolateySuccess "PsVso"
} 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
    )

    refreshCachedConfig

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

    $buildResults = getBuilds $accountName $projectName $definitionName

    if($buildResults) {
        if($buildResults[0].status -eq "succeeded") {
            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
  Removed
  Closed
  Cut
  Closed


.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 IncludeAllStates
By default Get-MyWorkItems trys to filter out "finished" items. This property
prevents this behavior.

.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)]
        [string]$OrderBy,
        [Parameter(Mandatory = $false)]
        [int]$Take = 200,
        [Parameter(Mandatory = $false)]
        [switch]$IncludeAllStates,
        [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()

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

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

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

    $workItems = getWorkItemsFromQuery $accountName $projectName $query $take

    $global:__res = $workItems
    # 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=$_
            } 
        }


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

    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
    )

    Process {
        refreshCachedConfig


        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\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) {
        $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


    Write-Host "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.


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

.PARAMETER TargetBranch
The branch you want to merge to.

.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 = $true)]
        [string]$SourceBranch,
        [Parameter(Mandatory = $true)]
        [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

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

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

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

    $payload = @{
        "sourceRefName" = $SourceBranch
        "targetRefName" = $TargetBranch
        "title"= $Title
        "description" = $Description
        "reviewers" = $reviewerIds | ForEach-Object { @{ "id" = $_ } }
    }

    $repoId = getRepoId $accountName $projectName $repoName


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

    if($repoResults) {
         Write-Host "Pull request created at $($repoResults.url)"
    }

}
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"


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
        $jsonObject = ConvertFrom-Json $content
        $jsonObject.psobject.Properties | ForEach-Object { $configHash[$_.Name] = $_.Value }
    }

    return $configHash
}
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:buildsUrl =      "https://{0}.visualstudio.com/defaultcollection/{1}/_apis/build/builds?definition={2}&`$top=1&status=Failed,PartiallySucceeded,Succeeded&api-version=1.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}"

# Temp overrides to run against a local TFS server
if($false) {
    $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:buildsUrl =      "http://{0}:8080/tfs/defaultcollection/{1}/_apis/build/builds?definition={2}&`$top=1&status=Failed,PartiallySucceeded,Succeeded&api-version=1.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:stateFilterQueryPart = "AND ([System.State] NOT IN ({0}))"
$script:getMyWorkItemsQuery  = "SELECT [System.Id]  
                               FROM Issue 
                               WHERE ([System.AssignedTo] = @me OR [System.CreatedBy] = @me) 
                                     AND ([System.ChangedDate] > '{0}')  
                                     {1}
                                     AND ([System.TeamProject] = @project)
                               ORDER BY [{2}] 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) {
    
    $url = [System.String]::Format($script:buildsUrl, $account, $project, $definition)
    $buildResults = getUrl $url


    if($buildResults) {
        return $buildResults.value
    }
    else {
        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"
    
    Write-Host "POST $urlStr"

    $payloadString = ConvertTo-Json $payload
    Write-Host "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"
    Write-Host "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
        }
    }
    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]::FromMinutes(30)
    $httpClient.DefaultRequestHeaders.Add("User-Agent", "PsVso/1.0");
    
    $script:cached_HttpClient = $httpClient

    return $httpClient
}
tools\PsVso.psm1
# PsVso

$ErrorActionPreference = "Stop"

$moduleRoot = Split-Path -Path $MyInvocation.MyCommand.Path

"$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, Open-WorkItems,
                    getUrl, postUrl, getProjects, getRepos, getProjectId, getIdentityId, getRepoId,getWorkItemsFromQuery
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 317 Wednesday, August 5, 2015 Approved
PsVso 0.4.0 267 Thursday, May 14, 2015 Approved
PsVso 0.3.1 332 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 278 Thursday, December 4, 2014 Approved
PsVso 0.2.13 253 Tuesday, December 2, 2014 Approved
PsVso 0.2.10 324 Tuesday, November 25, 2014 Approved
PsVso 0.2.6 282 Monday, November 24, 2014 Approved

  • Added Get-MyWorkItems
    * Added Open-WorkItems
    * Made local config default

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