has encountered a user authentication in its recent work and needs to verify that the user is legitimate based on the user name and password. In the foreign language website found this piece of code, here to share to everyone, if you also need user verification, then you can directly copy use, now there is no place to use, you can also collect spare.
Function test-usercredential {[cmdletbinding ()] [OutputType ([System.Boolean])] param ([Parameter (mandatory = $true)] [Validatenotnullorempty ()] [System.String] $Username, [Parameter (mandatory= $true)] [Validatenotnul
Lorempty ()] [System.String] $Password, [Parameter ()] [Switch] $Domain) Begin {
$assembly = [System.reflection.assembly]::loadwithpartialname (' System.DirectoryServices.AccountManagement ')} Process {try {$system = Get-wmiobject-class Win32_ComputerSystem if ($Domain) {if (0), 2-contains $system.
DomainRole) {Throw ' This computer isn't a member of a domain. ' else {$principalContext = New-object-typename System.DirectoryServices.AccountManagement.PrincipalContext ' Domain ', $system. Domain}} else {$principalContext = New-object-typename System.DirectoryServices.AccountMan Agement. PrincipalcontExt ' Machine ', $env: COMPUTERNAME} return $principalContext. Validatecredentials ($Username, $Passwo RD)} catch {throw ' Failed to test user credentials. The error was: ' {0} '. '-F $_}}
Easy to use: test-usercredential "username" "Password" "User domain", the third parameter "user domain" is an optional parameter, and returns to the Boolean type.
The above is the PowerShell user authentication function data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!