Connection/Connection.psm1

<#
 
.SYNOPSIS
    Connects to a configuration server.
 
.PARAMETER Credential
    Specifies a user account that has permission to perform this action. The default is the cached credential of the user under which the PowerShell process is being run - in most cases that corresponds to the user currently logged in. To provide a user name and password, and/or to open a input dialog to enter your credentials, call Get-TfsCredential with the appropriate arguments and pass its return to this argument. For more information, refer to https://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.client.tfsclientcredentials.aspx
 
.PARAMETER Passthru
    Returns the results of the command. By default, this cmdlet does not generate any output.
 
.DESCRIPTION
    The Connect-TfsConfigurationServer function connects to a TFS configuration server. Functions that operate on a server level (as opposed to those operation on a team project collection level) will use by default a connection opened by this function.
 
.NOTES
    A TFS Configuration Server represents the server that is running Team Foundation Server. On a database level, it is represented by the Tfs_Configuration database. Operations that should be performed on a server level (such as setting server-level permissions) require a connection to a TFS configuration server. Internally, this connection is represented by an instance of the Microsoft.TeamFoundation.Client.TfsConfigurationServer class and is kept in a PowerShell global variable caled TfsServerConnection .
 
.PARAMETER Interactive
    Prompts for user credentials. Can be used for both TFS and VSTS accounts - the proper login dialog is automatically selected. Should only be used in an interactive PowerShell session (i.e., a PowerShell terminal window), never in an unattended script (such as those executed during an automated build).
     
.INPUTS
    Microsoft.TeamFoundation.Client.TfsConfigurationServer
    System.String
    System.Uri
#>

Function Connect-TfsConfigurationServer
{
    [CmdletBinding(DefaultParameterSetName="Explicit credentials")]
    [OutputType([Microsoft.TeamFoundation.Client.TfsConfigurationServer])]
    Param
    (
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [ValidateNotNull()]
        [object] 
        $Server,
    
        [Parameter(ParameterSetName="Explicit credentials")]
        [object]
        $Credential,

        [Parameter(ParameterSetName="Prompt for credentials", Mandatory=$true)]
        [switch]
        $Interactive,

        [Parameter()]
        [switch]
        $Passthru
    )

    Process
    {
        if ($Interactive.IsPresent)
        {
            $Credential = (Get-TfsCredential -Interactive)
        }

        $configServer = Get-TfsConfigurationServer -Server $Server -Credential $Credential

        if (-not $configServer)
        {
            throw "Error connecting to TFS"
        }

        $Global:TfsTeamConnection = $null
        $Global:TfsProjectConnection = $null
        $Global:TfsTpcConnection = $null
        $Global:TfsServerConnection = $configServer

        if ($Passthru)
        {
            return $configServer
        }
    }
}
<#
 
.SYNOPSIS
    Connects to a team project.
 
.PARAMETER Credential
    Specifies a user account that has permission to perform this action. The default is the cached credential of the user under which the PowerShell process is being run - in most cases that corresponds to the user currently logged in. To provide a user name and password, and/or to open a input dialog to enter your credentials, call Get-TfsCredential with the appropriate arguments and pass its return to this argument. For more information, refer to https://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.client.tfsclientcredentials.aspx
 
.PARAMETER Interactive
    Prompts for user credentials. Can be used for both TFS and VSTS accounts - the proper login dialog is automatically selected. Should only be used in an interactive PowerShell session (i.e., a PowerShell terminal window), never in an unattended script (such as those executed during an automated build).
 
.PARAMETER Passthru
    Returns the results of the command. By default, this cmdlet does not generate any output.
 
#>

Function Connect-TfsTeamProject
{
    [CmdletBinding(DefaultParameterSetName="Explicit credentials")]
    [OutputType([Microsoft.TeamFoundation.WorkItemTracking.Client.Project])]
    Param
    (
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [ValidateNotNull()]
        [object] 
        $Project,
    
        [Parameter()]
        [object] 
        $Collection,
    
        [Parameter(ParameterSetName="Explicit credentials")]
        [object]
        $Credential,

        [Parameter(ParameterSetName="Prompt for credentials", Mandatory=$true)]
        [switch]
        $Interactive,

        [Parameter()]
        [switch]
        $Passthru
    )

    Process
    {
        if ($Interactive.IsPresent)
        {
            $Credential = (Get-TfsCredential -Interactive)
        }

        $tp = (Get-TfsTeamProject -Project $Project -Collection $Collection -Credential $Credential | Select -First 1)

        if (-not $tp)
        {
            throw "Error connecting to team project $Project"
        }

        $Global:TfsTeamConnection = $null
        $Global:TfsProjectConnection = $tp
        $Global:TfsTpcConnection = $tp.Store.TeamProjectCollection
        $Global:TfsServerConnection = $Global:TfsTpcConnection.ConfigurationServer

        if ($Passthru)
        {
            return $tp
        }
    }
}
<#
 
.SYNOPSIS
Connects to a team project collection.
 
.DESCRIPTION
The Connect-TfsTeamProjectCollection cmdlet "connects" (initializes a Microsoft.TeamFoundation.Client.TfsTeamProjectCollection object) to a TFS Team Project Collection. That connection is subsequently kept in a global variable to be later reused until it's closed by a call to Disconnect-TfsTeamProjectCollection.
Most cmdlets in the TfsCmdlets module require a TfsTeamProjectCollection object to be provided via their -Collection argument in order to access a TFS instance. Those cmdlets will use the connection opened by Connect-TfsTeamProjectCollection as their "default connection". In other words, TFS cmdlets (e.g. New-TfsWorkItem) that have a -Collection argument will use the connection provided by Connect-TfsTeamProjectCollection by default.
 
.PARAMETER Collection
Specifies either a URL/name of the Team Project Collection to connect to, or a previously initialized TfsTeamProjectCollection object.
When a TfsTeamProjectCollection object is provided via this argument, it will be used as the new default connection. This may be especially useful if you e.g. received a pre-initialized connection to a TFS collection via a call to an external library or API.
For more details, see the -Collection argument in the Get-TfsTeamProjectCollection cmdlet.
 
.PARAMETER Server
Specifies either a URL or the name of the Team Foundation Server configuration server (the "root" of a TFS installation) to connect to, or a previously initialized Microsoft.TeamFoundation.Client.TfsConfigurationServer object.
For more details, see the -Server argument in the Get-TfsConfigurationServer cmdlet.
 
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the cached credential of the user under which the PowerShell process is being run - in most cases that corresponds to the user currently logged in. To provide a user name and password, and/or to open a input dialog to enter your credentials, call Get-TfsCredential with the appropriate arguments and pass its return to this argument. For more information, refer to https://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.client.tfsclientcredentials.aspx
 
.PARAMETER Interactive
Prompts for user credentials. Can be used for both TFS and VSTS accounts - the proper login dialog is automatically selected. Should only be used in an interactive PowerShell session (i.e., a PowerShell terminal window), never in an unattended script (such as those executed during an automated build).
     
.PARAMETER Passthru
Returns the results of the command. By default, this cmdlet does not generate any output.
 
.EXAMPLE
    Connect-TfsTeamProjectCollection -Collection http://tfs:8080/tfs/DefaultCollection
    Connects to a collection called "DefaultCollection" in a TF server called "tfs" using the default credentials of the logged-on user
 
.EXAMPLE
    Connect-TfsTeamProjectCollection -Collection http://tfs:8080/tfs/DefaultCollection -Interactive
    Connects to a collection called "DefaultCollection" in a Team Foundation server called "tfs", firstly prompting the user for credentials (it ignores the cached credentials for the currently logged-in user). It's equivalent to the command:
 
    PS> Connect-TfsTeamProjectCollection -Collection http://tfs:8080/tfs/DefaultCollection -Credential (Get-TfsCredential -Interactive)
 
.LINK
    Get-TfsTeamProjectCollection
 
.LINK
    https://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.client.tfsteamprojectcollection.aspx
 
.INPUTS
    Microsoft.TeamFoundation.Client.TfsTeamProjectCollection
    System.String
    System.Uri
#>

Function Connect-TfsTeamProjectCollection
{
    [CmdletBinding(DefaultParameterSetName="Explicit credentials")]
    [OutputType([Microsoft.TeamFoundation.Client.TfsTeamProjectCollection])]
    Param
    (
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [ValidateNotNull()]
        [object] 
        $Collection,
    
        [Parameter()]
        [object] 
        $Server,
    
        [Parameter(ParameterSetName="Explicit credentials")]
        [object]
        $Credential,

        [Parameter(ParameterSetName="Prompt for credentials", Mandatory=$true)]
        [switch]
        $Interactive,

        [Parameter()]
        [switch]
        $Passthru
    )

    Process
    {
        $tpc = $null

        try
        {
            if ($Interactive.IsPresent)
            {
                $Credential = (Get-TfsCredential -Interactive)
            }

            $tpc = (Get-TfsTeamProjectCollection -Collection $Collection -Server $Server -Credential $Credential | Select -First 1)
            $tpc.EnsureAuthenticated()
        }
        catch
        {
            throw "Error connecting to team project collection $Collection ($_)"
        }

        $Global:TfsTeamConnection = $null
        $Global:TfsProjectConnection = $null
        $Global:TfsTpcConnection = $tpc
        $Global:TfsServerConnection = $tpc.ConfigurationServer

        if ($Passthru)
        {
            return $tpc
        }
    }
}
<#
 
.SYNOPSIS
    Disconnects from the currently connected configuration server.
 
.DESCRIPTION
    The Disconnect-TfsConfigurationServer cmdlet removes the global variable set by Connect-TfsConfigurationServer. Therefore, cmdlets relying on a "default server" as provided by "Get-TfsConfigurationServer -Current" will no longer work after a call to this cmdlet, unless their -Server argument is provided or a new call to Connect-TfsConfigurationServer is made.
 
.EXAMPLE
    Disconnect-TfsConfigurationServer
    Disconnects from the currently connected TFS configuration server
 
#>

Function Disconnect-TfsConfigurationServer
{
    Process
    {
        Disconnect-TfsTeamProjectCollection

        if ($Global:TfsServerConnection)
        {
            Remove-Variable -Name TfsServerConnection -Scope Global
        }
    }
}
<#
 
.SYNOPSIS
    Disconnects from the currently connected team project.
 
.DESCRIPTION
    The Disconnect-TfsTeamProject cmdlet removes the global variable set by Connect-TfsTeamProject . Therefore, cmdlets relying on a "default project" as provided by "Get-TfsTeamProject -Current" will no longer work after a call to this cmdlet, unless their -Project argument is provided or a new call to Connect-TfsTeamProject is made.
 
.EXAMPLE
    Disconnect-TfsTeamProject
    Disconnects from the currently connected TFS team project
 
#>

Function Disconnect-TfsTeamProject
{
    Process
    {
        if ($Global:TfsProjectConnection)
        {
            Remove-Variable -Name TfsProjectConnection -Scope Global
        }
    }
}
<#
 
.SYNOPSIS
    Disconnects from the currently connected team project collection.
 
.DESCRIPTION
    The Disconnect-TfsTeamProjectCollection cmdlet removes the global variable set by Connect-TfsTeamProjectCollection. Therefore, cmdlets relying on a "default collection" as provided by "Get-TfsTeamProjectCollection -Current" will no longer work after a call to this cmdlet, unless their -Collection argument is provided or a new call to Connect-TfsTeamProjectCollection is made.
 
.EXAMPLE
    Disconnect-TfsTeamProjectCollection
    Disconnects from the currently connected TFS team project collection
 
#>

Function Disconnect-TfsTeamProjectCollection
{
    Process
    {
        Disconnect-TfsTeamProject

        if ($Global:TfsTpcConnection)
        {
            Remove-Variable -Name TfsTpcConnection -Scope Global
        }
    }
}
<#
.SYNOPSIS
    Provides credentials to use when you connect to a Team Foundation Server or Visual Studio Team Services account.
 
.DESCRIPTION
 
.NOTES
 
.INPUTS
    
#>

Function Get-TfsCredential
{
    [CmdletBinding(DefaultParameterSetName="Prompt for credential")]
    [OutputType([Microsoft.TeamFoundation.Client.TfsClientCredentials])]
    Param
    (
        [Parameter(ParameterSetName="Cached Credential", Mandatory=$true)]
        [switch]
        $Cached,

        [Parameter(ParameterSetName="User name and password", Mandatory=$true, Position=1)]
        [string]
        $UserName,

        [Parameter(ParameterSetName="User name and password", Position=2)]
        [securestring]
        $Password,

        [Parameter(ParameterSetName="Credential object")]
        [object]
        $Credential,

        [Parameter(ParameterSetName="Personal Access Token")]
        [Alias('Pat')]
        $PersonalAccessToken,

        [Parameter(ParameterSetName="Prompt for credential")]
        [switch]
        $Interactive
    )

    Process
    {
        $parameterSetName = $PSCmdlet.ParameterSetName
        
        if (($parameterSetName -eq 'Credential object') -and (-not $Credential))
        {
            $parameterSetName = 'Cached Credential'
        }

        $allowInteractive = $false

        switch($parameterSetName)
        {
            'Cached Credential' {
                $fedCred = New-Object 'Microsoft.TeamFoundation.Client.CookieCredential' -ArgumentList $true
                $winCred = New-Object 'Microsoft.TeamFoundation.Client.WindowsCredential' -ArgumentList $true
            }

            'User name and password' {
                $netCred = New-Object 'System.Net.NetworkCredential' -ArgumentList $UserName, $Password
                $fedCred = New-Object 'Microsoft.TeamFoundation.Client.BasicAuthCredential' -ArgumentList $netCred
                $winCred = New-Object 'Microsoft.TeamFoundation.Client.WindowsCredential' -ArgumentList $netCred
            }

            'Credential object' {
                if ($Credential -is [Microsoft.TeamFoundation.Client.TfsClientCredentials])
                {
                    return $Credential
                }

                if($Credential -is [pscredential])
                {
                    $netCred = $Credential.GetNetworkCredential()
                }
                elseif ($Credential -is [System.Net.NetworkCredential])
                {
                    $netCred = $Credential
                }
                else
                {
                    throw "Invalid argument Credential. Supply either a PowerShell credential (PSCredential object) or a System.Net.NetworkCredential object."    
                }

                $fedCred = New-Object 'Microsoft.TeamFoundation.Client.BasicAuthCredential' -ArgumentList $netCred
                $winCred = New-Object 'Microsoft.TeamFoundation.Client.WindowsCredential' -ArgumentList $netCred
            }

            'Personal Access Token' {
                $netCred = New-Object 'System.Net.NetworkCredential' -ArgumentList 'dummy-pat-user', $PersonalAccessToken
                $fedCred = New-Object 'Microsoft.TeamFoundation.Client.BasicAuthCredential' -ArgumentList $netCred
                $winCred = New-Object 'Microsoft.TeamFoundation.Client.WindowsCredential' -ArgumentList $netCred
            }

            'Prompt for credential' {
                $fedCred = New-Object 'Microsoft.TeamFoundation.Client.CookieCredential' -ArgumentList $false
                $winCred = New-Object 'Microsoft.TeamFoundation.Client.WindowsCredential' -ArgumentList $false
                $allowInteractive = $true
            }

            else {
                throw "Invalid parameter set $($PSCmdlet.ParameterSetName)"
            }
        }

        return New-Object 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -ArgumentList $winCred, $fedCred, $allowInteractive
    }
}