在最近工作中遇到对用户验证,需要根据用户名和密码验证用户是否合法。在外文网站找到的这段代码,在这里分享给大家,如果你也需要用户验证的话,那么可以直接copy使用,现在没地方用,也可以收藏备用,
1 Function Test-UserCredential {
2
3 [CmdletBinding()] [OutputType([System.Boolean])]
4
5 param(
6
7 [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
8
9 [System.String] $Username,
10
11
12
13
14 [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
15
16 [System.String] $Password,
17
18
19
20 [Parameter()]
21
22 [Switch] $Domain
23
24 )
25
26
27
28 Begin {
29
30 $assembly = [system.reflection.assembly]::LoadWithPartialName('System.DirectoryServices.AccountManagement')
31
32 }
33
34
35
36 Process {
37
38 try {
39
40 $system = Get-WmiObject -Class Win32_ComputerSystem
41
42 if ($Domain) {
43
44 if (0, 2 -contains $system.DomainRole) {
45
46 throw 'This computer is not a member of a domain.'
47
48 } else {
49
50 $principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Domain', $system.Domain
51
52 }
53
54 } else {
55
56 $principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Machine', $env:COMPUTERNAME
57
58 }
59
60
61
62 return $principalContext.ValidateCredentials($Username, $Password)
63
64 }
65
66 catch {
67
68 throw 'Failed to test user credentials. The error was: "{0}".' -f $_
69
70 }
71
72 }
73
74 }
2
3 [CmdletBinding()] [OutputType([System.Boolean])]
4
5 param(
6
7 [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
8
9 [System.String] $Username,
10
11
12
13
14 [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
15
16 [System.String] $Password,
17
18
19
20 [Parameter()]
21
22 [Switch] $Domain
23
24 )
25
26
27
28 Begin {
29
30 $assembly = [system.reflection.assembly]::LoadWithPartialName('System.DirectoryServices.AccountManagement')
31
32 }
33
34
35
36 Process {
37
38 try {
39
40 $system = Get-WmiObject -Class Win32_ComputerSystem
41
42 if ($Domain) {
43
44 if (0, 2 -contains $system.DomainRole) {
45
46 throw 'This computer is not a member of a domain.'
47
48 } else {
49
50 $principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Domain', $system.Domain
51
52 }
53
54 } else {
55
56 $principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Machine', $env:COMPUTERNAME
57
58 }
59
60
61
62 return $principalContext.ValidateCredentials($Username, $Password)
63
64 }
65
66 catch {
67
68 throw 'Failed to test user credentials. The error was: "{0}".' -f $_
69
70 }
71
72 }
73
74 }
使用很简单方便:Test-UserCredential “用户名” “密码” “用户域”,第三个参数“用户域”为可选参数,返回为布尔类型。
本文转自破狼博客园博客,原文链接:http://www.cnblogs.com/whitewolf/archive/2012/06/09/2543584.html,如需转载请自行联系原作者