在最近工作中遇到對用戶驗證,需要根據(jù)用戶名和密碼驗證用戶是否合法。在外文網(wǎng)站找到的這段代碼,在這里分享給大家,如果你也需要用戶驗證的話,那么可以直接copy使用,現(xiàn)在沒地方用,也可以收藏備用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
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ù)補充相關(guān)資料,謝謝大家對本站的支持!