Search code examples
powershellloopsdo-whilebitlocker

How can I create a proper do-while loop using Powershell


I want the script to generate a random last group (Key0) and try to unlock the drive on each iteration with the concatenated string (Key), but is not working. I execute the script and it just makes one try. It seems the while is not working.

Do {      
  $Hash0 = 0..5 | % {Get-Random -Minimum 0 -Maximum 9 }
  $Key0 = $Hash0 -join ""
  $Key  = "175615-666567-468105-046717-174922-139634-579799-"+$Key0
  manage-bde.exe -unlock H: -recoverypassword $Key >$null
  $Status = Get-BitlockerVolume -MountPoint "H:" 
} while($Status.CapacityGB -ne "0")

I'm not a Powershell expert.


Solution

  • With a Do-While loop the script block is executed at least once.

    The While condition is evaluated after the script block has run. The script block will be repeated as long as the condition in the While statement is true.

    Your statement While statement is

    while($Status.CapacityGB -ne "0")

    You want the do loop to execute while CapacityGB is not equal to 0

    If the loop stopping it suggested that your while statement is evaluating to false which suggests the CapacityGB is zero. I'd check what you're getting in the $status variable