Recently there has been several requests for the TFS (Team Foundation Server, a.k.a VSTF - Visual Studio Team Foundation) Integration Pack on the Opalis Discussion Alias.  Some of them may already know that we do have such IP available as a prototype.  However, it is for internal use only and unavailable for general public before being productized.  On the other hand, most if not all functionalities of TFS client object model can be easily accessed using PowerShell script.  Therefore, if anyone needs to automate the TFS related scenarios without using TFS IP, I'd like to demonstrate how to do that using PowerShell.

 

Load TFS assemblies

 

The first thing is to load .NET assemblies of TFS client object model.  Without this nothing will work.  Here is the list of assemblies:

 

  • Microsoft.TeamFoundation.Client: must load this first.
  • Microsoft.TeamFoundation.WorkItemTracking.Client: for work item tracking scenarios like open/close bug, query work items, etc.
  • Microsoft.TeamFoundation.VersionControl.Client: for version control with TFS source code repository.
  • Microsoft.TeamFoundation.Build.Client: for team foundation build tasks including query build definitions, request new build, retrieve in-progress build details, etc.
  • Microsoft.TeamFoundation.Server.ICommonStructureService
  • Microsoft.TeamFoundation.Server.IGroupSecurityService

 

Suppose we want to do both work item tracking and build:

 

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.WorkItemTracking.Client")

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Build.Client")

 

If any command fails, check if TFS assemblies are in the Global Assembly Cache (GAC).  If not in GAC, install Team Explorer or copy those assemblies from another machine with Visual Studio 2010 installed at the directory %ProgramFiles (x86)%\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0.

 

Connect to TFS server

 

Suppose the TFS server URL is http://scxtfs2:8080/tfs, the following command connects to the sever and returns the Team Project Collection:

 

$teamProjectCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection("http://scxtfs2:8080/tfs")

 

Read MSDN doc http://msdn.microsoft.com/en-us/library/ff735851.aspx for more technical details.

 

Once we have the team project collection, we can use GetService method (http://msdn.microsoft.com/en-us/library/ff735148.aspx) to get a request service including work item tracking or build or version control.

 

Get and create a work item

 

Firstly get a instance of WorkItemStore as work item tracking service,

 

$ws = $teamProjectCollection.GetService([type]"Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore")

 

After that we can use method GetWorkItem (http://msdn.microsoft.com/en-us/library/bb140391.aspx) to get a work item with the specified ID:

 

PS C:\scxtfs\zzSandbox\zhyao\script\tfs> $ws.GetWorkItem(36474)

 

 

Id                  : 36474

TemporaryId         : 36474

Uri                 : vstfs:///WorkItemTracking/WorkItem/36474

Revision            : 3

Revisions           : {Microsoft.TeamFoundation.WorkItemTracking.Client.Revision, Microsoft.TeamFoundation.WorkItemTrac

                      king.Client.Revision, Microsoft.TeamFoundation.WorkItemTracking.Client.Revision}

Attachments         : {test.psq, test.txt}

WorkItemLinks       : {}

Links               : {}

WorkItemLinkHistory : {}

Store               : Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore

Title               : Test Bug From Opalis

State               : Active

Reason              : New

Rev                 : 3

Description         :

History             :

ChangedBy           : Zhenhua Yao

RevisedDate         : 1/1/9999 12:00:00 AM

ChangedDate         : 5/13/2011 4:03:21 PM

CreatedDate         : 3/7/2011 3:57:48 PM

CreatedBy           : SCX Service Account

NodeName            : zzSandbox

AreaPath            : zzSandbox

AreaId              : 271

IterationPath       : zzSandbox

IterationId         : 271

ExternalLinkCount   : 0

HyperLinkCount      : 0

AttachedFileCount   : 2

RelatedLinkCount    : 0

IsOpen              : True

IsPartialOpen       : False

IsReadOnly          : False

IsReadOnlyOpen      : False

IsNew               : False

Fields              : {Title, State, Rev, Changed By...}

Project             : Microsoft.TeamFoundation.WorkItemTracking.Client.Project

Type                : Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemType

IsDirty             : False

DisplayForm         : <FORM><Layout><Group><Column PercentWidth="100"><Control FieldName="System.Title" Type="FieldCont

 

To create a new work item, we need to get the team project by:

 

$proj = $ws.Projects["zzSandbox"]

 

We can check all types of work items defined in this team project by:

 

PS C:\scxtfs\zzSandbox\zhyao\script\tfs> $proj.WorkItemTypes | ft

 

Name                Project             DisplayForm         FieldDefinitions    Description         Store

----                -------             -----------         ----------------    -----------         -----

Bug                 Microsoft.TeamFo... <FORM><Layout><G... {Title, State, R... Describes a dive... Microsoft.TeamFo...

Task                Microsoft.TeamFo... <FORM><Layout><G... {Title, State, R... Includes informa... Microsoft.TeamFo...

Quality of Servi... Microsoft.TeamFo... <FORM><!-- Guide... {Title, State, R... Includes informa... Microsoft.TeamFo...

Scenario            Microsoft.TeamFo... <FORM><!-- Guide... {Title, State, R... Includes informa... Microsoft.TeamFo...

Risk                Microsoft.TeamFo... <FORM><!-- Guide... {Title, State, R... A risk is any pr... Microsoft.TeamFo...

Code Review Resp... Microsoft.TeamFo... <FORM><Layout><G... {Title, State, R... Includes informa... Microsoft.TeamFo...

Backlog Item        Microsoft.TeamFo... <FORM><Layout><G... {Title, State, R... Includes informa... Microsoft.TeamFo...

Test Case           Microsoft.TeamFo... <FORM><Layout><G... {Title, State, R... Server-side data... Microsoft.TeamFo...

Shared Steps        Microsoft.TeamFo... <FORM><Layout><G... {Title, State, R... Server-side data... Microsoft.TeamFo...

 

Suppose we want to create a bug:

 

$bug=$proj.WorkItemTypes["Bug"]

$workitem = $bug.NewWorkItem()

 

Then we can change the properties of $workitem and finally save it by:

 

$workitem.Save()

 

For tons of other things we can do, read MSDN doc: http://msdn.microsoft.com/en-us/library/bb141853.aspx

 

Team Build

 

Firstly get a IBuildServer service:

 

$bs = $teamProjectCollection.GetService([type]"Microsoft.TeamFoundation.Build.Client.IBuildServer")

 

Then we can use methods in IBuildServer http://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.build.client.ibuildserver.aspx to do various tasks.  For instance get a build definition:

 

PS C:\scxtfs\zzSandbox\zhyao\script\tfs> $bs.GetBuildDefinition("SC_Orchestration", "SCOMain")

 

 

BuildServer                      : Microsoft.TeamFoundation.Build.Client.BuildServer

BuildController                  : BuildController instance 40736959

 

TFS Integration Pack

 

As we see, by reading MSDN docs PowerShell can do many tasks with TFS client object model.  This requires you have a little bit knowledge of TFS and programming.  For internal people, you can just use TFS integration pack without writing a PowerShell script.  Here is the list of activities:

 

  • Work Item Tracking
    • Get Work Item
    • Query Work Items
    • Set Work Item
    • New Work Item
    • Monitor Work Items Query
  • Version control
    • List Version Control Items
    • Download File
    • Update Workspace
    • Check in
    • Check out
    • Get Changeset
  • Team Build
    • Get Build Definitions
    • Get Build Details
    • Request Build
    • Set Build Details
    • Monitor Build

 

Again, other than two monitor activities, everything can be done in PowerShell in a straightforward way.  It just a matter of tinkering with some lines of code.   If you need anything else, please don't hesitate to let me know and I will see how to make it work, either by PowerShell or new activities.