在最近工作中遇到對用戶驗證,需要根據用戶名和密碼驗證用戶是否合法。在外文網站找到的這段代碼,在這里分享給大家,如果你也需要用戶驗證的話,那麼可以直接copy使用,現在沒地方用,也可以收藏備用。
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 $_ } }}使用很簡單方便:Test-UserCredential “用戶名” “密碼” “用戶域”,第三個參數“用戶域”為可選參數,返回為布爾類型。
以上就是對PowerShell 用戶認證Function的資料整理,後續繼續補充相關資料,謝謝大家對本站的支持!