代码改变世界

分享一段PowerShell用户认证Function

  破狼  阅读(2139)  评论(1编辑  收藏  举报

      在最近工作中遇到对用户验证,需要根据用户名和密码验证用户是否合法。在外文网站找到的这段代码,在这里分享给大家,如果你也需要用户验证的话,那么可以直接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  “用户名” “密码” “用户域”,第三个参数“用户域”为可选参数,返回为布尔类型。

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2010-06-09 jQuery系列之目录汇总
2010-06-09 关于jConfirm回传的解决方案
点击右上角即可分享
微信分享提示