PowerShell通过创建和使用凭据对象验证密码更改是否成功

taor4pac  于 2023-03-23  发布在  Shell
关注(0)|答案(1)|浏览(148)

PowerShell 5.1
我想在更改User1的计算机阵列的密码后测试凭据。

function SetUser1Paswword($hosts, $credential, $newPassword) {
    Invoke-Command -ComputerName $hosts -Credential $credential -ScriptBlock {
        $securePassword = ConvertTo-SecureString -String $using:newPassword -AsPlainText -Force
        Set-LocalUser -Name User1 -Password $securePassword -Verbose
    }
}

有没有一个简单的一行程序,我可以用它来测试每台机器上的新密码,比如Invoke-Command或其他容易测试的东西。

k10s72fa

k10s72fa1#

基本上,如果Set-LocalUser没有抛出,它已经确保新密码成功设置。您可以实现Try Catch来处理可能的错误。

function SetUser1Paswword($hosts, $credential, $newPassword) {
    Invoke-Command -ComputerName $hosts -Credential $credential -ScriptBlock {
        $securePassword = ConvertTo-SecureString -String $using:newPassword -AsPlainText -Force
        try {
            Set-LocalUser -Name User1 -Password $securePassword -Verbose -ErrorAction Stop
        }
        catch {
            # handling here
        }
    }
}

至于验证密码,假设这是本地帐户,使用PrincipalContext.ValidateCredentials Method可以执行以下操作:

function SetUser1Paswword($hosts, $credential, $newPassword) {
    Invoke-Command -ComputerName $hosts -Credential $credential -ScriptBlock {
        $securePassword = ConvertTo-SecureString -String $using:newPassword -AsPlainText -Force
        try {
            Add-Type -AssemblyName System.DirectoryServices.AccountManagement
            Set-LocalUser -Name User1 -Password $securePassword -Verbose -ErrorAction Stop
            $context = [System.DirectoryServices.AccountManagement.PrincipalContext]::new(
                [System.DirectoryServices.AccountManagement.ContextType]::Machine)
            $context.ValidateCredentials('User1', $using:newPassword) # Should be True
        }
        catch {
            # handling here
        }
    }
}

相关问题