Monday, February 2, 2015

PowerShell script to download the source code from TFS as ZIP

param
(
     [Parameter(Mandatory = $true)]
     [string]
     $CodeServerPath,
    
     [Parameter(Mandatory = $true)]
     [string]
     $TeamProject,
    
     [string]
     $TfsUrl = "http://tfsyourserver:8080/tfs/DefaultCollection",
    
     [Parameter(Mandatory = $true)]
     [string]
     $DownloadPath,
    
     [string]
     $ZipFileName,
    
     [Parameter(Mandatory = $true)]
     [string]
     $Username,
    
     [Parameter(Mandatory = $true)]
     [string]
     $Domain,
    
     [Parameter(Mandatory = $true)]
     [string]
     $Password

)

[Reflection.Assembly]::LoadWithPartialName("System") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null

Write-Verbose "Checking whether download directory exists"
if(-not (Test-Path $DownloadPath)){
     throw "$DownloadPath is not a valid directory in the local computer. Provide a location that exists"
}

Write-Verbose "Html encoding the url of the server path"
$CodeServerPath = [System.Web.HttpUtility]::UrlEncode($CodeServerPath)
$Url = $TfsUrl + "/" + $TeamProject + "/_api/_versionControl/itemContentZipped?repositoryId=&path=" + $CodeServerPath
Write-Verbose "Download zip location parsed as $Url"

if([String]::IsNullOrEmpty($ZipFileName)){
     $index = $url.LastIndexOf("%2F"+ 3
     $ZipFileName = $Url.Substring($index, ($Url.Length - $index))
     $ZipFileName = $ZipFileName + ".zip"
}

$ZipFileName = Join-Path $DownloadPath $ZipFileName
Write-Verbose "Download location identified as $ZipFileName"
if(Test-Path $ZipFileName){
     Write-Verbose "Cleaning the $ZipFileName before downloading the new copy"
     Remove-Item $ZipFileName -Confirm:$false
}

$webClient = New-Object System.Net.WebClient
$webClient.Credentials = New-Object System.Net.NetworkCredential($Username$Password,$Domain)
Write-Verbose "Starting the download process"
$webClient.DownloadFile($Url$ZipFileName)
Write-Verbose "Successfully completed download from $Url to $ZipFileName"


No comments: