bootsector
bootsector

Reputation: 49

powershell bitlocker won't unlock drive properly

I'm about to write a powershell backup script.
- First step is to autodetect specific USB drives (by drive-ID)
- then, unlock-bitlocker unlocks the drive (by password)
- free disk space is checked
- backup is copied to hard drive
- lock-bitlocker locks the drive again.
- Email about backup success is sent.

now it appears, that running the script the first time won't unlock the drive properly. I know that, because my check-disk-space function won't find the right disk space. The script stops, but the drive is shown as unlocked. Now running the script the second time (drive is sitll unlocked from first run) will find the disk space and the script continues running as it should.

here is a sample of the code, I hope you can help me find out why I need to run the script 2 times to unlock, copy and lock the drive.

function getUSBDrive($validDriveIDs)
$connectedDrives = Get-WmiObject Win32_Volume

foreach ($drive in $connectedDrives) 
     foreach ($id in $validDriveIDs) 
        if ($drive.DeviceID -eq $id) 
            return $drive

so in $drive I got my valid USB drive
next function should unlock my drive

function unlockDrive ($backupDrive, $password) 
$SecureString = ConvertTo-SecureString $password -AsPlainText -Force

$DriveLetter = $backupDrive.DriveLetter
Unlock-BitLocker -MountPoint $DriveLetter -Password $SecureString

write-Host "unlocked"

next function says "not enough space" first time, but "enough space" second time

function checkFreeSpaceOnUSB($backupDrive)

$freeSpace = ($backupDrive.FreeSpace / 1GB) 

if ($freeSpace -lt $minimumDiskSpace)
    write-Host "less than $minimumDiskSpace GB free Space on USB Drive"
    return 0

else 
    write-Host "Drive has enough space"
    return 1

and this is how I call these functions:

$backupDrive = getUSBDrive $validDriveIDs
unlockDrive $backupDrive $passwordToUnlock
checkFreeSpaceOnUSB $backupDrive

So it seems like unlock-bitlocker won't unlock properly WITHIN the script. Explorer says drive is unlocked after first run. Calling the script second time with or without the unlock function gives same results - it works. So the first run must have unlocked the drive somehow. Since my english is not the best I hope I could describe the problem good enough.

Many thanks in advance for your help!

Upvotes: 0

Views: 495

Answers (1)

Artur Biesiadowski
Artur Biesiadowski

Reputation: 3698

It seems that inside getUSBDrive you are getting a static copy of current state of drive. Solution is to retrieve disk metadata once again after unlocking it and overwriting previous value in variable (or using new one). Something like

$backupDrive = getUSBDrive $validDriveIDs
unlockDrive $backupDrive $passwordToUnlock
$unlockedBackupDrive = getUSBDrive $validDriveIDs
checkFreeSpaceOnUSB $unlockedBackupDrive 

Upvotes: 0

Related Questions