четверг, 28 января 2016 г.

Получить задания TfsAgent'a через PowerShell

Необходимо получить все неудачно выполненные ($_.Result -eq "Failed") задания с именем 'LabManager VMM Server Background Synchronization Job'  ( [Guid[]] @('1039066b-8187-4831-bcb5-cfc981d98140') )за последний час ($time_period = [system.datetime]::Now.AddMinutes(-60)).

Скрипт:

#Load TFS PowerShell Snap-in
if ((Get-PSSnapIn -Name Microsoft.TeamFoundation.PowerShell -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin Microsoft.TeamFoundation.PowerShell
}

#Load Reference Assemblies
$tfsCollections = @('https://tfs-pc/tfs/Collection1','https://tfs-pc/tfs/Collection2')
#Get Team Project Collection    
$jobService = $teamProjectCollection.GetService([type]"Microsoft.TeamFoundation.Framework.Client.ITeamFoundationJobService")    

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


# period in min
$time_period = [system.datetime]::Now.AddMinutes(-60) 

foreach($tfsCollectionUrl in $tfsCollections)
{
    $teamProjectCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsCollectionUrl)

   
    $jobs = $jobService.QueryJobHistory([Guid[]] @('1039066b-8187-4831-bcb5-cfc981d98140')) | ?{ $_.Result -eq "Failed" } | select * | where-object { $_.ExecutionStartTime -ge $time_period }

if ($jobs.Count -gt 1)
    {    
        foreach($i in $jobs)
        {
            if($i.ResultMessage.Contains($ErrorNum))
            {
                Write-Host 'AgentId: '$i.AgentId
                Write-Host 'ExecutionStartTime: '$i.ExecutionStartTime
                Write-Host 'EndTime: '$i.EndTime
                Write-Host 'HistoryId: '$i.HistoryId
                Write-Host 'JobId: '$i.JobId
                Write-Host 'JobSource: '$i.JobSource
                Write-Host 'QueueTime: '$i.QueueTime
                Write-Host 'Result: '$i.Result
                Write-Host 'ResultMessage: '$i.ResultMessage
                Write-Host '-----'
       
            }
        }
    }
}


Просмотреть JobID для определённой Job можно так:
$tfsCollectionUrl = 'https://tfs-pc/tfs/Collection1'
$teamProjectCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsCollectionUrl)
$jobService = $teamProjectCollection.GetService([type]"Microsoft.TeamFoundation.Framework.Client.ITeamFoundationJobService")
$jobname = 'LabManager VMM Server Background Synchronization Job'
$jobService.QueryJobs() | sort Name | select * | where-object { $_.Name -eq $jobname }