分享一段PowerShell用户认证Function
在最近工作中遇到对用户验证,需要根据用户名和密码验证用户是否合法。在这里分享给大家,如果你也需要用户验证的话,那么可以直接copy使用,现在没地方用,也可以收藏备用,。[*]function Test-UserCredential {
[*]
[*] )]
[*]
[*] param(
[*]
[*]
[*]
[*] $Username,
[*]
[*]
[*]
[*] $Password,
[*]
[*]
[*]
[*] $Domain
[*]
[*] )
[*]
[*] Begin {
[*]
[*] $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 $_
[*]
[*] }
[*]
[*] }
[*]
[*]}
[*]
使用很简单方便:Test-UserCredential“用户名” “密码” “用户域”,第三个参数“用户域”为可选参数。
页:
[1]