none
BitLocker powershell script automation by GPO execute when logoff RRS feed

  • Question

  • I am very fresh on scripting.

    I need to auto enable bitlocker for all PCs.  I have cooked a powershell script for the assignment. And I have problem with it.  Please advise how to debug or handle.  Thanks!

    1. The script could run normally when logon and runas administrator

    2. While deploy by GPO logoff script not work and even don't know if it has been executed

    3. While deploy by GPO logon script it works

    • Moved by Bill_Stewart Wednesday, September 13, 2017 9:21 PM Unanswerable drive-by question
    Wednesday, July 26, 2017 9:21 AM

All replies

  • Wednesday, July 26, 2017 9:37 AM
  • What have you cooked? Can we see it?

    You should not use logon/logoff scripts, those run with user credentials. Use startup scripts instead or deploy a task that runs as system account. If you need syntax help, you'd need to clarify what you would like to do, what OS' and what parameters this is about. For example:

    manage-bde -on c: -used -s -em XTS_AES256 -rp

    would be a perfect startup script for win10 to turn on bitlocker while utilizing a TPM-only protector. One line of code. If you accompany that with a GPO that enforces Recovery key AD backup, the key will even be saved to AD fully automatic.



    Wednesday, July 26, 2017 1:11 PM
  • Thanks and here is my code.

    I need to use Local System credentials to execute the encryption and would like to complete without affect user normal work.

    My target clients are Windows 8.1 and sure need to support future version too.

    I have tried to use GPO StartUp /Shutdown & Logon/Logoff.  It seems Startup is much better and have successful case.

    For enforces Recovery Password AD backup, I have created a GPO to support and got no problem on that.

    Now I need:

    1. Logon script ==> To check if TPM status and notice user to report if TPM not exist, not ready for encrypt.

    2.  Startup / Shutdown (preferred) script ==> To automate enable BitLocker for PCs.  Including create System drive (Boot partition), encrypt local HDD (OS - Drive C and Data - Drive D).

    ======================================================================

                                                                                                      

    # To allow current user execute PowerShell Scripts
    Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope LocalMachine -Force

    # Encryption Method [e.g. Aes128 or Aes256]
    $EnMethod = "Aes128"

    # Log file with timestamp
    $TimeStamp = (get-date).ToString("yyyy-MM-dd-HH-mm-ss") 

    # Get target machine local drive
    $colItems = get-wmiobject -query "Select * from Win32_LogicalDisk where DriveType = 3" -computername $ENV:COMPUTERNAME


    ##############################
    # Encryption with TPM module #
    ##############################
    Function TPMEncryption {

        Write-Host "The drive is starting to encrypt....please state tune!!!"
        Write-Host

        # Match if total local volumn equal to BitLocker regonized total volumn
        if ($colItems.Count -eq $IfVolEnc.Count){

            For ($VolNu=0; $VolNu -le ($colItems.Count-1); $VolNu++)
                {

                    Switch ($VolNu){
                        0 {# Encryption for Drive C
                            if($IfVolEnc.volumestatus[$VolNu] -eq "FullyEncrypted" -and $IfVolEnc.protectionstatus[$VolNu] -eq "On"){}
                            Else{                                
                                    Enable-BitLocker -MountPoint $IfVolEnc.MountPoint[$VolNu] -TpmProtector -EncryptionMethod $EnMethod -UsedSpaceOnly -Verbose | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_C-$TimeStamp.log
                                    Add-BitLockerKeyProtector -MountPoint $IfVolEnc.MountPoint[$VolNu] -RecoveryPasswordProtector | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_C-$TimeStamp.log -Append
                                    #[System.Windows.MessageBox]::Show('Start to perform System Drive encryption','Encrypt System Drive','OK','Information')
                                    #Restart-Computer -ComputerName $ENV:COMPUTERNAME #-Wait -For PowerShell
                                }
                          }
                        1 {# Encryption for Drive D
                            if($IfVolEnc.volumestatus[0] -eq "FullyEncrypted" -and $IfVolEnc.protectionstatus[0] -eq "On"){
                                    Enable-BitLocker -MountPoint $IfVolEnc.MountPoint[$VolNu] -RecoveryPasswordProtector -EncryptionMethod $EnMethod -UsedSpaceOnly -Verbose | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_D-$TimeStamp.log
                                    Enable-BitLockerAutoUnlock -MountPoint $IfVolEnc.MountPoint[$VolNu] | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_D-$TimeStamp.log -Append
                            }                        
                          }
                        2 {# Encryption for Drive E
                            if($IfVolEnc.volumestatus[0] -eq "FullyEncrypted" -and $IfVolEnc.protectionstatus[0] -eq "On"){
                                    Enable-BitLocker -MountPoint $IfVolEnc.MountPoint[$VolNu] -RecoveryPasswordProtector -EncryptionMethod $EnMethod -UsedSpaceOnly -Verbose | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_E-$TimeStamp.log
                                    #Write-Host
                                    #Write-Warning "請設定一個高強度 8-256 位的密碼(包括:A-Z,a-z,0-9,!,$,#,%...)"
                                    #Write-Host
                                    #Add-BitLockerKeyProtector -MountPoint $IfVolEnc.MountPoint[$VolNu] -PasswordProtector | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_E-$TimeStamp.log -Append
                                    Enable-BitLockerAutoUnlock -MountPoint $IfVolEnc.MountPoint[$VolNu] | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_E-$TimeStamp.log -Append
                            }
                          }
                        }
                }
               }      
          Else{
                # Logic found miss match action
                Write-Host "HDD Volume regonized by BitLocker with error.  Please get your administrator support!!!!"
                #[System.Windows.MessageBox]::Show('HDD Volume regonized by BitLocker with error.  Please contact Help Desk by 2921 for support!!!!','HDD Volume Error','OK','Warning')
                $wshell = New-Object -ComObject Wscript.Shell
                $wshell.Popup("HDD Volume regonized by BitLocker with error.  Please contact Help Desk by 2921  for support!!!!",0,"HDD Recogonize",0)
            }              

    }# End function TPMEncryption

    #################################
    # Encryption without TPM module #
    #################################
    Function NonTPMEncryption {

        Write-Host "The drive is encrypting without TPM support....please state tune!!!"
        Write-Host

        # Match if total local volumn equal to BitLocker regonized total volumn
        if ($colItems.Count -eq $IfVolEnc.Count){

            # Debug if pass checing
            # Write-Host "Pass Vaildation Count vs Count"

            For ($VolNu=0; $VolNu -le ($colItems.Count-1); $VolNu++)
                {

                # Debug looping
                # Write-Host "Before loop: " $VolNu

                    Switch ($VolNu){
                        0 {# Encryption for Drive C
                            if($IfVolEnc.volumestatus[$VolNu] -eq "FullyEncrypted" -and $IfVolEnc.protectionstatus[$VolNu] -eq "On"){}
                            Else{
                                    Write-Host
                                    Write-Warning "請設定一個高強度 8-256 位的密碼(包括:A-Z,a-z,0-9,!,$,#,%...)"
                                    Write-Host
                                    Enable-BitLocker -MountPoint $IfVolEnc.MountPoint[$VolNu] -PasswordProtector -EncryptionMethod $EnMethod -UsedSpaceOnly -Verbose | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_C-$TimeStamp.log
                                    Add-BitLockerKeyProtector -MountPoint $IfVolEnc.MountPoint[$VolNu] -RecoveryPasswordProtector | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_C-$TimeStamp.log -Append
                                    #Restart-Computer -ComputerName $ENV:COMPUTERNAME #-Wait -For PowerShell                                                            
                                 }
                          }
                        1 {# Encryption for Drive D
                            if($IfVolEnc.volumestatus[0] -eq "FullyEncrypted" -and $IfVolEnc.protectionstatus[0] -eq "On"){
                                    Enable-BitLocker -MountPoint $IfVolEnc.MountPoint[$VolNu] -RecoveryPasswordProtector -EncryptionMethod $EnMethod -UsedSpaceOnly -Verbose | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_D-$TimeStamp.log
                                    Enable-BitLockerAutoUnlock -MountPoint $IfVolEnc.MountPoint[$VolNu] | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_D-$TimeStamp.log -Append
                            }
                          }
                        2 {# Encryption for Drive E
                            if($IfVolEnc.volumestatus[0] -eq "FullyEncrypted" -and $IfVolEnc.protectionstatus[0] -eq "On"){
                                    Enable-BitLocker -MountPoint $IfVolEnc.MountPoint[$VolNu] -RecoveryPasswordProtector -EncryptionMethod $EnMethod -UsedSpaceOnly -Verbose | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_E-$TimeStamp.log
                                    Write-Host
                                    Write-Warning "請設定一個高強度 8-256 位的密碼(包括:A-Z,a-z,0-9,!,$,#,%...)"
                                    Write-Host
                                    Add-BitLockerKeyProtector -MountPoint $IfVolEnc.MountPoint[$VolNu] -PasswordProtector | Out-File D:\logs\$ENV:COMPUTERNAME-bitlocker_E-$TimeStamp.log -Append
                            }
                          }
                    }

                # Debug looping
                #Write-Host "After loop: " $VolNu

                }
               }      
          Else{
                # Logic found miss match action
                Write-Host "HDD Volume regonized by BitLocker with error.  Please get your administrator support!!!!"
                #[System.Windows.MessageBox]::Show('HDD Volume regonized by BitLocker with error.  Please contact Help Desk by 2921 for support!!!!','HDD Volume Error','OK','Warning')
                $wshell = New-Object -ComObject Wscript.Shell
                $wshell.Popup("HDD Volume regonized by BitLocker with error.  Please contact Help Desk by 2921 for support!!!!",0,"HDD Recogonize",0)
            }

            # Debug if reach
            # Write-Host "End function NonTPMEncryption"


    }# End function NonTPMEncryption

    ######################
    # Main Program Start #
    ######################

    # Get target machine local drive
    $colItems = get-wmiobject -query "Select * from Win32_LogicalDisk where DriveType = 3" -computername $ENV:COMPUTERNAME

    # Is TPM present
    $Tpm = Get-Tpm
    $TPMHWExist = $Tpm.TpmPresent

    # Check if Device is already encrypted
    $IfVolEnc = Get-BitLockerVolume

    :DevEnCheck For ($a=0; $a -le ($IfVolEnc.count-1); $a++)
    {
        $VolEnc = "False"

        if ($IfVolEnc.volumestatus[$a] -eq "FullyEncrypted" -and $IfVolEnc.protectionstatus[$a] -eq "On"){ 
                $VolEnc = "True"
            }
        Else{ 
                if($IfVolEnc.volumestatus[$a] -eq "EncryptionInProgress" -or $IfVolEnc.volumestatus[$a] -eq "DecryptionInProgress"){
                    Write-Host
                    Write-Host "Drive" $IfVolEnc.MountPoint[$a] "operation is in process.  Please wait until completed......"
                    Write-Host 
                    Start-Sleep -Seconds 2
                    #Write-Host "************************************************" -ForegroundColor Green
                    Write-Host "==========================" -ForegroundColor Magenta
                    Write-Host "* Drive progress Summary *" -ForegroundColor Magenta
                    Write-Host "==========================" -ForegroundColor Magenta
                    Write-Host 
                    Write-Host "Encrypting Drive =>" $IfVolEnc.MountPoint[$a] -ForegroundColor Green
                    Write-Host
                    Write-Host "Process Status   =>" $IfVolEnc.VolumeStatus[$a] -ForegroundColor Green
                    Write-Host
                    Write-Host "Progess(%)       =>" $IfVolEnc.EncryptionPercentage[$a]"%" -ForegroundColor Green
                    #$ifVolEnc[$a] | select MountPoint,VolumeStatus,EncryptionPercentage
                    #Write-Host "*************************************************"-ForegroundColor Green
                    Read-Host
                    Exit
                }
                Else{
                        $VolEnc = "False"
                        break DevEnCheck
                }
            }
    }

    # Logic to exit program if all local HDDs already encrypted

    If ($VolEnc -eq "True"){
            Write-Host "The local HDD(s) is fully encrypted....."        
            # Start-Sleep -Seconds 5
            Exit
        }

    #####################################
    # Initial stage for disk encryption #
    #####################################

    $CheckBoot = Get-Partition | Select IsSystem
    $CheckBootResult = "True"

    :BootPartCheck For($PartNu=1; $PartNu -le ($CheckBoot.Count); $PartNu++){

        $CheckBootResult = $CheckBoot[$PartNu]
        If ($CheckBootResult -eq $true){
            Break BootPartCheck
        }
    }

    #If ($CheckBootResult -eq $False){
    #       Write-Host
    #       Write-Host "Preparing system partition for support Drive C encryption........"
    #       Write-Host
    #       [System.Windows.MessageBox]::Show('Now start to prepare the System Partition!!!','System Partition Operation','OK','Information')
            bdehdcfg -target default -quiet | Out-File D:\logs\$ENV:COMPUTERNAME-SysPart-$TimeStamp.log
    #}

    Switch ($TPMHWExist) # Check if TPM HW Present
    {
        "True" 
            {
                if($tpm.TpmReady -eq $true){ # Check if TPM Ready
                    TPMEncryption
                }
                Else{ 
                        Write-Host
                        Write-Warning "TPM not yet ready for BitLocker.  Please contact your Administrator to check the GPO readiness!!!"
                        Write-Host
                        #[System.Windows.MessageBox]::Show('TPM not yet ready for perform drive encryption.  Please contact Help Desk by 2921 for support!!!!','TPM readiness Error','OK','Warning')
                        $wshell = New-Object -ComObject Wscript.Shell
                        $wshell.Popup("TPM not yet ready for perform drive encryption.  Please contact Help Desk by 2921 for support!!!!",0,"TPM Readiness",0)
                        Get-Tpm | Out-File D:\logs\$ENV:COMPUTERNAME-TPM-Info-$TimeStamp.log
                    }
             }
        "False" 
             {
                 Write-Warning "The Trusted Platform Module (TPM) not found.  It is required to use personal PIN for OS start up.  Please ready to input your own PIN!"
                 #[System.Windows.MessageBox]::Show('The PC does not installed with TPM.  Please contact Help Desk by 2921 for support!!!!','TPM chips not exist','OK','Warning')
                 $wshell = New-Object -ComObject Wscript.Shell
                 $wshell.Popup("The PC does not installed with TPM.  Please contact Help Desk by 2921 for support!!!!",0,"TPM not installed",0)
                 #NonTPMEncryption
                }
        Default
              {
                 Write-Host "TPM HW status not define....Please contact your administrators for support" -ForegroundColor Red
                 #[System.Windows.MessageBox]::Show('The PC does not installed with TPM.  Please contact Help Desk by 2921 for support!!!!','TPM chips not exist','OK','Warning')
                 $wshell = New-Object -ComObject Wscript.Shell
                 $wshell.Popup("The PC does not installed with TPM.  Please contact Help Desk by 2921 for support!!!!",0,"TPM not installed",0)
                 exit
                }
    }

    ##########################################################
    # Get KeyProtector for individual Drive and backup to AD #
    ##########################################################

    $DL = Get-Volume
    New-PSDrive -Name dest -Root \\hkp\logs\Bitlockers -PSProvider FileSystem

    $WMIEnVol = Get-WmiObject -Namespace "Root\cimv2\security\MicrosoftVolumeEncryption" -ClassName "Win32_Encryptablevolume"

    # Get key protector ID
    ###(Get-BitLockerVolume).keyprotector[0].KeyProtectorID

    # Backup Recovery Information to AD
    ## manage-bde -protectors -adbackup C: -id %backupID%


    For($VolNu=0; $VolNu -le ($colItems.Count); $VolNu++){

        # To Print out all the ProtectorKey Info for particular drive [e.g. Drive C, Drive D or Drive E....etc]
        $ConDL = $DL.DriveLetter[$VolNu]   

        (Get-BitLockerVolume -MountPoint $ConDL).KeyProtector | Out-File dest:\$ENV:COMPUTERNAME-BitLocker_Recovery_info_$ConDL-$TimeStamp.txt

        # To Backup particular drive KeyProtector info to AD by ID
        ##For($KeyID=0; $KeyID -le ((Get-BitLockerVolume -MountPoint $ConDL).KeyProtector.count); $KeyID++){

        ##    manage-bde.exe -protectors -adbackup $WMIEnVol.driveLetter[$VolNu] -id ((Get-BitLockerVolume).keyprotector[$KeyID].KeyProtectorID) |  Out-File dest:\$ENV:COMPUTERNAME-BitLocker_Recovery_info_$ConDL-$TimeStamp.txt -Append

        ##}
    }

    ====================================================================

    Friday, July 28, 2017 2:09 AM
  • Noted with thanks
    Friday, July 28, 2017 2:11 AM
  • What doesn't work?  Where is your logoff script?  Why are you doing this with a script and not with a GPO?


    \_(ツ)_/

    Friday, July 28, 2017 2:19 AM