cne*_*son 2 powershell active-directory powershell-5.0
我正在我的“复制 AD 用户”powershell 脚本中进行错误检查。我使用表格来询问特定信息,这个问题的目的是确保我正确地进行错误检查。
IF ($Username.Text -eq Get-ADUser ($Username.Text))
{$wshell = New-Object -ComObject Wscript.Shell
$wshell.PopUp("This username already exists. Please choose another")}
Run Code Online (Sandbox Code Playgroud)
的$Username.Text是,其中用于新帐户的用户名正在从拉文本框中。我想通过 AD 运行它以查看该用户名是否已存在,如果存在则显示一条消息。
我是否以正确的方式处理它?
问题Get-ADUser -Identity $Username.Text是当它找不到某些东西时它会抛出异常。如果你想避免这种情况,你必须使用过滤器进行搜索:
if (!(Get-ADUser -Filter "sAMAccountName -eq '$($Username.Text)'")) {
Write-Host "User does not exist."
}
Run Code Online (Sandbox Code Playgroud)
否则,您可以执行以下操作:
try {
Get-ADUser -Identity $Username.Text
$UserExists = $true
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityResolutionException] {
Write-Host "User does not exist."
$UserExists = $false
}
Run Code Online (Sandbox Code Playgroud)
这是一种快速方法:
([ADSISearcher] "(sAMAccountName=kendyer)").FindOne()
Run Code Online (Sandbox Code Playgroud)
如果没有返回结果,则说明未找到用户帐户。
作为一个函数:
function Test-ADUser {
param(
[Parameter(Mandatory = $true)]
[String] $sAMAccountName
)
$null -ne ([ADSISearcher] "(sAMAccountName=$sAMAccountName)").FindOne()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34869 次 |
| 最近记录: |