vbs unlock bitlocker code example

Example: vbs unlock bitlocker

Set oShell = CreateObject("Wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")

' :CONFIGURATION:

' Unlock a drive with the letter "E:", the name "test" and its recovery key
Call PossiblyUnlock (_
	"E",_
	"test",_
	"YOUR-BITLOCKER-RECOVERY-KEY-HERE"_
)


' :FUNCTIONS:

' Runs the current process with administrator rights if it ain't already
Function RunAsAdmin ()
	If Not WScript.Arguments.Named.Exists("elevate") Then
		CreateObject("Shell.Application").ShellExecute WScript.FullName _
			, """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
		WScript.Quit
	End If
End Function

' Checks if the drive with the given letter and name is available
' Params:
' - letter: letter of the drive
' - name: name of the drive
' Returns:
' - 0: Drive not found
' - 1: Error (-> Drive possibly locked)
' - 2: Drive available
Function CheckForDrive (letter, name)
	CheckForDrive = 0
	On Error Resume Next
	If fso.DriveExists(letter) Then
		Set drive = fso.GetDrive(letter)
		If drive.VolumeName = name Then
			CheckForDrive = 2
		End If
	End If
	If Err.Number <> 0 Then
		CheckForDrive = 1
	End If
	On Error Goto 0
End Function

' Unlocks a BitLocker locked drive if neccessary
' Params:
' - letter: letter of the drive
' - name: name of the drive
' - password: BitLocker recovery key to unlock the locked drive
' Returns:
' - Boolean: Was the drive successfully unlocked
Function PossiblyUnlock (letter, name, password)
	PossiblyUnlock = False
	If CheckForDrive(letter, name) = 1 Then
		RunAsAdmin
		cmd = "manage-bde -unlock D: -RecoveryPassword " & password
		oShell.Run cmd, 0, True
		If CheckForDrive(letter, name) = 2 Then
			PossiblyUnlock = True
		End If
	End If
End Function