I have encountered verification of users in my recent work and need to verify whether the user is legal based on the user name and password. This code found on a foreign language website is shared with you here. If you also need user verification, you can use it directly. There is no place to use it now, and you can also bookmark it for later use.
Function Test-UserCredential { [CmdletBinding()] [OutputType([System.Boolean])] param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.String] $Username, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [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 is not a member of a domain.' } else { $principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Domain', $system.Domain } } else { $principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Machine', $env:COMPUTERNAME } return $principalContext.ValidateCredentials($Username, $Password) } catch { throw 'Failed to test user credentials. The error was: "{0}".' -f $_ } }}It is very simple and convenient to use: Test-UserCredential "Username", "Password", "User Domain", the third parameter "User Domain" is an optional parameter, and returns to Boolean type.
The above is a compilation of the information on PowerShell user authentication function. We will continue to add relevant information in the future. Thank you for your support for this site!