创建新的AD用户并计数(如果找到) [英] Create New AD-User and Count if found

查看:103
本文介绍了创建新的AD用户并计数(如果找到)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加脚本来帮助自动创建帐户。它将查询用户的AD,如果找到该用户,请在末尾添加一个数字,然后执行另一个查询。同样,如果找到,则将数字从2改为3。

I am attempting to implment a script to help automate account creation. It will query AD for a user and if found, add a number to the end, and then do another query. Again, if found, change the number from say 2 - 3.

就像以下用户已经在AD中一样:

Such as if the following users are already in AD:


  • 史密斯,詹姆斯W = SmithJW

  • 史密斯,Jason W = SmithJW2

我想添加一个新用户Smith,JacobW。首先应在AD中查询SmithJW,然后如果找到,则添加2,如果找到,则添加3。我得到了两个下面的工作基本上可以做到,但是由于找到了SmithJW2,它只是在该名称上添加了计数器。这样我就可以回到SmithJW22。

I want to add a new user, Smith, Jacob W. It should query AD for SmithJW at first, then if found, add a 2, and if found, add a 3. What I got two work below, essentially does it, but due to it finding a SmithJW2, it just adds the counter to that name. So I would get back SmithJW22.

代码:

$user = "smithjw"

Do{
    $adcheck = $null
    $counter = 2

 Try {$adcheck = Get-Aduser $user
     }  
  Catch {If($adcheck.SamAccountName-eq$null){$NewUserName = $user}
        }

    If($adcheck.SamAccountName-ne$null){$user = $user+$counter++}
  }until($adcheck.SamAccountName-eq$null)

因此,我正在寻找一种方法,如果我找到一个用户(即SmithJW2)先删除 2,然后添加计数器。

So I'm looking for a way to if I find a user (i.e. SmithJW2) to remove the "2" first, then add the counter.

希望这是有道理的。谢谢。

Hopefully this makes sense. Thanks.

推荐答案

Get出现其他问题的情况下,该解决方案不涉及try catch语句。 -AdUser

$accountname = "account"
$count = $null
do{
    $query = "(&(objectClass=user)(samaccountname=$accountname$count))"
    $result = ([adsisearcher]$query).FindOne()
    If($result){If($count -eq $null){$count = 2}Else{$count++}}
}While($result)

Write-Host "The account name you should use is: $accountname$count"

[adsisearcher] $ query)。如果未找到对象,FindOne()将返回 $ null 。如此循环直到 $ result 为空/空。我对 $ count 的处理方式不满意,但它确实有效。如果有返回的用户,则会更改 $ count 。如果存在 $ count ,则需要更改。自从2开始,我们需要检查是否是第一次设置变量。还有其他方法,但这是一致且可读的。 (我有一个使用 Get-Variable 的想法,但这不必要地复杂。)

[adsisearcher]$query).FindOne() would return $null if there is not object found. So loop until $result is empty/null. I'm not happy with how the $count is handled but it does work. The $count is changed if there is a returned user. If there is the $count needs to be changed. Since you start 2 we need to check if its the first time the variable is going to be set. There are other ways but this is consistent and readable. (I have an idea using Get-Variable but it's needlessly complicated.)

这篇关于创建新的AD用户并计数(如果找到)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆