English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
I encountered user verification in my recent work, which requires verifying whether a user is legitimate based on username and password. I found this code on a foreign website and am sharing it with everyone here. If you also need user verification, you can directly copy and use it. If there is no place to use it now, you can also save it for future reference.
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.' } $principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Domain', $system.Domain } } $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 the return type is boolean.
This is the material compilation of PowerShell User Authentication Function. We will continue to supplement relevant information in the future, thank you for your support to this site!
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)