Hi i am actually new to powershell. I am trying to do ETL database deployment, so i need all the files with in the tfs folder after a given time. I established the connection with the tfs but i am able to download the files but if a file has two check-ins i am getting the file with the previous checkin and not the latest
My code:
$TfsUrl = "http://tfs2013-xxx02.ad.xxx.com:8080/tfs/abcd-xxx243"
# Load TFS assemblies for connecting to the TFS server
Add-Type -Path "E:\Microsoft Visual Studio 14.0\Common7\IDE\TestAgent\Microsoft.TeamFoundation.Client.dll"
Add-Type -Path "E:\Microsoft Visual Studio 14.0\Common7\IDE\TestAgent\Microsoft.TeamFoundation.Common.dll"
Add-Type -Path "E:\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\4qvjm2or.ipa\Microsoft.TeamFoundation.Lab.Client.dll"
Add-Type -Path "E:\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\4qvjm2or.ipa\Microsoft.TeamFoundation.Lab.Common.dll"
Add-Type -Path "E:\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\4qvjm2or.ipa\Microsoft.TeamFoundation.VersionControl.Client.dll"
#Get TFS Instance
$Tfs = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($TfsUrl)
# use the account credentials of the process running the script
try
{
$Tfs.EnsureAuthenticated()
Write-Output "TFS Connection is successful"
}
catch
{
Write-Output "Error trying to connect to tfs server. Check your tfs permissions and path: $_ "
Exit(1)
}
#Write-Message $LogFileName "THIS IS INSIDE Connect-ToTFS"
#Write-Message $LogFileName "TFS IS $Tfs"
$DeploymentFilePath= "$/xxxx/FutureReleases/Database/ReportingETLs"
$TFSInstance = $Tfs.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$LatestVersion = [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest
$RecursionType = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
$DateFrom = "D2016-10-08T01:59"
# Get the From and To date-time in version format to be passed to TFS API
$VersionFrom = $null
$VersionFrom = [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::ParseSingleSpec($DateFrom, "")
$FileHistory = #($TFSInstance.QueryHistory($DeploymentFilePath,$LatestVersion,0,$RecursionType,$null,$null,$null,[int32]::MaxValue, $true ,$true, $true))
#Write-Output "Filehistory is: $FileHistory"
#$ChangeSetCount = $FileHistory.Count
#Write-Output "ChangeSetCount is: $ChangeSetCount"
$TFSGetFullPath = "E:\temp\"
$chArray = #()
$checkin =""
foreach ($history in $FileHistory)
{
foreach ($change in $history.Changes)
{
foreach ($item in $change.item)
{
if($item.CheckinDate -gt $VersionFrom.Date)
{
$chArray += $history.ChangesetId
}
}
}
}
Write-Output "ChangesetArray is: $chArray"
foreach ($ch in $chArray)
{
foreach ($lastdeployedHistory in $FileHistory)
{
if($lastdeployedHistory.ChangesetId -eq $ch)
{
foreach ($workitem in $lastdeployedHistory.Changes)
{
$workitem.Item.DownloadFile([IO.Path]::GetFullPath($TFSGetFullPath) + $workitem.Item.ServerItem.Split('/')[$workitem.Item.ServerItem.Split('/').Length - 1]);
}
}
}
}
This is caused by the object order in $chArray. The changeset in $chArray is ordered from new to old. When you download the file, it is downloading the new file first and then download the older file.
For example, there are two changesets for one file: 111 and 112, with the code Write-Output "ChangesetArray is: $chArray" in your script, you should see the output like: ChangesetArray is: 112 111. When it downloads the file, the file with 112 version is downloaded first and then 111 version which overwrite the latest version.
You can sort the array in $chArray to fix this issue:
Write-Output "ChangesetArray is: $chArray"
$sortcsarray = $chArray | Sort-Object
Write-Output "ChangesetArray is: $sortcsarray"
foreach ($ch in $sortcsarray)
Related
I'm in the process of automating my .Net solution build to be completely in PowerShell. I want to locate MSTest.exe using PowerShell.
I used the following script to locate MSBuild.exe and I hope that I can have something similar to locate MSTest.exe
$msBuildQueryResult = reg.exe query "HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0" /v MSBuildToolsPath
$msBuildQueryResult = $msBuildQueryResult[2]
$msBuildQueryResult = $msBuildQueryResult.Split(" ")
$msBuildLocation = $msBuildQueryResult[12] + "MSBuild.exe"
Any directions ?
The following works with Visual Studio 2010 and higher[1]:
# Get the tools folder location:
# Option A: Target the *highest version installed*:
$vsToolsDir = (
Get-Item env:VS*COMNTOOLS | Sort-Object {[int]($_.Name -replace '[^\d]')}
)[-1].Value
# Option B: Target a *specific version*; e.g., Visual Studio 2010,
# internally known as version 10.0.
# (See https://en.wikipedia.org/wiki/Microsoft_Visual_Studio#History)
$vsToolsDir = $env:VS100COMNTOOLS
# Now locate msbuild.exe in the "IDE" sibling folder.
$msTestExe = Convert-Path -EA Stop (Join-Path $vsToolsDir '..\IDE\MSTest.exe')
The approach is based on this answer and is generalized and adapted to PowerShell.
It is based on system environment variables VS*COMNTOOLS, created by Visual Studio setup, where * represents the VS version number (e.g., 100 for VS 2010).
Re option A: Sort-Object is used to ensure that the most recent Visual Studio installation is targeted, should multiple ones be installed side by side:
The script block used for sorting first extracts only the embedded version number from the variable name ($_.Name -replace '[^\d]'; e.g., 100 from VS100COMNTOOLS) and converts the result to an integer ([int]); [-1] then extracts the last element from the sorted array - i.e., the variable object whose names has the highest embedded version number - and accesses its value (.Value).
The IDE subfolder, in which MSTest.exe is located is a sibling folder of the tools folder that VS*COMNTOOLS points to.
If MSTest.exe is NOT in the expected location, Convert-Path will throw a non-terminating error by default; adding -EA Stop (short for: -ErrorAction Stop) ensures that the script is aborted instead.
[1]
- I've tried up to Visual Studio 2015; do let me know whether or not it works on higher versions.
- Potentially also works with VS 2008.
Perhaps you are wanting something like this?
$regPath = "HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0"
$regValueName = "MSBuildToolsPath"
$msBuildFilename = "MSBUild.exe"
if ( Test-Path $regPath ) {
$toolsPath = (Get-ItemProperty $regPath).$regValueName
if ( $toolsPath ) {
$msBuild = Join-Path $toolsPath $msBuildFilename
if ( -not (Test-Path $msBuild -PathType Leaf) ) {
Write-Error "File not found - '$msBuild'"
}
}
}
# Full path and filename of MSBuild.exe in $msBuild variable
My way of getting mstest path.
GetMSTestPath function is main function which you call and then if first GetMsTestPathFromVswhere function will find something it returns path if not your will be making a long search for mstest.exe. Usually, it takes approximately 10 sec. I know that this is not the best but at least it is something when you struggle to find mstest.exe. Hope it will be helpful for somebody. :)))
function GetMSTestPath
{
function GetTime()
{
$time_now = Get-Date -format "HH:mm:ss"
return $time_now;
}
function GetMsTestPathFromVswhere {
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$path = & $vswhere -latest -prerelease -products * -requires Microsoft.Component.MSBuild -property installationPath
#write-host $path
if ($path) {
$tool = join-path $path 'Common7\IDE\MSTest.exe'
if (test-path $tool) {
return $tool
}
return ""
}
}
function SeachForMsTestPath
{
write-host $(GetTime)
$path = Get-ChildItem C:\ -Filter MSTest.exe -Recurse -ErrorAction Ignore | ? { $_.VersionInfo.FileDescription -eq 'Test Execution Command Line Tool' } | Select -First 1
write-host $(GetTime)
return $path
}
$msTestExePath = GetMsTestPathFromVswhere
if ([string]::IsNullOrEmpty($msTestExePath))
{
$msTestExePath = SeachForMsTestPath;
if ([string]::IsNullOrEmpty($msTestExePath))
{
Write-host "MsTest path is not found. Exiting with error"
Exit -1
}
}
return $msTestExePath;
}
Thanks #Bill_Stewart , I used your comments to write this working function:
function Get-MSTest-Location {
$msTests = #()
$searchResults = Get-ChildItem C:\* -Filter MSTest.exe -Recurse -ErrorAction Ignore
foreach($searchResult in $searchResults) {
try{
if(($searchResult.VersionInfo -ne $null) -and ($searchResult.VersionInfo.FileDescription -eq "Test Execution Command Line Tool"))
{ $msTests = $msTests + $searchResult.FullName }
}
catch{}
}
if($msTests.Length -eq 0)
{return "MSTest not found."}
return $msTests[0]
}
I'm working on a TFS build with a pre-build PowerShell script that (in addition to building my app) automatically checks out a file where we maintain version, increments the build number, then checks the file in.
I have been able to do this, except that I get an error from the script which results in a partially successful build (orange). I need to have a fully successful (green) build.
Here's the check-in line (using TFS Power Tools for VS 2013):
New-TfsChangeset -Item $versionFile -Override "Automated" -Notes "Code Reviewer=tfs" -Comment "Automated"
The error I receive is that the changeset is not associated with a work item, but the -Override should handle that. The funny thing is that it checks in anyway.
Running locally on my machine instead of the build server, I get the same thing, except that I also see a line that says The policies have been overridden. This tells me that the override is working, but it still outputs the error.
I've tried adding -ErrorAction SilentlyContinue, but it has no effect.
I need one of three options:
A way to suppress output of the checkin error,
A way to create a work item and associate it to the checkin, or
Some other third option that will result in a green build.
Any ideas?
Credit goes to Eddie - MSFT for leading me the right direction, but I wanted to consolidate everything here.
WARNING This will check in all pending changes in the workspace.
Creating a new work item (source)
I did modify it quite a bit to support automation. It connects to TFS and generates a new work item.
function New-WorkItem()
{
# These *should* be registered in the GAC.
# The version numbers will likely have to change as new versions of Visual Studio are installed on the server.
Add-Type -Assembly "Microsoft.TeamFoundation.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Add-Type -Assembly "Microsoft.TeamFoundation.WorkItemTracking.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
$server = "http://YOURTFSSERVER:8080/tfs"
$tfs = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer($server)
$type = [Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore]
$store = [Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore] $tfs.GetService($type)
$workItem = New-Object Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem($store.Projects[0].WorkItemTypes[0])
$workItem.Title = "Automated work item"
$workItem
}
Associating the work item and checking in
Slight modifications to the code from the link given by Eddie, we get the following:
function CheckIn()
{
param([Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem] $workItem)
$col = Get-TfsCollection("http://YOURTFSSERVER:8080/tfs/YOURCOLLECTION")
$vcs = Get-TfsVersionControlServer($col)
$ws = $vcs.GetWorkspace([System.IO.Path]::GetDirectoryName($anyPathInWorkspace))
$pc = $ws.GetPendingChanges()
$wici = Get-TfsWorkItemCheckinInfo($workItem)
$changeset = $ws.CheckIn($pc, "Automated check in", $null, $wici, $null)
}
That post doesn't tell you that Get-TfsCollection, Get-TfsVersionControlServer, and Get-TfsWorkItemCheckinInfo aren't defined. I had to find them.
I found the first two on http://nkdagility.com/powershell-tfs-2013-api-1-get-tfscollection-and-tfs-services/. I didn't have to change anything.
function Get-TfsCollection
{
param([string] $CollectionUrl)
if ($CollectionUrl -ne "")
{
#if collection is passed then use it and select all projects
$tfs = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($CollectionUrl)
}
else
{
#if no collection specified, open project picker to select it via gui
$picker = New-Object Microsoft.TeamFoundation.Client.TeamProjectPicker([Microsoft.TeamFoundation.Client.TeamProjectPickerMode]::NoProject, $false)
$dialogResult = $picker.ShowDialog()
if ($dialogResult -ne "OK")
{
#exit
}
$tfs = $picker.SelectedTeamProjectCollection
}
$tfs
}
function Get-TfsVersionControlServer
{
param([Microsoft.TeamFoundation.Client.TfsTeamProjectCollection] $TfsCollection)
$TfsCollection.GetService("Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer")
}
But I couldn't find Get-TfsWorkItemCheckinInfo. The only Google hit was the kinook link from Eddie (and soon probably this answer). Here's what I came up with:
function Get-TfsWorkItemCheckinInfo
{
param([Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem] $workItem)
$wi = New-Object Microsoft.TeamFoundation.VersionControl.Client.WorkItemCheckinInfo($workItem, [Microsoft.TeamFoundation.VersionControl.Client.WorkItemCheckinAction]::Resolve)
$wi
}
Now we can use it
CheckIn (New-WorkItem)
That's it!
You can create a work item from PowerShell by following this article: http://halanstevens.com/blog/powershell-script-to-create-a-workitem/
Quote the code here for reference:
$key = Get-ItemProperty HKLM:\SOFTWARE\Microsoft\VisualStudio\8.0
$dir = [string] (Get-ItemProperty $key.InstallDir)
$dir += "PrivateAssemblies\"
$lib = $dir + "Microsoft.TeamFoundation.WorkItemTracking.Client.dll"
[Reflection.Assembly]::LoadFrom($lib)
$lib = $dir + "Microsoft.TeamFoundation.Client.dll"
[Reflection.Assembly]::LoadFrom($lib)
"Please enter your Team Foundation Server Name:"
$server = [Console]::ReadLine()
$server = $server.Trim()
"Connecting to " + $server + "..."
$tfs = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer($server)
$type = [Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore]
$store = [Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore] $tfs.GetService($type)
$workItem = new-object Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem($store.Projects[0].WorkItemTypes[0])
"Created a new work item of type " + $workItem.Type.Name
$workItem.Title = "Created by Windows PowerShell!"
$workItem.Save()
And then refer to this article to associate the work item to changeset: http://www.kinook.com/Forum/showthread.php?t=4502
In TFS 2015 new build system, did the functionality to automatically add build number to Global List (Build - Project Name) upon build complete removed?
Do I need to write a custom PowerShell task to accomplish this?
Note: XAML builds still add build number to Global List as it did before.
Since many features are still missing in the vNext build system, I've made a PowerShell script that do the Job.
In a near futur, I plan to update this script to support IntegratedIn field filling and to convert the script as a custom build task.
[CmdletBinding(SupportsShouldProcess=$false)]
param()
function Update-GlobalListXml
{
[CmdletBinding(SupportsShouldProcess=$false)]
param(
[xml]$globalListsDoc,
[parameter(Mandatory=$true)][string][ValidateNotNullOrEmpty()]$glName,
[parameter(Mandatory=$true)][string][ValidateNotNullOrEmpty()]$buildNumber
)
Write-Verbose "Checking whether '$glName' exists"
$buildList = $globalListsDoc.GLOBALLISTS.GLOBALLIST | Where-Object { $_.name -eq $glName }
if ($buildList -eq $null)
{
Write-Host "GlobalList '$glName' does not exist and will be created"
$globalLists = $globalListsDoc.GLOBALLISTS
if($globalLists.OuterXml -eq $null)
{
$newDoc = [xml]"<gl:GLOBALLISTS xmlns:gl="""http://schemas.microsoft.com/VisualStudio/2005/workitemtracking/globallists"""></gl:GLOBALLISTS>"
$globalLists = $newDoc.GLOBALLISTS
}
$globalList = $globalLists.OwnerDocument.CreateElement("GLOBALLIST")
$globalList.SetAttribute("name", $glName)
$buildList = $globalLists.AppendChild($globalList)
}
if(($buildList.LISTITEM | where-object { $_.value -eq $buildNumber }) -ne $null)
{
throw "The LISTITEM value: '$buildNumber' already exists in the GLOBALLIST: '$glName'"
}
Write-Host "Adding '$buildNumber' as a new LISTITEM in '$glName'"
$build = $buildList.OwnerDocument.CreateElement("LISTITEM")
$build.SetAttribute("value", $buildNumber)
$buildList.AppendChild($build) | out-null
return $buildList.OwnerDocument
}
function Invoke-GlobalListAPI()
{
[CmdletBinding(SupportsShouldProcess=$false)]
param(
[parameter(Mandatory=$true)][Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore]$wiStore,
[parameter(Mandatory=$true,ParameterSetName="Import")][switch]$import,
[parameter(Mandatory=$true,ParameterSetName="Import")][xml]$globalLists,
[parameter(ParameterSetName="Export")][switch]$export
)
try {
if($import)
{
$wiStore.ImportGlobalLists($globalLists.OuterXml) # Account must be explicitly in the Project Administrator Group
}
if($export)
{
return [xml]$wiStore.ExportGlobalLists()
}
}
catch [Microsoft.TeamFoundation.TeamFoundationServerException] {
Write-Error "An error has occured while exporting or importing GlobalList"
throw $_
}
}
function Get-WorkItemStore()
{
[CmdletBinding(SupportsShouldProcess=$false)]
param(
[parameter(Mandatory=$true)][string][ValidateNotNullOrEmpty()]$tpcUri,
[parameter(Mandatory=$true)][string][ValidateNotNullOrEmpty()]$agentWorker
)
# Loads client API binaries from agent folder
$clientDll = Join-Path $agentWorker "Microsoft.TeamFoundation.Client.dll"
$wiTDll = Join-Path $agentWorker "Microsoft.TeamFoundation.WorkItemTracking.Client.dll"
[System.Reflection.Assembly]::LoadFrom($clientDll) | Write-Verbose
[System.Reflection.Assembly]::LoadFrom($wiTDll) | Write-Verbose
try {
Write-Host "Connecting to $tpcUri"
$tfsTpc = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tpcUri)
return $tfsTpc.GetService([Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore])
}
catch [Microsoft.TeamFoundation.TeamFoundationServerException] {
Write-Error "An error has occured while retrieving WorkItemStore"
throw $_
}
}
function Get-WITDataStore64
{
[CmdletBinding(SupportsShouldProcess=$false)]
param()
if($env:VS140COMNTOOLS -eq $null)
{
throw New-Object System.InvalidOperationException "Visual Studio 2015 must be installed on the build agent" # TODO: Change it by checking agent capabilities
}
$idePath = Join-Path (Split-Path -Parent $env:VS140COMNTOOLS) "IDE"
return Get-ChildItem -Recurse -Path $idePath -Filter "Microsoft.WITDataStore64.dll" | Select-Object -First 1 -ExpandProperty FullName
}
function Update-GlobalList
{
[CmdletBinding(SupportsShouldProcess=$false)]
param()
# Get environment variables
$tpcUri = $env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI
Write-Verbose "Team Project Collection Url: '$tpcUri'"
$teamProjectName = $env:SYSTEM_TEAMPROJECT
Write-Verbose "Team Project: '$teamProjectName'"
$buildNumber = $env:BUILD_BUILDNUMBER
Write-Verbose "Build Number: '$buildNumber'"
$agentHome = $env:AGENT_HOMEDIRECTORY
Write-Verbose "Agent home direrctory: '$agentHome'"
$globalListName = "Builds - $teamProjectName"
Write-Verbose "GlobalList name: '$teamProjectName'"
# Copy 'Microsoft.WITDataStore64.dll' from Visual Studio directory to AgentBin directory if it does not exist
$agentWorker = Join-Path $agentHome "agent\Worker"
$targetPath = Join-Path $agentWorker "Microsoft.WITDataStore64.dll" # Only compatible with x64 process #TODO use constant instead
if(-not (Test-Path $targetPath))
{
$wITDataStore64FilePath = Get-WITDataStore64
Write-Host "Copying $wITDataStore64FilePath to $targetPath"
Copy-Item $wITDataStore64FilePath $targetPath | Write-Verbose
}
$wiStore = Get-WorkItemStore -tpcUri $tpcUri -agentWorker $agentWorker
# Retrive GLOBALLISTS
$xmlDoc = Invoke-GlobalListAPI -export -wiStore $wiStore
$gls2 = Update-GlobalListXml -globalListsDoc $xmlDoc -glName $globalListName -buildNumber $buildNumber
Invoke-GlobalListAPI -import -globalLists $gls2 -wiStore $wiStore
}
Update-GlobalList
Here is the link of the Github repo, feedbacks are welcome => https://github.com/GregoryOtt/UpdateWiBuildNum/blob/master/Update-GlobalList.ps1
[disclaimer - I work on the new build system]
That global list on the workitem is a mechanism that dated back to the original release of TFS. It's one that sort of worked in that day and age (days of nightly builds, pre-CI and CD agility). It's starts to fall apart and doesn't show as proper relationships in TFS. I worked on WIT at that time and we needed a queryable mechanism and that's what we had (blame me :)
So, when we started a new build system, we didn't want to rebuild things and repeat the same mistakes. We're trying to take an agile, incremental approach to a better build system.
In the next sprint (88), we are starting work on proper links between builds and workitems and the WIT team is also doing work to make them more first class. The first thing you'll see is a link on the WIT form and that should hopefully make QU1 as well (at least parts of it).
We realize this does leave a few gaps but we are working to close them (gated and label sources being two others) and hopefully in a better way for a better long term product.
As far as a workaround goes, it should be possible to automate via powershell and our clients but we don't have anything canned for others to use.
I have a PowerShell script that is intended to modify a web config transform as a pre-build event in a build definition. I've gotten it working for the most part, however when it goes to save the updated file I am getting access denied.
Is there a way to give the right access, without opening a window as this is done via the TFS build agent?
Here is the script:
param(
[string]$buildTarget="Dev",
[string]$projectName="SalesTools"
)
$VerbosePreference = "continue"
Write-Verbose "Params: buildTarget = '$($buildTarget)', projectName = '$($projectName)'"
# Make sure path to source code directory is available
if (-not $Env:TF_BUILD_SOURCESDIRECTORY)
{
Write-Error ("TF_BUILD_SOURCESDIRECTORY environment variable is missing.")
exit 1
}
elseif (-not (Test-Path $Env:TF_BUILD_SOURCESDIRECTORY))
{
Write-Error "TF_BUILD_SOURCESDIRECTORY does not exist: $Env:TF_BUILD_SOURCESDIRECTORY"
exit 1
}
Write-Verbose "TF_BUILD_SOURCESDIRECTORY: $Env:TF_BUILD_SOURCESDIRECTORY"
$webConfig = "$($Env:TF_BUILD_SOURCESDIRECTORY)\$($buildTarget)\SalesTools.Web\$($projectName)\web.$($buildTarget).config"
#$webConfig = "$($Env:TF_BUILD_SOURCESDIRECTORY)\$($buildTarget)\SalesTools.Web\ARCTools\web.$($buildTarget).config"
Write-Verbose "File Path: $($webConfig)"
$doc = (gc $webConfig) -as [xml]
$versionNumber = $doc.SelectSingleNode('//appSettings/add[#key="versionNumber"]/#value').'#text'
Write-Verbose "Current Version Number: $($versionNumber)"
if (($versionNumber))
{
$versionInfo = $versionNumber.Split(".")
$versionIteration = $versionInfo[1]
$minorVersion = $versionInfo[2] -as [int]
$minorVersion = $minorVersion + 1
$currentIteration = Get-Iteration
$newVersionInfo = ("v: 1.$($currentIteration).$($minorVersion)")
}
else
{
Write-Error "Could not get version info from config."
exit 1
}
$doc.SelectSingleNode('//appSettings/add[#key="versionNumber"]/#value').'#text' = $newVersionInfo
$doc.Save($webConfig)
Before you read & update the web.config, try to change the "Read-Only" attribute of web.config file. Because by default, all the source files are "Read-Only".
Add this line before "$doc = ....":
attrib -R $webConfig /S
My build server is doing all the steps necessary to build a zip of the new website. I would like to add a step to checkin zipfile to TFS. I have created a ps1 file to perform the checkin. I am running it in ISE so there is no dependency on having TeamCity. Here are the errors that I am seeing.
No matter how I do workspace.GET, it does not get the latest code
from the server.
Even when I change a file on the hard drive it
does not see changes.
Because no changes are detected the zip is
not checked in to TFS.
Here is the code....
#============================================================================
# Method to check in all zip files
#
# Example of WorkingDir passed in
# "D:\TeamCity\buildAgent\work\281509782e84e723\Powershell"
#
# Example of where freshly created zips live
# "D:\TeamCity\buildAgent\work\281509782e84e723\Zips"
#
# this script is based on
# From https://github.com/mmessano/PowerShell/blob/master/TFSCheckIn.ps1
# From http://stackoverflow.com/questions/25917753/check-a-file-into-tfs-using-powershell
# from http://lennartjansson2.wordpress.com/2011/10/13/setting-tfs-vcs-security-with-ps-2/
#
#============================================================================
function StackOverflow {
Param( [Parameter(Mandatory=$true)][string]$WorkingDir )
Write-BuildLog "Inside StackOverflow"
# Get the direcory where new zips where built
$NewZipFiles = $WorkingDir + "\..\Zips\*"
# This is the url to the TFS server + Project collection
$tfsServer = "YourServerAndCollection";
# this is the full path on server where zips live
# You need to start description with $
$tfsServerPath = "$/MyProject/FullPathToDirwithZips"
# Where on local hard drive should files from TFS be placed
$LocalCkoutDir = "D:\MyLocalHDPath"
# Debug print var to verify correct
Write-BuildLog "NewZipFiles => $NewZipFiles"
Write-BuildLog "tfsServer => $tfsServer"
Write-BuildLog "tfsServerPath => $tfsServerPath"
Write-BuildLog "LocalCkoutDir => $LocalCkoutDir"
# Get the TeamCity build number
#$VarName = "BUILD_NUMBER"
#$TeamCityVersionNbr = (get-item env:$VarName).Value
$TeamCityVersionNbr = "MyProject_03_02_81"
Write-BuildLog "Version Nbr $TeamCityVersionNbr"
$CheckInComment = "Check in zips for $BuildNumber"
# Load the assemblies needed for TFS:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Common") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Client") | out-null
#Set up connection to TFS Server and get version control
$tfs = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer($tfsServer)
$versionControlType = [Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]
$versionControlServer = $tfs.GetService($versionControlType)
#check to see if workspace already exists. If it does delete it.
$WorkSpaceNameForCheckIn = "TeamCityWorkspace"
$ThisBoxName = [System.Environment]::MachineName
$test = $versionControlServer.QueryWorkspaces( $WorkSpaceNameForCheckIn, $versionControlServer.AuthenticatedUser, $ThisBoxName )
if ( $test.length -eq 1 )
{
$test[0].Delete()
}
# Generate a workspace
$workspace = $versionControlServer.CreateWorkspace($WorkSpaceNameForCheckIn);
# Map Server path to local path
$workspace.Map($tfsServerPath, $LocalCkoutDir)
# DEBUG: build filename of a zip.
# We will overwrite this file to test the get
$file = "AZipFileThatExists.zip"
$filePath = $LocalCkoutDir + "\" + $file
"hello world" | Out-File $filePath
# I tried the simple get but it does not get
# Get the zip files from the server to local directory
$getstatus = $workspace.Get()
# Csharp way of doing it
#workspace.Map(projectPath, workingDirectory);
# var myItemSpec = new ItemSpec(projectPath, RecursionType.Full);
#GetRequest request = new GetRequest(myItemSpec, VersionSpec.Latest);
#GetStatus status = workspace.Get(request, GetOptions.GetAll | GetOptions.Overwrite); // this line doesn't do anything - no failures or er
# This does not work either
# Powershell checkout the file. Overwrite if file exists. Get even if TFS thinks it is up to date.
$NewItemSpec = New-Object Microsoft.TeamFoundation.VersionControl.Client.ItemSpec ( $tfsServerPath, [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full)
$NewRequest = New-Object Microsoft.TeamFoundation.VersionControl.Client.GetRequest( $NewItemSpec, [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest)
$getstatus = $workspace.Get( $NewRequest, [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::GetAll -bOr [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::Overwrite )
# I have not tested the rest of this since the "get" does not work.
# Mark the files before we refresh them with new zips
$result = $workspace.PendEdit($LocalCkoutDir)
# Copy zips that where built by TeamCity to checkin direcory
Copy-Item $NewZipFiles $LocalCkoutDir -force -recurse
# check if we have some pending changes. If we do checkin changes
$pendings = $workspace.GetPendingChanges();
if($pendings.Count -gt 0){
$result = $workspace.CheckIn($pendings, $CheckInComment);
Write-BuildLog "Changes where checked in";
}
else
{
Write-BuildLog "No changes found";
}
# delete the workspace
$result = $workspace.Delete()
}
#============================================================================
# Write to the build log
#============================================================================
function Write-BuildLog {
param( [Parameter( Mandatory=$true)] $Message
)
write-host $Message
#write-host "##teamcity[message text='" + $Message + "']"
}
$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path
StackOverflow $myDir
use the tf command line
Example for checkin:
cd C:\TFS\Arquitectura
%ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\TF.exe checkin $/Arquitectura/Main /recursive
On Windows x64
"%ProgramFiles(x86)%\Microsoft Visual Studio 10.0\Common7\IDE\TF.exe" checkin $/Arquitectura/Main /recursive
See for more information on the tf commandline: http://msdn.microsoft.com/en-us/library/z51z7zy0(v=VS.90).aspx
Only learning curve about use tf.exe with Powershell. Maybe source code sample is required.
Source: Scripting TFS Command Line for Get Latest Version, Check Out and Check in, programmatically