Tuesday, December 11, 2018

Clean up unused TFS Work Item Fields

Here with another script for TFS! This time it's for cleanup. Occasionally we find ourselves with unused work item fields in TFS, either after projects get deleted, when fields become obsolete and are removed from WITs, or when you made a typo and have to create a new field. I made a simple Powershell script to find and delete all unused work item fields in your TFS collection. The entire script is as follows:


DeleteUnusedWorkItemFields.ps1

#location of WitdAdmin.exe
cd "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer"

#input your collection URL here
$collectionURL = "https://www.fabrikam.con:8080/tfs/collectionA"

#save unused fields output to a variable/array
$fieldsToDelete = .\witadmin listfields /collection:$collectionURL /unused

#listfields command nearly outputs to a StringData type; just need to replace colons with equal signs. then convert from StringData to PowerShell format
$powershellFieldsToDelete = $fieldsToDelete -replace ":", "=" | ConvertFrom-StringData

#Show me all of the unused fields; stop after this Output if you do not wish to delete them yet
Write-Output $powershellFieldsToDelete."Field"

#loop through each field in the array with delete command
ForEach ($unusedField IN $powershellFieldsToDelete."Field") {
    .\witadmin deletefield /collection:$collectionURL /noprompt /n:$unusedField
    Write-Output "Deleted unused field: $unusedField"
}

Write-Output "All unused fields in this collection have been deleted."

Hope this helps somebody!