Tuesday, May 16, 2006

PowerShell Script to Create a WorkItem

Here is the PoSh script I demonstrated at the Atlanta Code Camp for creating a workitem in Team Foundation Server.  It is quite possible that there is a better way to load private assemblies into a PoSh session, but this works.

I did not run the script in my presentation, but pasted sections into the shell, to demonstrate how PoSh allows you to create objects from .NET types and interact with them at the command prompt.

##############################################################################
##
## Create-Workitem.ps1
##
## This script is converted from the C# Work Item Edit sample in the Visual
## Studio 2005 SDK.  I have ignored error checking, so you must have a valid server,
## with at least one team project.
##
## The purpose of this script is to demonstrate how a developer can use the Windows 
## PowerShell to automate tasks using private .NET assemblies.
## 
## In order to run this or any other PowerShell script, you will need to configure
## your PoSh environment to run scripts.  Type Help Set-ExecutionPolicy at a PoSh
## prompt to learn more.
## 
##############################################################################

$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()

++Alan

Comments are closed.