在最近工作中遇到对用户验证,需要根据用户名和密码验证用户是否合法。在外文网站找到的这段代码,在这里分享给大家,如果你也需要用户验证的话,那么可以直接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/
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。该文章也同时发布在我的独立博客中-个人独立博客、博客园--破狼和51CTO--破狼。http://www.cnblogs.com/whitewolf/archive/2012/06/09/2543584.html