functionpowershellbitlocker

Verify a function in PowerShell has run succesfully


I'm writing a script to backup existing bit locker keys to the associated device in Azure AD, I've created a function which goes through the bit locker enabled volumes and backs up the key to Azure however would like to know how I can check that the function has completed successfully without any errors. Here is my code. I've added a try and catch into the function to catch any errors in the function itself however how can I check that the Function has completed succesfully - currently I have an IF statement checking that the last command has run "$? - is this correct or how can I verify please?

    function Invoke-BackupBDEKeys {

        ##Get all current Bit Locker volumes - this will ensure keys are backed up for devices which may have additional data drives
        $BitLockerVolumes = Get-BitLockerVolume | select-object MountPoint
        foreach ($BDEMountPoint in $BitLockerVolumes.mountpoint) {

            try {
            #Get key protectors for each of the BDE mount points on the device
            $BDEKeyProtector = Get-BitLockerVolume -MountPoint $BDEMountPoint | select-object -ExpandProperty keyprotector
            #Get the Recovery Password protector - this will be what is backed up to AAD and used to recover access to the drive if needed
            $KeyId = $BDEKeyProtector | Where-Object {$_.KeyProtectorType -eq 'RecoveryPassword'}
            #Backup the recovery password to the device in AAD
            BackupToAAD-BitLockerKeyProtector -MountPoint $BDEMountPoint -KeyProtectorId $KeyId.KeyProtectorId
            }
             catch {
                 Write-Host "An error has occured" $Error[0] 
            }
        }
    }     

#Run function
    Invoke-BackupBDEKeys

if ($? -eq $true) {

    $ErrorActionPreference = "Continue"
    #No errors ocurred running the last command - reg key can be set as keys have been backed up succesfully
    $RegKeyPath = 'custom path'
    $Name = 'custom name'
    New-ItemProperty -Path $RegKeyPath -Name $Name -Value 1 -Force
    Exit
}
 else {
    Write-Host "The backup of BDE keys were not succesful"
    #Exit
}

Solution

  • Here's the outline of this approach:

    function Invoke-BackupBDEKeys {
      # Make the function an *advanced* function, to enable
      # support for -ErrorVariable (and -ErrorAction)
      [CmdletBinding()]
      param()
    
      # ...
      foreach ($BDEMountPoint in $BitLockerVolumes.mountpoint) {
    
          # ... Statements that may cause errors.
          # If you need to short-circuit a loop iteration immediately
          # after an error occurred, check each statement's return value; e.g.:
          #      if (-not $BDEKeyProtector) { continue }
      }
    }     
    
    # Call the function and collect any
    # non-terminating errors in variable $errs.
    # IMPORTANT: Pass the variable name *without the $*.
    Invoke-BackupBDEKeys -ErrorAction SilentlyContinue -ErrorVariable errs
    
    # If $errs is an empty collection, no errors occurred.
    if (-not $errs) {
    
      "No errors occurred"
      # ... 
    }
    else {
      "At least one error occurred during the backup of BDE keys:`n$errs"
      # ...
    }
    

    Here's a minimal example, which uses a script block in lieu of a function:

    & {
      [CmdletBinding()] param() Get-Item NoSuchFile 
    } -ErrorVariable errs -ErrorAction SilentlyContinue
    "Errors collected:`n$errs"
    

    Output:

    Errors collected:
    Cannot find path 'C:\Users\jdoe\NoSuchFile' because it does not exist.