Tuesday, January 8, 2013

PowerShell CmdLet to Get the Latest TFS Changeset Number

Sometimes, as a part of a scripted activity (e.g. packaging) you need to determine the latest TFS Changeset number / revision of your working copy. The following handy PowerShell script does just this, and it was just nuanced enough to figure out how to do it that I thought I'd share it here. For the really interested, the two nuances are:
  • You have to use the history command with the recurse option. If you use history without recurse, or if you use the info command, it only interrogates a specific folder or file's data, and not the checkout, meaning you won't get the latest revision for the entire working copy.
  • You have to use the /noprompt option to cause the history to be outputted to the console window instead of viewing the information in a dialog box. The option is not appropriately described and command line tools shouldn't open dialog boxes, but that is the situation here.
This is the script:
param(
    $sourcePath = "."
)

[string]$rawTfsOutput = tf history . /noprompt /recursive /stopafter:1

if ($LastExitCode -ne 0)
{
    throw "Get-TfsChangeset.ps1: Stopping due to TFS error. 
           See console output. Command executed was: 'tf
           history . /noprompt /recursive /stopafter:1'"
}

return ($rawTfsOutput | select-string "\d+").matches[0].Value

3 comments:

Anonymous said...

thank you for the post.
Running this command from powershell window gives me this error:
The term 'tf' is not recognized as the name of a cmdlet, function, script file or operable programe.

Miles said...

You need to add the TFS executable to your system path. Or you can edit the PowerShell script to call TF.exe using the fully qualified path.

For me it is C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE

Anonymous said...

should be:

param(
$sourcePath = "."
)

[string]$rawTfsOutput = tf history $sourcePath /noprompt /recursive /stopafter:1

if ($LastExitCode -ne 0)
{
throw "Get-TfsChangeset.ps1: Stopping due to TFS error.
See console output. Command executed was: 'tf
history . /noprompt /recursive /stopafter:1'"
}

return ($rawTfsOutput | select-string "\d+").matches[0].Value