【发布时间】:2022-01-05 17:20:20
【问题描述】:
我正在编写一个脚本来将现有的位锁密钥备份到 Azure AD 中的关联设备,我创建了一个函数,该函数通过启用位锁的卷并将密钥备份到 Azure 但是想知道如何我可以检查该功能是否已成功完成,没有任何错误。这是我的代码。我已经在函数中添加了一个 try and catch 以捕获函数本身的任何错误但是我如何检查函数是否已成功完成 - 目前我有一个 IF 语句检查最后一个命令是否已运行“$? - 这是是否正确或如何验证?
function Invoke-BackupBDEKeys {
##Get all current Bit Locker volumes - this will ensure keys are backed up for devices which may have additional data drives
$BitLockerVolumes = Get-BitLockerVolume | select-object MountPoint
foreach ($BDEMountPoint in $BitLockerVolumes.mountpoint) {
try {
#Get key protectors for each of the BDE mount points on the device
$BDEKeyProtector = Get-BitLockerVolume -MountPoint $BDEMountPoint | select-object -ExpandProperty keyprotector
#Get the Recovery Password protector - this will be what is backed up to AAD and used to recover access to the drive if needed
$KeyId = $BDEKeyProtector | Where-Object {$_.KeyProtectorType -eq 'RecoveryPassword'}
#Backup the recovery password to the device in AAD
BackupToAAD-BitLockerKeyProtector -MountPoint $BDEMountPoint -KeyProtectorId $KeyId.KeyProtectorId
}
catch {
Write-Host "An error has occured" $Error[0]
}
}
}
#Run function
Invoke-BackupBDEKeys
if ($? -eq $true) {
$ErrorActionPreference = "Continue"
#No errors ocurred running the last command - reg key can be set as keys have been backed up succesfully
$RegKeyPath = 'custom path'
$Name = 'custom name'
New-ItemProperty -Path $RegKeyPath -Name $Name -Value 1 -Force
Exit
}
else {
Write-Host "The backup of BDE keys were not succesful"
#Exit
}
【问题讨论】:
-
BackupToAAD-BitLockerKeyProtector可能会引发异常,$?仍会返回$true- 您的catch块隐藏了这一事实。如果您想在调用堆栈的上层处理错误,则需要重新抛出错误(或抛出新错误) -
为什么不在同一个函数中包含所有代码,
if语句的内容可能在您的 try 语句和 中的elsecatch 语句。
标签: function powershell bitlocker