The Kirkland Coder: May 2012

Wednesday, May 23, 2012

I have too much, Temporal Time on my hands...

Recently I had to write some FIM test automation against some temporal sets. So I needed to be able to run the 'FIM_TemporalEventsJob' in SQL from PowerShell. This would cache my new test users "Date/Time" stamp for the expiration of their group membership. Then when I changed their time stamp the temporal set would fire off the correct MPR's and FIMagic would take place. So to save code repeating I cobbled together information and wrote the following function.
Here is hoping you find it as handy as I did to get work done.

function Invoke-FimTemporal
{
<# 
.SYNOPSIS 
This function will start the 'FIM_TemporalEventsJob' SQL Agent Job. 
  
.DESCRIPTION 
This function will start the 'FIM_TemporalEventsJob' SQL Agent Job
and then wait for the job to finish and then return status.
#>
    param
    (
        [string]
        $server = "MYFIMSERVER"
    )

    ###--------------------------------------------------------------
    ### Verify that SQL agent is running or exit.
    ###--------------------------------------------------------------
    $CheckSqlAgent = Get-Service "SQLSERVERAGENT"
    if ($CheckSqlAgent.Status -ne "Running")
    {
        throw "SQL Server Agent is not running. This script can not continue."
    }
    
    ###--------------------------------------------------------------
    ### Start the FIM_TemporalEventsJob SQL Agent Job.
    ###--------------------------------------------------------------
    [void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")
    [void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
    $SqlServer = new-object ("Microsoft.SqlServer.Management.Smo.Server") $server
    $jobsrv = $SqlServer.JobServer
    $FimTemporalJob = $jobsrv.Jobs | where {$_.name -like "FIM_TemporalEventsJob"}
    $LastRun = $FimTemporalJob.LastRunDate
    Write-Verbose ("Last run was [{0}]." -f $LastRun)
    Write-Verbose "Starting the FIM_TemporalEventsJob."
    $FimTemporalJob.Start()

    ###--------------------------------------------------------------
    ### Wait for the FIM_TemporalEventsJob SQL Agent Job to complete.
    ###--------------------------------------------------------------
    Write-Verbose ("Waiting for the FIM_TemporalEventsJob to complete. Started [{0}]." -f (get-date))
    do {
        Start-Sleep -Seconds 10
        $FimTemporalJob.Refresh()
    }
    while ($LastRun -eq $FimTemporalJob.LastRunDate)
    Write-Verbose ("FIM_TemporalEventsJob completed at [{0}]." -f (get-date))
    Write-Verbose ("FIM_TemporalEventsJob completed with a status of [{0}]." -f $FimTemporalJob.LastRunOutcome)
    Write-Output $FimTemporalJob.LastRunOutcome
}