Friday, July 6, 2012

Powershell Unlock File In TFS Using Visual Studio Command Line Vars

I recently found a situation where someone checked out a file and locked it. That severely impedes my ability to make changes to that file. So I set out to remove the lock using Powershell, while I didn't get the native Powershell functionality I normally like, it still achieves the solution in a usable script.

The solution required that I use tf.exe, not an issue, but it is not in windows path by default. It is available if you use the Visual Studio Command Line, which is just a regular command line which runs a batch file. I thought it might be useful to have the ability to turn Powershell into a Visual Studio Command Line. I found a blog post, Replace Visual Studio Command Prompt with Powershell, that works, but I updated it to work with Visual Studio 2010 and more fully use the power of Powershell.

Set Visual Studio Command Prompt environment variables
#Set Visual Studio Command Prompt environment variables
pushd "c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC";
cmd /c "vcvarsall.bat&set" | ? { $_ -match "^(?<Name>[^=]+)=(?<Value>.+)$" } | % {
    Set-Item -Force -Path "env:\$($matches['Name'])" -Value $matches["Value"];
}
popd;
Write-Host "Visual Studio 2010 Command Prompt variables set." -ForegroundColor Yellow;
Here is my script to unlock a file in TFS even if the workspace doesn't belong to the user or on the users computer. If the command line arguments are not entered, the script will prompt for the arguments. It is a nice pattern that I may make a standard of in my scripts.
param(
  [string] $SourceControlFilePath = $(Read-Host "Source Control File Path"),
  [string] $Workspace = $(Read-Host "Workspace"),
  [string] $Username = $(Read-Host "Username")
)

& .\set-vsvars.ps1;

tf lock /lock:none $SourceControlFilePath /workspace:$Workspace`;$Username

No comments: