You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本elseif分支异常:BitLocker加密分支未执行排查

问题:BitLocker加密分支未执行排查

编写了一个PowerShell脚本,功能为检测BitLocker GPO生成的注册表项属性、检查设备是否已加密,当注册表项状态正确且设备未加密时执行加密操作。各函数单独测试均正常,整体运行时其他elseif分支均能正确触发,唯独加密分支无任何输出与退出码,虽已确认变量值设置正确,但加密函数始终未执行。

原脚本代码如下:

# FUNCTION - Function created to check existence of Active Directory GPO
Function Test-RegistryValue {
$regPath = 'HKLM:\SOFTWARE\Policies\Microsoft\FVE'
$regPropertyName = 'ActiveDirectoryBackup'

# Value of registry key ported into a script-level variable accessible from outside the function
  $regValue = (Get-ItemPropertyValue -Path $regPath -Name $regPropertyName -ErrorAction ignore)
     if ($regValue -eq 1)
       {
         $script:regExit = 0
       } 

# If the key exists but is not set to write back    
     elseif ($regValue -eq 0) 
     { 
        $script:regExit = 1
     }
# If the registry property doesn't exist
     else 
     {
       $script:regExit = 5
     }

} 

# FUNCTION - Function tests if BitLocker protection is already on
function Test-TBBitlockerStatus {$BLinfo = Get-Bitlockervolume

if($blinfo.ProtectionStatus -eq 'On' -and $blinfo.EncryptionPercentage -eq '100')
    {
      return $true
    }
else 
    {
     return $false
    }
}

# FUNCTION - This function is the actual encryption script
Function Enable-TBBitlocker {
Add-BitLockerKeyProtector -MountPoint $env:SystemDrive -RecoveryPasswordProtector 

$RecoveryKey = (Get-BitLockerVolume -MountPoint $env:SystemDrive).KeyProtector | Where-Object {$_.KeyProtectorType -eq "RecoveryPassword"} 

Manage-bde -protectors -adbackup $env:SystemDrive -id $RecoveryKey[0].KeyProtectorId

Enable-BitLocker -MountPoint $env:SystemDrive -UsedSpaceOnly -TpmProtector -SkipHardwareTest
}

# MAIN SCRIPT
# Running the GPO check function
Test-RegistryValue
Test-TBBitlockerStatus
$regExit

    if ($regExit -eq 1) 
        {
             Write-Host 'Key present but writeback not enabled.'
             exit 51
        }
# Exit if GPO not present
    elseif ($regExit -eq 5) 
        {
             Write-Host 'GPO not present.'
              exit 55
        }
# Test for device already being encrypted
    elseif ((Test-TBBitlockerStatus -eq True) -and ($regExit -eq 0))
        {
            Write-Host 'Writeback enabled but device already protected.'
            exit 61
        }
# Test for device being encrypted and writeback is not enabled.
    elseif ((Test-TBBitlockerStatus -eq True) -and ($regExit -ge 1))
        {
            Write-Host 'Device already protected but AD writeback is not enabled.'
            exit 65
        }
    elseif ((Test-TBBitlockerStatus -eq False) -and ($regExit -eq 0)) 
        {
             Enable-TBBitlocker | Write-Output
             Write-Host 'Encryption successful.'
             exit 10 
        }

问题排查与修复

1. 核心条件判断语法错误

加密分支的条件写法错误:(Test-TBBitlockerStatus -eq True) 不符合PowerShell语法逻辑。函数本身返回布尔值,直接调用函数即可作为判断条件,无需再与True比较。错误写法会导致函数被当作命令接收-eq、True参数,执行异常后返回非预期结果,分支永远无法触发。

2. 加密状态检测函数的逻辑漏洞

Get-BitLockerVolume会返回系统所有卷的信息,直接使用$blinfo.ProtectionStatus会得到数组值,判断逻辑不准确。应只针对系统盘做检测,同时EncryptionPercentage是数值类型,无需加引号。

修改后的Test-TBBitlockerStatus函数:

function Test-TBBitlockerStatus {
    $BLinfo = Get-Bitlockervolume -MountPoint $env:SystemDrive
    if($blinfo.ProtectionStatus -eq 'On' -and $blinfo.EncryptionPercentage -eq 100)
    {
      return $true
    }
    else 
    {
     return $false
    }
}

3. 加密函数添加错误捕获

原加密函数无错误处理,执行异常会静默失败,无法排查问题。添加try/catch捕获异常,同时增加密钥保护器存在性校验:

修改后的Enable-TBBitlocker函数:

Function Enable-TBBitlocker {
    try {
        Add-BitLockerKeyProtector -MountPoint $env:SystemDrive -RecoveryPasswordProtector -ErrorAction Stop
        $RecoveryKey = (Get-BitLockerVolume -MountPoint $env:SystemDrive).KeyProtector | Where-Object {$_.KeyProtectorType -eq "RecoveryPassword"}
        if (-not $RecoveryKey) {
            throw "未找到RecoveryPassword类型的密钥保护器"
        }
        Manage-bde -protectors -adbackup $env:SystemDrive -id $RecoveryKey[0].KeyProtectorId
        Enable-BitLocker -MountPoint $env:SystemDrive -UsedSpaceOnly -TpmProtector -SkipHardwareTest -ErrorAction Stop
    }
    catch {
        Write-Error "加密失败: $_"
        exit 11
    }
}

4. 主脚本分支逻辑修正

修正条件判断,同时提前存储函数返回值,避免重复调用函数导致的状态不一致或性能损耗:

修改后的主脚本部分:

# MAIN SCRIPT
# Running the GPO check function
Test-RegistryValue
$isEncrypted = Test-TBBitlockerStatus
$regExit

if ($regExit -eq 1) 
{
    Write-Host 'Key present but writeback not enabled.'
    exit 51
}
# Exit if GPO not present
elseif ($regExit -eq 5) 
{
    Write-Host 'GPO not present.'
    exit 55
}
# Test for device already being encrypted
elseif ($isEncrypted -and $regExit -eq 0)
{
    Write-Host 'Writeback enabled but device already protected.'
    exit 61
}
# Test for device being encrypted and writeback is not enabled.
elseif ($isEncrypted -and $regExit -ge 1)
{
    Write-Host 'Device already protected but AD writeback is not enabled.'
    exit 65
}
elseif (-not $isEncrypted -and $regExit -eq 0) 
{
    Enable-TBBitlocker
    Write-Host 'Encryption successful.'
    exit 10 
}

内容的提问来源于stack exchange,提问作者Daratic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 12:10:38