How to query all the environments in a project collection?

MTM provides ability to see all the environments within a team project but there is no view in which you can see all the environments across all the projects. Recently one of our customer mentioned that they want to find out this list programmatically. So in this blog, I am sharing how to do that programmatically.

  • Login to a machine with tfs object model installed. (The tfs object model gets installed with VS, MTM, Tfs, test controller etc)
  • Open notepad, copy paste the following script and change the highlighted variables as per your setup/deployment.
  • Open a power-shell command prompt and run the modified power-shell script.
  • It should show the list of environments. 

Enjoy !!

# Define parameters
$tfsCollectionUrl = New-Object System.URI("
https://myserver/tfs/defaultcollection");

# Load Client Assembly
[Reflection.Assembly]::Load(“Microsoft.TeamFoundation.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”);
[Reflection.Assembly]::Load(“Microsoft.TeamFoundation.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”);
[Reflection.Assembly]::Load(“Microsoft.TeamFoundation.Lab.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”);
[Reflection.Assembly]::Load(“Microsoft.TeamFoundation.Lab.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”);
  

# Connect to tfs
$tfsCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsCollectionUrl);
$labService = $tfsCollection.GetService([Microsoft.TeamFoundation.Lab.Client.LabService]);
$projectService = $tfsCollection.GetService([Microsoft.TeamFoundation.Server.ICommonStructureService]);

# Query all the projects
$projects = $projectService.ListAllProjects();

foreach ($project in $projects)
{
Write-Host Finding environments for project $project.Name

  # Query all environments in this project
$labEnvironmentQuerySpec = New-Object Microsoft.TeamFoundation.Lab.Client.LabEnvironmentQuerySpec;
$labEnvironmentQuerySpec.Disposition = [Microsoft.TeamFoundation.Lab.Client.LabEnvironmentDisposition]::Active;
$labEnvironmentQuerySpec.Project = $project.Name;

  $labEnvironments = $labService.QueryLabEnvironments($labEnvironmentQuerySpec);
foreach ($environment in $labEnvironments)
{
Write-Host $project.Name -> $environment.Name
}
}