分享一段PowerShell用户认证Function

      在最近工作中遇到对用户验证,需要根据用户名和密码验证用户是否合法。在外文网站找到的这段代码,在这里分享给大家,如果你也需要用户验证的话,那么可以直接copy使用,现在没地方用,也可以收藏备用,LY6DR3ISJE0)6K)L)]~VIZK 

复制代码
 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 }
复制代码

      

使用很简单方便:Test-UserCredential  “用户名” “密码” “用户域”,第三个参数“用户域”为可选参数,返回为布尔类型。


作者:破  狼 
出处:http://www.cnblogs.com/whitewolf/ 
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。该文章也同时发布在我的独立博客中-个人独立博客博客园--破狼51CTO--破狼。http://www.cnblogs.com/whitewolf/archive/2012/06/09/2543584.html


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值