使用powershell验证数字引脚长度

zhte4eai  于 2023-01-17  发布在  Shell
关注(0)|答案(2)|浏览(158)

此问题来自超级用户migrated,因为23天前可以在Stack Overflow. Migrated上回答。
我想让用户设置锁位器引脚和引脚长度应该是数字9位数,而不是像123456789序列。

我尝试的代码:-

$PIN = Read-Host -AsSecureString -Prompt 'Input your bitlocker PIN'

$SecureString = ConvertTo-SecureString $PIN -AsPlainText -Force

Enable-BitLocker -MountPoint "C:" -EncryptionMethod Aes256 -UsedSpaceOnly -Pin $SecureString -TPMandPinProtector
u5rb5r59

u5rb5r591#

这段代码假设您不希望用户在他们的pin中有3个或更多的序列号。我们可以设置多个值来进行匹配,然后使用regex将字符串与列表中的任何值进行匹配。

$sequence = @('012','123','234','345','456','567','678','789','987','876','765','654','543','432','321','210')
$sequenceRegex = [string]::Join('|', $sequence)

Do 
{ 

    $PIN = Read-Host -Prompt 'Input your PIN. Should be 9 digits and not contain a sequence of 3 or more numbers.'
}

While($PIN -match $sequenceRegex -or $PIN.Length -ne 9)

Write-Host $PIN  # just for example to confirm

$SecureString = ConvertTo-SecureString $PIN -AsPlainText -Force

Enable-BitLocker -MountPoint "C:" -EncryptionMethod Aes256 -UsedSpaceOnly -Pin $SecureString -TPMandPinProtector
hk8txs48

hk8txs482#

如果愿意,您可以想出更多的规则(在下面的代码中,我添加了一个测试,以排除重复两次以上的数字),但您应该

  • 如果用户想要退出,则提供退出方法
  • 从用户可能输入的字符串中删除所有非数字
  • 如果其中一项测试失败,则向用户提供一些解释

试试看

# create a regex sequence
# $sequence = (0..7 | ForEach-Object { ('{0}{1}{2}' -f $_, ($_ + 1), ($_ + 2)),
#                                      ('{0}{1}{2}' -f (9 - $_), (8 - $_), (7 - $_)) } |
#              Sort-Object) -join '|'

# or just define it
$sequence = '012|123|210|234|321|345|432|456|543|567|654|678|765|789|876|987'
$repeats  = '111|222|333|444|555|666|777|888|999'

while ($true) {
    $PIN = Read-Host 'Input your bitlocker PIN. Must be 9 digits. Press Q to quit'
    if ($PIN -match '^q') { $PIN = $null; break }   # exit the loop

    $PIN = $PIN -replace '\D'  # remove all non-digits from the input string
    # test length
    if ($PIN.Length -ne 9) {
        Write-Warning "You must enter 9 digits exactly.."
        continue
    }

    # test for repeated digits. Remove this block if you don't want to test on repeats
    if ($PIN -match $repeats) {
        Write-Warning "The pin may not have repeated digits more than twice (like 111 or 888).."
        continue
    }

    # test for sequences
    if ($PIN -notmatch $sequence) { break }  # corect pin, exit the loop

    Write-Warning "The pin may not have sequential digits (like 123 or 876).."
}

if ($PIN) {
    $SecureString = ConvertTo-SecureString $PIN -AsPlainText -Force
    Enable-BitLocker -MountPoint "C:" -EncryptionMethod Aes256 -UsedSpaceOnly -Pin $SecureString -TPMandPinProtector
}

相关问题