powershell - 使用 Powershell 将文件 checkin TFS

标签 powershell tfs tfs-power-tools

作为持续集成构建的一部分,我正在创建一个 SQL 脚本。此 SQL 脚本在生成后必须重新检入到 TFS。我在 Powershell 中使用 TFS Powertools。

我在我的机器上使用的代码是:

Add-TfsPendingChange -Add -Item $filename | New-TfsChangeSet

这在我的开发箱上运行良好,因为我所在的文件夹映射到 TFS 工作区。当我将它移动到我的构建服务器时,它不再工作,因为 TeamCity 不会将它的结帐映射到工作区,它只是将文件拉下来。

如何将文件检入 TFS 中的特定文件夹而不在映射工作区中?这甚至可能吗?

最佳答案

我使用 GO 为我们的持续交付项目做了一些工作。我使用 PowerShell 和 .NET 程序集提供程序与团队资源管理器的组合使其工作。我无法让它纯粹在 PowerShell 中工作(尽管可能有办法!)

以下脚本将检入作为参数提供给指定服务器路径(也是参数)的 Material 路径中包含的任何内容。您还可以指定要使用的凭据和 TFS 服务器的 url。

此代码需要安装 Visual Studio 或 TFS 团队资源管理器客户端。您需要在 AssemblyPath 参数中向脚本提供程序集的目录位置。如果未找到这些程序集,则脚本将出错并显示缺少哪些程序集。

注意:代码已经有一段时间没有检查过,所以可能会有拼写错误等。如果您有任何问题,请告诉我,我会尽力提供帮助。

[CmdletBinding(PositionalBinding=$false)]
Param(
    [Parameter(Mandatory)] [string] $ServerUrl,
    [Parameter(Mandatory)] [string] $ServerPath,
    [Parameter(Mandatory=$False)] [string] $Domain = "",
    [Parameter(Mandatory=$False)] [string] $Username = "",
    [Parameter(Mandatory=$False)] [System.Security.SecureString] $Password,
    [Parameter(Mandatory)] [string] [ValidateScript({($_ -eq $null) -or (Test-Path -Path $_ -PathType Container)})] $MaterialPath,
    [Parameter(Mandatory)] [string] [ValidateScript({ Test-Path -Path $_ -PathType Container})] $AssemblyPath
)

<#
    .SYNOPSIS
    Responsible for checking in files into Source Control
    .DESCRIPTION
#>

$clientDllName = "Microsoft.TeamFoundation.Client.dll"
$commonDllName = "Microsoft.TeamFoundation.Common.dll"
$versionControlClientDllName = "Microsoft.TeamFoundation.VersionControl.Client.dll"
$versionControlClientCommonDllName = "Microsoft.TeamFoundation.VersionControl.Common.dll"


#Create global variables to hold the value of Debug and Verbose action preferences which can then be used for all module function calls and passed into the remote session.
$verboseParameter = $PSCmdlet.MyInvocation.BoundParameters["Verbose"]
if ($verboseParameter -ne $null)
{
    $Global:Verbose = [bool]$verboseParameter.IsPresent
}
else
{
    $Global:Verbose = $false
}
$debugParameter = $PSCmdlet.MyInvocation.BoundParameters["Debug"]
if ($debugParameter -ne $null)
{
    $Global:Debug = [bool]$debugParameter.IsPresent
}
else
{
    $Global:Debug = $false
}

$scriptName = $(Split-Path -Leaf $PSCommandPath)

#Ensure any errors cause failure
$ErrorActionPreference = "Stop"

Write-Host "Running script ""$scriptName"" as user ""$env:USERDOMAIN\$env:USERNAME"""

#Check assembly path is a valid directory
If (Test-Path -Path $AssemblyPath -PathType Container)
{
    Write-Host "Loading required assemblies from assembly path ""$AssemblyPath"""

    $clientDllPath = Join-Path -Path $AssemblyPath -ChildPath $clientDllName
    $commonDllPath = Join-Path -Path $AssemblyPath -ChildPath $commonDllName
    $versionControlClientDllPath = Join-Path -Path $AssemblyPath -ChildPath $versionControlClientDllName
    $versionControlClientCommonDllPath = Join-Path -Path $AssemblyPath -ChildPath $versionControlClientCommonDllName

    If (!Test-Path -Path $clientDllPath -PathType Leaf)
    {
        Throw "Required assembly ""$clientDllName"" not found at path ""$clientDllPath"""
    }
    If (!Test-Path -Path $commonDllPath -PathType Leaf)
    {
        Throw "Required assembly ""$commonDllName"" not found at path ""$commonDllPath"""
    }
    If (!Test-Path -Path $versionControlClientDllPath -PathType Leaf)
    {
        Throw "Required assembly ""$versionControlClientDllName"" not found at path ""$versionControlClientDllPath"""
    }
    If (!Test-Path -Path $versionControlClientCommonDllPath -PathType Leaf)
    {
        Throw "Required assembly ""$versionControlClientCommonDllName"" not found at path ""$versionControlClientCommonDllPath"""
    }

    #Load the Assemblies
    [Reflection.Assembly]::LoadFrom($clientDllPath) | Out-Null
    [Reflection.Assembly]::LoadFrom($commonDllPath)| Out-Null
    [Reflection.Assembly]::LoadFrom($versionControlClientDllPath) | Out-Null
    [Reflection.Assembly]::LoadFrom($versionControlClientCommonDllPath) | Out-Null

    #If the credentials have been specified then create a credential object otherwise we will use the default ones
    If ($Username -and $Password)
    {

        $creds = New-Object System.Net.NetworkCredential($Username,$Password,$Domain)
        Write-Host "Created credential object for user ""$($creds.UserName)"" in domain ""$($creds.Domain)"""

        $tfsProjectCollection = New-Object Microsoft.TeamFoundation.Client.TFSTeamProjectCollection($ServerUrl, $creds)
    }
    else
    {
        Write-Host "Using default credentials for user ""$Env:Username"""
        $tfsProjectCollection = New-Object Microsoft.TeamFoundation.Client.TFSTeamProjectCollection($ServerUrl)
    }

    $versionControlType = [Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]
    $versionControlServer = $tfsProjectCollection.GetService($versionControlType)

    Write-Host "Version control server authenticated user: $($versionControlServer.AuthenticatedUser)"

    #Create a local path in the temp directory to hold the workspace
    $LocalPath = Join-Path -Path $env:TEMP -ChildPath $([System.Guid]::NewGuid().ToString())
    $null = New-Item -Path $LocalPath -ItemType Directory

    #Create a "workspace" and map a local folder to a TFS location
    $workspaceName = "PowerShell Workspace_{0}" -f [System.Guid]::NewGuid().ToString()
    $workspace = $versionControlServer.CreateWorkspace($workspaceName, $versionControlServer.AuthenticatedUser)
    $workingfolder = New-Object Microsoft.TeamFoundation.VersionControl.Client.WorkingFolder($ServerPath,$LocalPath)
    $result = $workspace.CreateMapping($workingFolder)
    $result = $workspace.Get() #Get the latest version into the workspace

    Write-Host "Copying files from materials path ""$MaterialPath"" to temporary workspace path ""$LocalPath"""
    robocopy $MaterialPath $LocalPath /s | Out-Null

    $checkInComments = "Files automatically checked in by PowerShell script ""$scriptName"""

    #Submit file as a Pending Change and submit the change
    $result = $workspace.PendAdd($LocalPath,$true)
    $pendingChanges = $workspace.GetPendingChanges()

    Write-Host "Getting pending changes"

    #Only try to check in if there are changes
    If ($pendingChanges -ne $null)
    {
        If ($pendingChanges.Count -gt 0)
        {
            $changeSetId = $workspace.CheckIn($pendingChanges,$checkInComments)

            Write-Host "Successfully checked in ""$($pendingChanges.Count)"" changes using changeset id ""$changeSetId"""
        }
        else
        {
            Write-Host "No changes to check-in"
        }
    }
    else
    {
        Write-Host "No changes to check-in"
    }

    Write-Host "Deleting workspace and temporary folders"
    $result = $workspace.Delete()
    $null = Remove-Item -Path $LocalPath -Recurse -Force
}
else
{
    Write-Error "The path to required assemblies ""$AssemblyPath"" cannot be found"
}

关于powershell - 使用 Powershell 将文件 checkin TFS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25917753/

相关文章:

powershell - 如何在Powershell中测试无效路径?

tfs - Team Foundation - 通过标签查询用户故事

tfs - Azure 网站在 TFS 上构建和部署时缺少 msshrtmi

Powershell模板

azure - 如何获取 Azure VM 及其 VNet 的报告?

powershell - 脚本中混合使用 groovy 和 powershell 变量 - Jenkins

代理后面的 TFS 2015 Flowdock 服务 Hook

powershell - 无法确定工作区

powershell - 使用 PowerShell 将文件从 tfs 版本控制复制到目录

powershell - TFS 构建 : `Microsoft.TeamFoundation.PowerShell' is not installed on this computer