PowerShell用戶認證Function實例代碼
更新時間:2016年09月15日 09:47:58 作者:破狼
這篇文章主要介紹了PowerShell用戶認證Function的資料,并附實例代碼,幫助大家學習理解,有需要的小伙伴可以參考下
在最近工作中遇到對用戶驗證,需要根據(jù)用戶名和密碼驗證用戶是否合法。在外文網(wǎng)站找到的這段代碼,在這里分享給大家,如果你也需要用戶驗證的話,那么可以直接copy使用,現(xiàn)在沒地方用,也可以收藏備用。
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 “用戶名” “密碼” “用戶域”,第三個參數(shù)“用戶域”為可選參數(shù),返回為布爾類型。
以上就是對PowerShell 用戶認證 Function的資料整理,后續(xù)繼續(xù)補充相關資料,謝謝大家對本站的支持!

