将“下一个可用的AD计算机”添加到Power-Shell脚本

时间:2019-07-11 17:21:24

标签: powershell active-directory

当前,我正在尝试将功能添加到Powershell脚本中,以实现以下目标:

在尚未添加到域的计算机上,请它根据用户的输入在本地AD服务器(非Azure)上搜索下一个可用名称。

过去,我尝试使用数组失败,但是我想在其中使用Get-ADComputer cmdlet,但是我不确定如何实现它。

boost

上面的代码是较大的脚本的一部分,该脚本分析计算机名称并将其最终分配给正确的OU。

我们的命名方案如下:BTS-ONE-LAP-000

就是这样:部门-位置-设备类型-设备数量

然后,代码将采用第一部分“ BTS-ONE”并将其解析为应该去的正确OU,然后使用Add-Computer cmdlet对其进行分配。它还会将计算机重命名为用户键入的($ pcname)。

因此,在解析名称之前,我希望它可以搜索AD中的所有当前名称。

因此,用户可以输入:“ BTS-ONE-LAP”,它将自动找到下一个可用的设备计数,并将其添加到名称中。因此,它将自动生成“ BTS-ONE-LAP-041”。

添加的注释:

我用过boost,输出是

$usrinput = Read-Host 'The current PC name is $pcname , would you like to rename it? (Y/N)'
if($usrinput -like "*Y*") {
    Write-Output ""
    $global:pcname = Read-Host "Please enter the desired PC Name"
    Write-Output ""

    $userinput = Read-Host "You've entered $pcname, is this correct? (Y/N)"
    if($usrinput -like "*N*") {
    GenName
    #name of the parent function
}
Write-Output ""

我不知道如何解析它,因此代码知道BTS-ONE-LAP-003可用(我对数组很糟糕)。

2 个答案:

答案 0 :(得分:1)

$list = (Get-ADComputer -Filter 'Name -like "BTS-ONE-LAP-*"' | Sort-Object Name[-1])

$i = 1
$found = $false
Foreach($Name in $list.Name)
{
    while($i -eq [int]$Name.Split("-")[3].Split("-")[0])
    {
        $i++
    }
}
$i

上面的代码将遍历列表中的每个名称,并在发现其中的第三台计算机不是3号计算机时停止运行。

示例:

BTS-ONE-LAP-001 | $i = 1
BTS-ONE-LAP-002 | $i = 2
BTS-ONE-LAP-006 | $i = 3

将BTS-ONE-LAP-006拆分为006,并将其转换为整数,使其为6。 由于6不等于3,因此我们知道BTS-ONE-LAP-003可用。

答案 1 :(得分:1)

另一种方法可能是创建如下所示的可重用函数:

function Find-FirstAvailableNumber ([int[]]$Numbers, [int]$Start = 1) {
    $Numbers | Sort-Object -Unique | ForEach-Object {
        if ($Start -ne $_) { return $Start }
        $Start++
    }
    # no gap found, return the next highest value
    return $Start
}

# create an array of integer values taken from the computer names
# and use the helper function to find the first available number
$numbers = (Get-ADComputer -Filter 'Name -like "BTS-ONE-LAP-*"') | 
            ForEach-Object { [int](([regex]'(\d+$)').Match($_.Name).Groups[1].Value) }

# find the first available number or the next highest if there was no gap
$newNumber = Find-FirstAvailableNumber $numbers

# create the new computername using that number, formatted with leading zero's
$newComputerName = 'BTS-ONE-LAP-{0:000}' -f $newNumber

使用示例列表,$newComputerName将变成BTS-ONE-LAP-003

请注意,并非用户可以用Read-Host输入的所有内容都是有效的计算机名称。您应该添加一些检查以查看提议的名称是否可接受,或者跳过提议的名称alltogehter,因为所有计算机均被命名为“ BTS-ONE-LAP-XXX”。
参见custom type adapter