Loading the SCOM PowerShell Module, For Real This Time!

This is just a quick post and reference for how I have come to load the SCOM PowerShell module for scripts that requiring SCOM cmdlets. It evolved from several examples I borrowed (thank you to those sources which I've since lost), combined with some real world experiences (such as running inside a SCOM rule / PowerShell Workspace API, running from Orchestrator, running from a scheduled task, running from a machine with the console and PS module install but not a MS), and is now:

 $OMCmdletsTest = (Get-Module|% {$_.Name}) -Join ' '
If (!$OMCmdletsTest.Contains('OperationsManager')) {
    $ModuleFound = $false
    $SetupKeys = @('HKLM:\Software\Microsoft\Microsoft Operations Manager\3.0\Setup',       
        'HKLM:\SOFTWARE\Microsoft\System Center Operations Manager\12\Setup')
    foreach($setupKey in $SetupKeys) {
        If ((Test-Path $setupKey) -and ($ModuleFound -eq $false)) {
            $setupKey = Get-Item -Path $setupKey           
            $installDirectory = $setupKey.GetValue('InstallDirectory')
            $psmPath = $installdirectory + '\Powershell\OperationsManager\OperationsManager.psm1'
            If (Test-Path $psmPath) {
                $ModuleFound = $true
            }
        }
    }
    If ($ModuleFound) {
        Import-Module $psmPath
    } else {
        Import-Module OperationsManager
    }
}