Powershell 位锁检查

Powershell bitlocker check

嗨,我很难让我的脚本正常工作: 它在第一次写入输出时一直失败,即使 powershell 版本高于 4。它仅在我删除 And $winver -eq $os1 -or $os2 -or $os3 时有效。

不然一直提示我的powershell版本需要升级。我目前使用的是 V5,$PSVersionTable.PSVersion.Major 的确如此 5。 我做错了什么?

    $winver = (Get-WmiObject -class Win32_OperatingSystem).Caption
$powershellversion = $PSVersionTable.PSVersion.Major
$os1 = "Microsoft Windows 7 Professional"
$os2 = "Microsoft Windows 10 Pro"
$os3 = "Microsoft Windows 10 Enterprise"

if($winver -ne ($os1, $os2, $os3) -contains $winver){
    Write-Host "Bitlocker not supported on $winver"
    Exit 0
}

if($powershellversion -lt 4){
    Write-Host "Upgrade Powershell Version"
    Exit 1010
}
else
{

$bitlockerkey = (Get-BitLockerVolume -MountPoint C).KeyProtector.RecoveryPassword
$pcsystemtype = (Get-WmiObject -Class Win32_ComputerSystem).PCSystemType
if ($pcsystemtype -eq "2"){
$setsystemtype = "Laptop"
}
else {
$setsystemtype = "Desktop"
}

if ($setsystemtype -eq "laptop" -And $bitlockerkey -eq $null  -and ($os1, $os2, $os3) -contains $winver){
Write-Host "$setsystemtype without bitlocker"
Exit 1010
}

if ($setsystemtype -eq "desktop" -And $bitlockerkey -eq $null  -and ($os1, $os2, $os3) -contains $winver){
Write-Host "$setsystemtype without bitlocker"
Exit 0
}

if ($winver -eq ($os1, $os2, $os3) -contains $winver){
Write-Host "$bitlockerkey"
Exit 0
}
}

让我们看看这实际上做了什么:

if ($powershellversion -lt 4 -And $winver -eq $os1 -or $os2 -or $os3) { ... }
  • 如果你的powershell版本小于4,Win版本相等 到 os1,然后继续
  • 如果os2有值,则继续
  • 如果os3有值,则继续

这里的主题是Operator Precedence,具体来说,在评估一行代码时首先发生什么,第二、第三,等等。就像在代数数学中一样,在部分公式周围添加括号会改变您阅读它的顺序。

所以,你可以乱用括号来让你的逻辑起作用:

if($powershellversion -lt 4 -and ( ($winver -eq $os1) -or ($winver -eq $os2) -or ($winver -eq $os3) ))

换句话说

  • 评估 PS 版本是否 < 4 ($powershellversion -lt 4),-and
  • 评估 winver 是 os1、os2 还是 os3:( ($winver -eq $os1) -or ($winver -eq $os2) -or ($winver -eq $os3) )

或者,您可以通过将 os 变量放入数组中并查看 $winver 是否在其中来稍微重新安排您的逻辑:

if($powershellversion -lt 4 -and $winver -in ($os1, $os2, $os3)) { ... }

编辑:或

if($powershellversion -lt 4 -and ($os1, $os2, $os3) -contains $winver) { ... }

向后兼容 v2.0。