04 March 2016

Bitlocker Access is Denied

We recently started getting access is denied when trying to enable bitlocker on our Dell Latitude E7440 models. At first we thought it was a problem with the laptop itself upon the first occurrence of it. We were able to image all other models with no problems. We contacted Dell Premiere support and they concurred. They said that replacing the motherboard should rectify the issue since the issue seemed to be with the TPM chip. Dell replaced the motherboard and this issue persisted. We imaged other E7440 laptops and got the same error. Actually, the access is denied appeared when we went to manually encrypt the laptops. We would get Error code: 0x80070005 when trying to enable bitlocker via the control panel. The build would fail when it tried to enable the bitlocker. When I looked at the event viewer logs, I found the following errors:




At this point, we thought the issue might have been with the build process. We started combing through the build trying to find out what might be wrong. The problem was that all other model systems worked, except for this one. We did the following steps in troubleshooting:

  1. Verified all other model laptops enable bitlocker with no issues
  2. The same task sequence is used on all laptops. The only differences are drivers and bios.
  3. We followed the procedure from this blog that fixed this issue for some users. It did not fix it for our systems.
  4. We verified the BIOS is updated to the latest version
  5. Dell replaced the motherboard and HDD
  6. Windows 7 32-Bit installs and bitlockering on this model had no issues
  7. We verified that the system will bitlocker if we move it to the computers container in active directory
  8. We noticed two problems with the BIOS. The first is that it will not activate the TPM on the first try. When you click activate, apply, and exit, the system reboots, but it goes back to deactivate. It takes two times to activate it. The second problem is pxe booting. When we select to boot from the NIC, the system reboots on the first try. These problems are happening to all of our E7440 laptops.
  9. I laid down a base windows 7 image with no drivers or windows updates. The only driver I installed was the NIC for network connectivity. When I joined it to the domain, it still gave access denied.
  10. I downgraded the BIOS
  11. We disabled the Cisco Anywhere Connect VPN software from being installed during the build. I ran across troubleshooting post for the access is denied where they recommended uninstall any VPN software. This did not fix the issue.
  12. I gave the SELF account full control of the specific computer in active directory with no success
  13. One more suggestion we found that some said worked was upgrading the firmware to the latest version for the HDD. We were not able to get the firmware to upgrade on our flash HDD.
  14. We were able to get systems to bitlocker if we joined the system to a local workgroup, changed the name of the system to one that had never been used before, and then joined the domain.
  15. We were able to get systems to bitlocker if we moved the system in active directory to the computers container where it gets no GPOs.
  16. We also noticed other problems with the E7440. When you go into the BIOS to turn on, clear, and activate the TPM, it does not behave correctly. Once you have completed the clear process, the TPM is automatically put into deactivated mode. You must then reboot the system for it to take effect. Next, you click to activate the TPM, it shows it is activated, but when you reboot and go back into the BIOS, the TPM is showing as deactivated. The activation step must be done twice. The second issue we found was with PXE booting. Sometimes when we hit F12, select Onboard NIC, the system will reboot when it begins the initializing step of the PXE process.
By this time, we had spent almost 70 hours troubleshooting this, including Dell support trying to help. Finally I decided to find out exactly what the Bitlocker GPO changed on system. I found it pushed two registry keys: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\FVE and HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\TPM. I deleted those registry keys out and then tried to enable bitlocker through the control panel. It worked. I knew at this point, it had to be with the system and not the GPO, especially since it worked with all other systems. The next thing that needed to be done was to make sure the recovery key got to active directory. I ran a GPUPDATE.EXE to force the registry keys back down to the system. I then ran manage-bde -protectors -get c: to get the numerical password ID. Finally, I ran manage-bde -protectors -adbackup c: -id {Numerical ID} to push the key to active directory and it worked! My next step was to make sure this same process would work on other model systems so that we could have a single process to work on all instead of having more than one. It does successfully work on the other models. 

I have written two PowerShell scripts, with the help of PowerShell Studio by Sapien Technologies, that bitlocker the systems. The first script uses BitlockerSAK to make sure the TPM is ready to be used. Once it verifies the TPM is turned on, cleared, and activated, the script deletes the FVE and TPM registry keys. The next step is does is to take ownership of the TPM. To take ownership of the TPM, it needs the BIOS password, which is a mandatory parameter upon the execution of the script. The next step is to enable bitlocker. A group policy update is now necessary to repopulate the registry keys the script deleted earlier. Next, the script gets the Bitlocker ID using the function provided by PowerShell District. This is necessary for the next step that pushes the recovery key to active directory. At this point, the script is finished and the system must be rebooted in order for bitlocker to begin encrypting the drive. 

There is a second script for the actual encryption process. This script is executed as the next task sequence. It first waits for the fvenotify.exe to begin. The script waits 5 minutes for this to begin. If it does not begin within 5 minutes, the script exits with an error code 1. Once the fvenotify.exe is a process, the script waits until it disappears. This is intended to delay a build until the encryption process is completed. 

You can download the scripts from the following links:


BitlockerSystem.ps1
 <#       
      .NOTES  
      ===========================================================================  
       Created with:      SAPIEN Technologies, Inc., PowerShell Studio 2015 v4.2.99  
       Created on:       2/25/2016 4:29 PM  
       Created by:       Mick Pletcher  
       Organization:         
       Filename:        BitlockerSystem.ps1  
      ===========================================================================  
      .DESCRIPTION  
           This script waits for the bitlocker process to begin. If the bitlocker  
           process does not begin within 5 minutes, the script exits with an error  
           code 1. If the process does begin, then the script waits until   
           bitlocker is complete with encrypting the system.  
 #>  
   
   
 #Declare Variables  
 Set-Variable -Name CurrentTime -Scope Local -Force  
 Set-Variable -Name Difference -Scope Local -Force  
 Set-Variable -Name Output1 -Scope Local -Force  
 Set-Variable -Name Output2 -Scope Local -Force  
 Set-Variable -Name Output3 -Scope Local -Force  
 Set-Variable -Name Process -Value $null -Scope Local -Force  
 Set-Variable -Name StartTime -Scope Local -Force  
   
 Clear-Host  
 $StartTime = Get-Date  
 $Output1 = "Waiting for Bitlocker Encryption to begin....."  
 $Output1  
 While ($Process -eq $null) {  
      Start-Sleep -Seconds 5  
      $Process = Get-Process -Name fvenotify -ErrorAction SilentlyContinue  
      $CurrentTime = Get-Date  
      $Difference = (New-TimeSpan -Start $StartTime -End $CurrentTime).minutes  
      If ($Difference -eq 5) {  
           Exit 1  
      }  
 }  
 $Output1 = $Output1 + "Completed"  
 Clear-Host  
 $Output1  
 $Output2 = "Bitlockering System....."  
 $Output2  
 while ($Process -ne $null) {  
      $Process = $null  
      $Process = Get-Process -Name fvenotify -ErrorAction SilentlyContinue  
      $Output3 = manage-bde -status $env:HOMEDRIVE  
      Clear-Host  
      $Output1  
      $Output2  
      Write-Host  
      $Output3[9].TRIM()  
      Start-Sleep -Seconds 60  
 }  
 Write-Host "Complete" -ForegroundColor Yellow  
   
 #Cleanup Variables  
 Remove-Variable -Name CurrentTime -Scope Local -Force  
 Remove-Variable -Name Difference -Scope Local -Force  
 Remove-Variable -Name Output1 -Scope Local -Force  
 Remove-Variable -Name Output2 -Scope Local -Force  
 Remove-Variable -Name Output3 -Scope Local -Force  
 Remove-Variable -Name Process -Scope Local -Force  
 Remove-Variable -Name StartTime -Scope Local -Force  
   


EnableBitlocker.ps1
 <#  
      ===========================================================================  
      Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2015 v4.2.99  
      Created on:       2/26/2016 2:02 PM  
      Created by:       Mick Pletcher  
      Organization:  
      Filename:         EnableBitlocker.ps1  
      ===========================================================================  
      .DESCRIPTION  
           This script will enable bitlocker on a system. It first tests the   
           system to make sure the TPM is ready for bitlocker. If it passes  
           the test, then it does the following:  
           1) Deletes the FVE and TPM registry keys  
           2) Takes ownership of the TPM  
           3) Enables bitlocker  
           4) Performs a gpupdate  
           5) Gets the bitlocker recovery key ID  
           6) Backs up the recovery key to active directory  
 #>  
   
 param  
 (  
      [Parameter(Mandatory = $true)][string]$BIOSPassword  
 )  
   
 Function BitLockerSAK {  
 <#  
 .SYNOPSIS  
      Get and set Bitlocker related information.  
     
 .DESCRIPTION  
      Based on WMI classes, this function can achiev the following tasks :  
   
   --TPM operations---  
     -TPM activation state.  
     -If the TPM is enabled or not.  
     -If a TPM OwnerShip is Allowed.  
     -If the TPM is currently owned.  
     -The possibility to take the ownerShip  
   
   --Encryption possibilities ---  
     - Retrieves the current encryption method.  
     - Get the current protection status.  
     - The current protection state.  
     - The possibility to encrypt a Drive.  
     - The possibility to Resume an encryption that has been paused.  
     - Possibility to return the current protector ID's.  
     - Possibility to return the current protector type(s).  
     - Retrieves the Volume key protector Passwords  
     
   
 .PARAMETER isTPMActivated  
      Returns activation state of the TPM:  
   Returns true if activated and false if not.  
   
 .PARAMETER isTPMEnabled  
      Returns the enabled state of the TPM:  
   Returns true if activated and false if not.  
   
 .PARAMETER IsTPMOwnerShipAllowed  
   Returns if the TPM ownership is allowed.  
   Returns true if allowed, false if not.  
   
 .PARAMETER ResumeEncryption  
   Will resume an paused encryption.  
   
 .PARAMETER GetEncryptionState  
   Returns the current encurrent state in an object as wolled :   
   
 .PARAMETER GetProtectionStatus  
   Returns the current protection status. It will return "Protected" if the drive is 100% encrypted, and "Unprotected" if anything else then "100% encrypted".  
   
 .PARAMETER Encrypt  
   Will encrypt a drive.  
   
 .PARAMETER TakeTPMOwnerShip  
   Returns true if allowed, false if not  
   
 .PARAMETER pin  
   Is needed in order to take the ownership and to encrypt the drive.  
   
 .PARAMETER IsTPMOwned  
   Returns true if owned, false if not  
   
 .PARAMETER GetKeyProtectorIds  
   Returns all the protector id's available on the machine.  
   
 .PARAMETER GetKeyProtectorType  
   Returns the type of protector that is currently in use.  
   
 .PARAMETER GetEncryptionMethod  
   REturns the current encryption method that is in use.  
   
 .PARAMETER GetKeyProtectorNumericalPassword  
   Returns a given numerical password based on a Protector ID value.  
   The ProtectorID value is mandatory, and must be passed using the parameter VolumeKeyProtectorID.   
   
 .PARAMETER VolumeKeyProtectorID  
   This parameter will work only in conjunction with GetKeyProtectorNumericalPassword switch.  
   It must contain the ProtectorID from which the desired Numerical Password will be returned.  
             
 .PARAMETER GetKeyProtectorTypeAndID  
   The GetKeyProtectorTypeAndID switch will return all the existing key protector ID's and their type of the Keys existing on the machine.  
   
   
 .PARAMETER Whatif  
      Permits to launch this script in "draft" mode. This means it will only show the results without really making generating the files.  
   
 .PARAMETER Verbose  
      Allow to run the script in verbose mode for debbuging purposes.  
     
 .EXAMPLE  
   
 BitLockerSAK  
   
 Returns the current status of the drives.  
   
 IsTPMOwned         : True  
 EncryptionMethod      : AES_128  
 IsTPMOwnerShipAllowed    : True  
 IsTPMActivated       : True  
 IsTPMEnabled        : True  
 CurrentEncryptionPercentage : 100  
 EncryptionState       : FullyEncrypted  
 ProtectorIds        : {{FFC19381-6E75-4D1E-94E9-D6E0D3E681FA}, {65AF5A93-9846-47AC-B3B1-D8DE6F06B780}}  
 KeyProtectorType      : {Numerical password, Trusted Platform Module (TPM)}  
   
 .EXAMPLE  
    
 BitLockerSAK -GetProtectionStatus  
   
 Returns the current protection status : Protected or unprotected  
   
 .EXAMPLE  
    
 BitLockerSAK -GetEncryptionState  
   
 CurrentEncryptionProgress is express in percentage.   
   
 CurrentEncryptionProgress EncryptionState                                             
 ------------------------- ---------------                                             
            100 FullyEncrypted  
     
 .EXAMPLE  
   
 Get all the key protectors and their respective ID's and protector types from the current machine.  
   
 BitLockerSAK -GetKeyProtectorTypeAndID  
   
 KeyProtectorID                                           KeyProtectorType                                            
 --------------                                           ----------------                                            
 {AB1535D4-ECB3-49D6-8AB1-E334A4F60579}                               Numerical password                                           
 {B1BDF8CD-55F2-4532-A93F-4B1AF4F22B55}                               Trusted Platform Module (TPM)  
   
 .EXAMPLE  
   
 Get the numerical password from a specefic Key using the ID.  
   
 BitLockerSAK -GetKeyProtectorNumericalPassword -VolumeKeyProtectorID "{AB1535D4-ECB3-49D6-8AB1-E334A4F60579}"  
   
 Message                              KeyProtectorNumericalPassword                   VolumeKeyProtectorID                         
 -------                              -----------------------------                   --------------------                         
 The method was successful.                     242968-693319-295251-477840-704451-214225-550055-383229      {AB1535D4-ECB3-49D6-8AB1-E334A4F60579}   
   
 .NOTES  
      -Author: Stephane van Gulick  
      -Email :   
      -CreationDate: 13-01-2014  
      -LastModifiedDate: 11.06.2015  
      -Version: 1.5  
      -History:  
   #0.1 : Created function  
   #1.1 : 20140901 Added GetProtectorIds  
   #1.2 : 20140909 Rewrote function  
           Added GetKeyprotectorType  
           Added EncryptionMethod  
      #1.3 : 20141003 Added TPM conditions.  
   #1.4 : Possiblity to select drive letter, added RemoveKeyProtectors.  
     --> GetKeyProtectorTypeAndID,  
     --> DeleteKeyProtectors,  
     --> ProtectorIDs,  
     --> DeleteKeyProtector,  
     --> PauseEncryption,  
     --> PauseDecryption,  
     --> Decrytp  
   #1.4.1 --> updated help with GetKeyPRotectedID instead of KeyProtectedID parameter  
   #1.5 Added GetKeyProtectorNumericalPassword and VolumeKeyProtectorID parameters.  
   
 .LINK  
   www.PowerShellDistrict.com  
   
 #>  
      [cmdletBinding()]  
      Param (  
           [Switch]$IsTPMActivated,  
           [Switch]$IsTPMEnabled,  
           [Switch]$IsTPMOwnerShipAllowed,  
           [Switch]$ResumeEncryption,  
           [Switch]$GetEncryptionState,  
           [Switch]$GetProtectionStatus,  
           [switch]$Encrypt,  
           [Parameter(ParameterSetName = 'OwnerShip')][switch]$TakeTPMOwnerShip,  
           [Parameter(ParameterSetName = 'OwnerShip')][int]$pin,  
           [switch]$IsTPMOwned,  
           [Switch]$GetKeyProtectorIds,  
           [switch]$GetEncryptionMethod,  
           [ValidateScript({  
                if ($_ -match '^[A-Z]{1}[:]') {  
                     return $true  
                } else {  
                     Write-Warning 'The drive letter parameter has to respect the following case: DriverLetter+Colomn EG: --> C: --> D: --> E: '  
                     return $false  
                }  
           })][string]$DriveLetter = 'C:',  
           [switch]$GetKeyProtectorTypeAndID,  
           [switch]$DeleteKeyProtectors,  
           #Acceptvaluefrompipelinebyname  
           [String[]]$ProtectorIDs,  
           [switch]$DeleteKeyProtector,  
           [switch]$PauseEncryption,  
           [switch]$PauseDecryption,  
           [switch]$Decrytp,  
           [Parameter(ParameterSetName = 'NumericalPassword')][Switch]$GetKeyProtectorNumericalPassword,  
           [Parameter(ParameterSetName = 'NumericalPassword', Mandatory = $true)][String]$VolumeKeyProtectorID  
             
      )  
      Begin {  
           try {  
                $Tpm = Get-WmiObject -Namespace ROOT\CIMV2\Security\MicrosoftTpm -Class Win32_Tpm -ErrorAction Stop  
           } catch [System.Management.ManagementException]{  
                  
                write-warning 'Could not access the WMI methods. Verify that you run the script with elevated rights and try again.'  
                continue  
                  
                  
           }  
      }  
      Process {  
           ##Add switch to verify if enough place is present on HD (6gig are need, 10 recommended).  
             
             
           switch ($PSBoundParameters.keys) {  
                  
                'IsTPMActivated'{ $return = if ($Tpm) { $tpm.IsActivated().isactivated }; break }  
                'IsTPMEnabled'{ $return = if ($Tpm) { $tpm.IsEnabled().isenabled }; break }  
                'IsTPMOwnerShipAllowed'{ $return = if ($Tpm) { $tpm.IsOwnerShipAllowed().IsOwnerShipAllowed }; break }  
                'IsTPMOwned'{ $return = if ($Tpm) { $Tpm.isowned().isowned }; break }  
                'GetEncryptionState'{  
                     write-verbose "Getting the encryptionstate of drive $($driveletter)"  
                     #http://msdn.microsoft.com/en-us/library/aa376433(VS.85).aspx  
                     #We only want to work on the C: drive.  
                     $EncryptionData = Get-WmiObject -Namespace ROOT\CIMV2\Security\Microsoftvolumeencryption -Class Win32_encryptablevolume -Filter "DriveLetter = '$DriveLetter'"  
                     $protectionState = $EncryptionData.GetConversionStatus()  
                     $CurrentEncryptionProgress = $protectionState.EncryptionPercentage  
                       
                     switch ($ProtectionState.Conversionstatus) {  
                            
                          '0' {  
                                 
                               $Properties = @{ 'EncryptionState' = 'FullyDecrypted'; 'CurrentEncryptionProgress' = $CurrentEncryptionProgress }  
                               $Return = New-Object psobject -Property $Properties  
                                 
                          }  
                            
                          '1' {  
                                 
                               $Properties = @{ 'EncryptionState' = 'FullyEncrypted'; 'CurrentEncryptionProgress' = $CurrentEncryptionProgress }  
                               $Return = New-Object psobject -Property $Properties  
                                 
                          }  
                          '2' {  
                                 
                               $Properties = @{ 'EncryptionState' = 'EncryptionInProgress'; 'CurrentEncryptionProgress' = $CurrentEncryptionProgress }  
                               $Return = New-Object psobject -Property $Properties  
                          }  
                          '3' {  
                                 
                               $Properties = @{ 'EncryptionState' = 'DecryptionInProgress'; 'CurrentEncryptionProgress' = $CurrentEncryptionProgress }  
                               $Return = New-Object psobject -Property $Properties  
                          }  
                          '4' {  
                                 
                               $Properties = @{ 'EncryptionState' = 'EncryptionPaused'; 'CurrentEncryptionProgress' = $CurrentEncryptionProgress }  
                               $Return = New-Object psobject -Property $Properties  
                          }  
                          '5' {  
                                 
                               $Properties = @{ 'EncryptionState' = 'DecryptionPaused'; 'CurrentEncryptionProgress' = $CurrentEncryptionProgress }  
                               $Return = New-Object psobject -Property $Properties  
                          }  
                          default {  
                               write-verbose "Couldn't retrieve an encryption state."  
                               $Properties = @{ 'EncryptionState' = $false; 'CurrentEncryptionProgress' = $false }  
                               $Return = New-Object psobject -Property $Properties  
                          }  
                     }  
                }  
                'ResumeEncryption'{  
                     write-verbose 'Resuming encryption'  
                     $ProtectionState = Get-WmiObject -Namespace ROOT\CIMV2\Security\Microsoftvolumeencryption -Class Win32_encryptablevolume -Filter "DriveLetter = '$DriveLetter'"  
                       
                     $Ret = $protectionState.ResumeConversion()  
                     $ReturnCode = $ret.ReturnValue  
                       
                     switch ($ReturnCode) {  
                            
                          ('0') { $Message = 'The Method Resume Conversion was called succesfully.' }  
                          ('2150694912') { $message = 'The volume is locked' }  
                          default { $message = 'The resume operation failed with an uknowned return code.' }  
                     }  
                       
                     $Properties = @{ 'ReturnCode' = $ReturnCode; 'ErrorMessage' = $message }  
                     $Return = New-Object psobject -Property $Properties  
                } #EndResumeEncryption    
                'GetProtectionStatus'{  
                     #http://msdn.microsoft.com/en-us/library/windows/desktop/aa376448(v=vs.85).aspx  
                     $ProtectionState = Get-WmiObject -Namespace ROOT\CIMV2\Security\Microsoftvolumeencryption -Class Win32_encryptablevolume -Filter "DriveLetter = '$DriveLetter'"  
                     write-verbose 'Gathering BitLocker protection status infos.'  
                       
                     switch ($ProtectionState.GetProtectionStatus().protectionStatus) {  
                            
                          ('0') { $return = 'Unprotected' }  
                          ('1') { $return = 'Protected' }  
                          ('2') { $return = 'Uknowned' }  
                          default { $return = 'NoReturn' }  
                     } #EndSwitch  
                } #EndGetProtection  
                'Encrypt'{  
                     #http://msdn.microsoft.com/en-us/library/windows/desktop/aa376432(v=vs.85).aspx  
                     $ProtectionState = Get-WmiObject -Namespace ROOT\CIMV2\Security\Microsoftvolumeencryption -Class Win32_encryptablevolume -Filter "DriveLetter = '$DriveLetter'"  
                     write-verbose 'Launching drive encryption.'  
                       
                     $ProtectorKey = $protectionState.ProtectKeyWithTPMAndPIN('ProtectKeyWithTPMAndPin', '', $pin)  
                     Start-Sleep -Seconds 3  
                     $NumericalPasswordReturn = $protectionState.ProtectKeyWithNumericalPassword()  
                       
                     $Return = $protectionState.Encrypt()  
                     $returnCode = $return.returnvalue  
                     switch ($ReturnCode) {  
                            
                          ('0') { $message = 'Operation successfully started.' }  
                          ('2147942487') { $message = 'The EncryptionMethod parameter is provided but is not within the known range or does not match the current Group Policy setting.' }  
                          ('2150694958') { $message = 'No encryption key exists for the volume' }  
                          ('2150694957') { $message = 'The provided encryption method does not match that of the partially or fully encrypted volume.' }  
                          ('2150694942') { $message = 'The volume cannot be encrypted because this computer is configured to be part of a server cluster.' }  
                          ('2150694956') { $message = 'No key protectors of the type Numerical Password are specified. The Group Policy requires a backup of recovery information to Active Directory Domain Services' }  
                          default {  
                               $message = 'An unknown status was returned by the Encryption action.'  
                                 
                          }  
                     }  
                       
                     $Properties = @{ 'ReturnCode' = $ReturnCode; 'ErrorMessage' = $message }  
                     $Return = New-Object psobject -Property $Properties  
                }  
                'GetKeyProtectorIds'{  
                     $BitLocker = Get-WmiObject -Namespace 'Root\cimv2\Security\MicrosoftVolumeEncryption' -Class 'Win32_EncryptableVolume' -Filter "DriveLetter = '$DriveLetter'"  
                     $return = $BitLocker.GetKeyProtectors('0').VolumeKeyProtectorID  
                }  
                'GetEncryptionMethod'{  
                     $BitLocker = Get-WmiObject -Namespace 'Root\cimv2\Security\MicrosoftVolumeEncryption' -Class 'Win32_EncryptableVolume' -Filter "DriveLetter = '$DriveLetter'"  
                     $EncryptMethod = $BitLocker.GetEncryptionMethod().encryptionmethod  
                     switch ($EncryptMethod) {  
                          '0'{ $Return = 'None'; break }  
                          '1'{ $Return = 'AES_128_WITH_DIFFUSER'; break }  
                          '2'{ $Return = 'AES_256_WITH_DIFFUSER'; break }  
                          '3'{ $Return = 'AES_128'; break }  
                          '4'{ $Return = 'AES_256'; break }  
                          '5'{ $Return = 'HARDWARE_ENCRYPTION'; break }  
                          default { $Return = 'UNKNOWN'; break }  
                     }  
                       
                }  
                'GetKeyProtectorTypeAndID'{  
                       
                     $BitLocker = Get-WmiObject -Namespace 'Root\cimv2\Security\MicrosoftVolumeEncryption' -Class 'Win32_EncryptableVolume' -Filter "DriveLetter = '$DriveLetter'"  
                     $ProtectorIds = $BitLocker.GetKeyProtectors('0').volumekeyprotectorID  
                       
                     $return = @()  
                       
                     foreach ($ProtectorID in $ProtectorIds) {  
                            
                          $KeyProtectorType = $BitLocker.GetKeyProtectorType($ProtectorID).KeyProtectorType  
                          $keyType = ''  
                          switch ($KeyProtectorType) {  
                                 
                               '0'{ $Keytype = 'Unknown or other protector type'; break }  
                               '1'{ $Keytype = 'Trusted Platform Module (TPM)'; break }  
                               '2'{ $Keytype = 'External key'; break }  
                               '3'{ $Keytype = 'Numerical password'; break }  
                               '4'{ $Keytype = 'TPM And PIN'; break }  
                               '5'{ $Keytype = 'TPM And Startup Key'; break }  
                               '6'{ $Keytype = 'TPM And PIN And Startup Key'; break }  
                               '7'{ $Keytype = 'Public Key'; break }  
                               '8'{ $Keytype = 'Passphrase'; break }  
                               '9'{ $Keytype = 'TPM Certificate'; break }  
                               '10'{ $Keytype = 'CryptoAPI Next Generation (CNG) Protector'; break }  
                                 
                          } #endSwitch  
                            
                          $Properties = @{ 'KeyProtectorID' = $ProtectorID; 'KeyProtectorType' = $Keytype }  
                          $Return += New-Object -TypeName psobject -Property $Properties  
                     } #EndForeach  
                       
                } #EndGetKeyProtectorType  
                'DeleteKeyProtectors'{  
                     $BitLocker = Get-WmiObject -Namespace 'Root\cimv2\Security\MicrosoftVolumeEncryption' -Class 'Win32_EncryptableVolume' -Filter "DriveLetter = '$DriveLetter'"  
                     $Return = $BitLocker.DeleteKeyProtectors()  
                       
                }  
                'TakeTPMOwnerShip'{  
                     $Tpm.takeOwnership()  
                }  
                'DeleteKeyProtector'{  
                       
                     if ($PSBoundParameters.ContainsKey('ProtectorIDs')) {  
                          $Return = @()  
                          $BitLocker = Get-WmiObject -Namespace 'Root\cimv2\Security\MicrosoftVolumeEncryption' -Class 'Win32_EncryptableVolume' -Filter "DriveLetter = '$DriveLetter'"  
                            
                          foreach ($ProtID in $ProtectorIDs) {  
                               $Return += $BitLocker.DeleteKeyProtector($ProtID)  
                          }  
                     } else {  
                          write-warning 'Could not delete the key protector. Missing ProtectorID parameter.'  
                          $Return = 'Could not delete the key protector. Missing ProtectorID parameter.'  
                            
                     }  
                }  
                'PauseEncryption'{  
                     $BitLocker = Get-WmiObject -Namespace 'Root\cimv2\Security\MicrosoftVolumeEncryption' -Class 'Win32_EncryptableVolume' -Filter "DriveLetter = '$DriveLetter'"  
                     $ReturnCode = $BitLocker.PauseConversion()  
                       
                     switch ($ReturnCode.ReturnValue) {  
                          '0'{ $Return = 'Paused sucessfully.'; break }  
                          '2150694912'{ $Return = 'The volume is locked.'; Break }  
                          default { $Return = 'Uknown return code.'; break }  
                     }  
                }  
                'PauseDecryption'{  
                     $BitLocker = Get-WmiObject -Namespace 'Root\cimv2\Security\MicrosoftVolumeEncryption' -Class 'Win32_EncryptableVolume' -Filter "DriveLetter = '$DriveLetter'"  
                     $ReturnCode = $BitLocker.PauseConversion()  
                       
                     switch ($ReturnCode.ReturnValue) {  
                          '0'{ $Return = 'Paused sucessfully.'; break }  
                          '2150694912'{ $Return = 'The volume is locked.'; Break }  
                          default { $Return = 'Uknown return code.'; break }  
                     }  
                }  
                'Decrytp'{  
                     $BitLocker = Get-WmiObject -Namespace 'Root\cimv2\Security\MicrosoftVolumeEncryption' -Class 'Win32_EncryptableVolume' -Filter "DriveLetter = '$DriveLetter'"  
                     $ReturnCode = $BitLocker.Decrypt()  
                       
                     switch ($ReturnCode.ReturnValue) {  
                          '0'{ $Return = 'Uncryption started successfully.'; break }  
                          '2150694912'{ $Return = 'The volume is locked.'; Break }  
                          '2150694953' { $Return = 'This volume cannot be decrypted because keys used to automatically unlock data volumes are available.'; Break }  
                          default { $Return = 'Uknown return code.'; break }  
                     }  
                       
                }  
                'GetKeyProtectorNumericalPassword'{  
                     $BitLocker = Get-WmiObject -Namespace 'Root\cimv2\Security\MicrosoftVolumeEncryption' -Class 'Win32_EncryptableVolume' -Filter "DriveLetter = '$DriveLetter'"  
                     $Return = @()  
                       
                       
                     $KeyProtectorReturn = $BitLocker.GetKeyProtectorNumericalPassword($VolumeKeyProtectorID)  
                       
                     switch ($KeyProtectorReturn.ReturnValue) {  
                          '0' { $msg = 'The method was successful.' }  
                          '2150694912' { $msg = 'The volume is locked.'; Break }  
                          '2147942487' { $msg = "The VolumeKeyProtectorID parameter does not refer to a key protector of the type 'Numerical Password'."; Break }  
                          '2150694920' { $msg = 'BitLocker is not enabled on the volume. Add a key protector to enable BitLocker.'; Break }  
                          default { $msg = "Unknown return value: $($KeyProtectorReturn.ReturnValue)" }  
                     } #EndSwitch  
                       
                     $Properties = @{ 'KeyProtectorNumericalPassword' = $KeyProtectorReturn.NumericalPassword; 'VolumeKeyProtectorID' = $VolumeKeyProtectorID; 'Message' = $msg }  
                     $Return += New-Object -TypeName psobject -Property $Properties  
                       
                       
                }  
           } #endSwitch  
             
             
           if ($PSBoundParameters.Keys.Count -eq 0) {  
                #Returning info on all drives.  
                write-verbose 'Returning bitlocker main status'  
                $Tpm = Get-WmiObject -Namespace ROOT\CIMV2\Security\MicrosoftTpm -Class Win32_Tpm  
                $BitLocker = Get-WmiObject -Namespace 'Root\cimv2\Security\MicrosoftVolumeEncryption' -Class 'Win32_EncryptableVolume' -Filter "DriveLetter = '$DriveLetter'"  
                  
                #If no TPM module is present  
                if ($tpm) {  
                     $TpmActivated = $tpm.IsActivated().isactivated  
                     $TPMEnabled = $tpm.IsEnabled().isenabled  
                     $TPMOwnerShipAllowed = $Tpm.IsOwnershipAllowed().IsOwnerShipAllowed  
                     $TPMOwned = $Tpm.isowned().isowned  
                       
                }  
                  
                $ProtectorIds = $BitLocker.GetKeyProtectors('0').volumekeyprotectorID  
                $CurrentEncryptionState = BitLockerSAK -GetEncryptionState  
                $EncryptionMethod = BitLockerSAK -GetEncryptionMethod  
                $KeyProtectorTypeAndID = BitLockerSAK -GetKeyProtectorTypeAndID  
                  
                $properties = @{  
                     'IsTPMActivated' = $TpmActivated;`  
                     'IsTPMEnabled' = $TPMEnabled;`  
                     'IsTPMOwnerShipAllowed' = $TPMOwnerShipAllowed;`  
                     'IsTPMOwned' = $TPMOwned;`  
                     'CurrentEncryptionPercentage' = $CurrentEncryptionState.CurrentEncryptionProgress;`  
                     'EncryptionState' = $CurrentEncryptionState.encryptionState; `  
                     'EncryptionMethod' = $EncryptionMethod;`  
                     'KeyProtectorTypesAndIDs' = $KeyProtectorTypeAndID  
                }  
                  
                $Return = New-Object psobject -Property $Properties  
           }  
             
      }  
      End {  
           return $return  
      }  
        
 }  
   
 Function Get-Architecture {  
      #Define Local Variables  
      Set-Variable -Name Architecture -Scope Local -Force  
        
      $Architecture = Get-WmiObject -Class Win32_OperatingSystem | Select-Object OSArchitecture  
      $Architecture = $Architecture.OSArchitecture  
      Return $Architecture  
      #Returns 32-bit or 64-bit  
        
      #Cleanup Local Variables  
      Remove-Variable -Name Architecture -Scope Local -Force  
 }  
   
 function Get-BiosStatus {  
      param ([String]$Option)  
        
      #Declare Local Variables  
      Set-Variable -Name Architecture -Scope Local -Force  
      Set-Variable -Name Argument -Scope Local -Force  
      Set-Variable -Name CCTK -Scope Local -Force  
      Set-Variable -Name Output -Scope Local -Force  
        
      $Architecture = Get-Architecture  
      If ($Architecture -eq "32-bit") {  
           $CCTK = $env:ProgramFiles + "\Dell\Command Configure\X86\cctk.exe"  
      } else {  
           $CCTK = ${env:ProgramFiles(x86)} + "\Dell\Command Configure\X86_64\cctk.exe"  
      }  
      $Argument = "--" + $Option  
      $Output = [string] (& $CCTK $Argument)  
      $Output = $Output.Split('=')  
      Return $Output[1]  
        
      #Cleanup Local Variables  
      Remove-Variable -Name Architecture -Scope Local -Force  
      Remove-Variable -Name Argument -Scope Local -Force  
      Remove-Variable -Name CCTK -Scope Local -Force  
      Remove-Variable -Name Output -Scope Local -Force  
 }  
   
 Function Install-EXE {  
      Param ([String]$DisplayName,  
           [String]$Executable,  
           [String]$Switches)  
        
      #Declare Local Variables  
      Set-Variable -Name ErrCode -Scope Local -Force  
        
      Write-Host "Install"$DisplayName"....." -NoNewline  
      If ((Test-Path $Executable) -eq $true) {  
           $ErrCode = (Start-Process -FilePath $Executable -ArgumentList $Switches -Wait -Passthru).ExitCode  
      } else {  
           $ErrCode = 1  
      }  
      If (($ErrCode -eq 0) -or ($ErrCode -eq 3010)) {  
           Write-Host "Success" -ForegroundColor Yellow  
      } else {  
           Write-Host "Failed with error code "$ErrCode -ForegroundColor Red  
      }  
        
      #Cleanup Local Variables  
      Remove-Variable -Name ErrCode -Scope Local -Force  
 }  
   
 Function Get-BitLockerRecoveryKeyId {  
        
      <#  
      .SYNOPSIS  
      This returns the Bitlocker key protector id.  
        
      .DESCRIPTION  
      The key protectorID is retrived either according to the protector type, or simply all of them.  
        
      .PARAMETER KeyProtectorType  
        
      The key protector type can have one of the following values :  
      *TPM  
      *ExternalKey  
      *NumericPassword  
      *TPMAndPin  
      *TPMAndStartUpdKey  
      *TPMAndPinAndStartUpKey  
      *PublicKey  
      *PassPhrase  
      *TpmCertificate  
      *SID  
        
        
      .EXAMPLE  
        
      Get-BitLockerRecoveryKeyId  
      Returns all the ID's available from all the different protectors.  
   
   .EXAMPLE  
   
     Get-BitLockerRecoveryKeyId -KeyProtectorType NumericPassword  
     Returns the ID(s) of type NumericPassword  
   
   
      .NOTES  
           Version: 1.0  
     Author: Stephane van Gulick  
     Creation date:12.08.2014  
     Last modification date: 12.08.2014  
   
      .LINK  
           www.powershellDistrict.com  
   
      .LINK  
           http://social.technet.microsoft.com/profile/st%C3%A9phane%20vg/  
   
   .LINK  
     #http://msdn.microsoft.com/en-us/library/windows/desktop/aa376441(v=vs.85).aspx  
 #>       
        
      [cmdletBinding()]  
      Param (  
           [Parameter(Mandatory = $false, ValueFromPipeLine = $false)][ValidateSet("Alltypes", "TPM", "ExternalKey", "NumericPassword", "TPMAndPin", "TPMAndStartUpdKey", "TPMAndPinAndStartUpKey", "PublicKey", "PassPhrase", "TpmCertificate", "SID")]$KeyProtectorType  
      )  
        
      $BitLocker = Get-WmiObject -Namespace "Root\cimv2\Security\MicrosoftVolumeEncryption" -Class "Win32_EncryptableVolume"  
        
      switch ($KeyProtectorType) {  
           ("Alltypes") { $Value = "0" }  
           ("TPM") { $Value = "1" }  
           ("ExternalKey") { $Value = "2" }  
           ("NumericPassword") { $Value = "3" }  
           ("TPMAndPin") { $Value = "4" }  
           ("TPMAndStartUpdKey") { $Value = "5" }  
           ("TPMAndPinAndStartUpKey") { $Value = "6" }  
           ("PublicKey") { $Value = "7" }  
           ("PassPhrase") { $Value = "8" }  
           ("TpmCertificate") { $Value = "9" }  
           ("SID") { $Value = "10" }  
           default { $Value = "0" }  
      }  
      $Ids = $BitLocker.GetKeyProtectors($Value).volumekeyprotectorID  
      return $ids  
 }  
   
 Function Remove-RegistryKey {  
      Param ([String]$RegistryKey,  
           [Boolean]$Recurse)  
        
      #Declare Local Variables  
      Set-Variable -Name i -Scope Local -Force  
      Set-Variable -Name RegKey -Scope Local -Force  
      Set-Variable -Name RegistryKey1 -Scope Local -Force  
      Set-Variable -Name tempdrive -Scope Local -Force  
        
      $tempdrive = New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT  
      $RegistryKey1 = $RegistryKey.split("\")  
      switch ($RegistryKey1[0]) {  
           "HKEY_CLASSES_ROOT" { $RegistryKey1[0] = "HKCR" }  
           "HKEY_CURRENT_USER" { $RegistryKey1[0] = "HKCU" }  
           "HKEY_LOCAL_MACHINE" { $RegistryKey1[0] = "HKLM" }  
           "HKEY_USERS" { $RegistryKey1[0] = "HKU" }  
           "HKEY_CURRENT_CONFIG" { $RegistryKey1[0] = "HKCC" }  
      }  
      For ($i = 0; $i -lt $RegistryKey1.Count; $i++) {  
           $RegKey = $RegKey + $RegistryKey1[$i]  
           If ($i -eq 0) {  
                $RegKey = $RegKey + ":\"  
           } elseif ($i -ne $RegistryKey1.Count - 1) {  
                $RegKey = $RegKey + "\"  
           } else {  
                $RegKey = $RegKey  
           }  
      }  
      Write-Host "Delete"$RegKey"....." -NoNewline  
      If (Test-Path $RegKey) {  
           If (($Recurse -eq $false) -or ($Recurse -eq $null)) {  
                Remove-Item -Path $RegKey -Force  
           } elseIf ($Recurse -eq $true) {  
                Remove-Item -Path $RegKey -Recurse -Force  
           }  
           if ((Test-Path $RegKey) -eq $false) {  
                Write-Host "Success" -ForegroundColor Yellow  
           } else {  
                Write-Host "Failed" -ForegroundColor Yellow  
           }  
      } else {  
           Write-Host "Not Present" -ForegroundColor Green  
      }  
        
      #Cleanup Local Variables  
      Remove-Variable -Name i -Scope Local -Force  
      Remove-Variable -Name RegKey -Scope Local -Force  
      Remove-Variable -Name RegistryKey1 -Scope Local -Force  
      Remove-Variable -Name tempdrive -Scope Local -Force  
 }  
   
 #Declare Local Variables  
 Set-Variable -Name BitlockerID -Scope Local -Force  
 Set-Variable -Name ManageBDE -Value $env:windir"\System32\manage-bde.exe" -Scope Local -Force  
 Set-Variable -Name Switches -Scope Local -Force  
 Set-Variable -Name TPMActivated -Scope Local -Force  
 Set-Variable -Name TPMEnabled -Scope Local -Force  
 Set-Variable -Name TPMOwnershipAllowed -Scope Local -Force  
   
 cls  
 #Check if TPM is enabled  
 $TPMEnabled = Get-BiosStatus -Option "tpm"  
 Write-Host "TPM Enabled:"$TPMEnabled  
 #Check if TPM is activated  
 $TPMActivated = Get-BiosStatus -Option "tpmactivation"  
 Write-Host "TPM Activated:"$TPMActivated  
 #Check if TPM Ownership is allowed  
 $TPMOwnershipAllowed = BitLockerSAK -IsTPMOwnerShipAllowed  
 Write-Host "TPM Ownership Allowed:"$TPMOwnershipAllowed  
 #Check if TPM is owned  
 $TPMOwned = BitLockerSAK -IsTPMOwned  
 Write-Host "TPM Owned:"$TPMOwned  
 If (($TPMEnabled -eq "on") -and ($TPMActivated -eq "activate") -and ($TPMOwnershipAllowed -eq $true) -and ($TPMOwned -eq $false)) {  
      #Delete Bitlocker GPO registry keys  
      Remove-RegistryKey -RegistryKey "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\FVE" -Recurse $true  
      Remove-RegistryKey -RegistryKey "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\TPM" -Recurse $true  
      #Take ownership of TPM  
      $Switches = "-tpm -takeownership" + [char]32 + $BIOSPassword  
      Install-EXE -DisplayName "Take TPM Ownership" -Executable $ManageBDE -Switches $Switches  
      #Enable Bitlocker  
      $Switches = "-on" + [char]32 + $env:HOMEDRIVE + [char]32 + "-recoverypassword"  
      Install-EXE -DisplayName "Enable Bitlocker" -Executable $ManageBDE -Switches $Switches  
      #Execute GPUpdate to re-apply registry keys  
      Install-EXE -DisplayName "GPUpdate" -Executable $env:windir"\System32\gpupdate.exe" -Switches " "  
      #Retrieve numerical password ID  
      $BitlockerID = Get-BitLockerRecoveryKeyId -KeyProtectorType NumericPassword  
      #Backup recovery key to active directory  
      $Switches = "-protectors -adbackup" + [char]32 + $env:HOMEDRIVE + [char]32 + "-id" + [char]32 + $BitlockerID  
      Install-EXE -DisplayName "Backup Recovery Key to AD" -Executable $ManageBDE -Switches $Switches  
 }  
 #Cleanup Local Variables  
 Remove-Variable -Name BitlockerID -Scope Local -Force  
 Remove-Variable -Name ManageBDE -Scope Local -Force  
 Remove-Variable -Name Switches -Scope Local -Force  
 Remove-Variable -Name TPMActivated -Scope Local -Force  
 Remove-Variable -Name TPMEnabled -Scope Local -Force  
 Remove-Variable -Name TPMOwnershipAllowed -Scope Local -Force