在ADSISearcher中使用变量

时间:2018-08-21 13:42:04

标签: powershell

我正在使用PowerShell自动执行新的计算机帐户请求。我的第一步是能够找到下一个可用的计算机号码。我们的命名约定是Department + DeviceType + Year + 3DigitNumber。现在,我正在使用PWNB18001和PWNB18002。我正在努力让我的脚本输出PWNB18003。我遇到的问题是将变量传递到ADSISearcher cmdlet。这是我的脚本,之所以有效,是因为我对搜索条件(PWNB18)进行了硬编码:

$AnotherComputer = "y"

while ($AnotherComputer.ToLower() -ne "n") {
    $Department = Read-Host -Prompt 'Department (CD,HS,PW,etc.)'
    $Type = Read-Host -Prompt 'Device Type (DT,NB,TB)'
    $Year = Read-Host -Prompt 'Year of Device (16,17,18,etc.)'
    $NameSearch = ($Department + $Type + $Year)
    $Prefix = ($Department + $Type)

    $searcher = [ADSISearcher]'(&(objectCategory=computer)(name=PWNB18*))'
    $searcher.PageSize = 1000
    $last = $searcher.FindAll() |
            ForEach-Object { [int]($_.Properties.name -replace '\D').Trim() } |
            Sort-Object |
            Select-Object -Last 1
    $digitLength = "$last".Length
    $NewComputerName = "{0}{1:D$digitLength}" -f $Prefix,($last+1)

    Write-Host "Department: "$Department
    Write-Host "Type: "$Type
    Write-Host "Year: "$Year
    Write-Host "NameSearch: "$NameSearch
    Write-Host "Prefix: "$Prefix
    Write-Host "Searcher: "$searcher
    Write-Host "Last: "$last
    Write-Host "DigitLength: "$digitLength
    Write-Host "NewComputerName: "$NewComputerName
    #Write-Host "Number: "$number

    $AnotherComputer = Read-Host -Prompt 'Create another computer account? (y/n)'
}

我添加了所有Write-Host行以帮助发现问题,而绝对是第11行$searcher = [ADSISearcher]...。我发布脚本的方式非常有效。这是PowerShell的输出:

PS C:\Temp> .\NewComputerAccount.ps1
Department (CD,HS,PW,etc.): PW
Device Type (DT,NB,TB): NB
Year of Device (16,17,18,etc.): 18
Department:  PW
Type:  NB
Year:  18
NameSearch:  PWNB18
Prefix:  PWNB
Searcher:  System.DirectoryServices.DirectorySearcher
Last:  18002
DigitLength:  5
NewComputerName:  PWNB18003
Create another computer account? (y/n): n
PS C:\Temp>

一旦我尝试在第11行使用变量,例如...(name=$NameSearch*)...,就会得到以下输出:

PS C:\Temp> .\NewComputerAccount.ps1
Department (CD,HS,PW,etc.): PW
Device Type (DT,NB,TB): NB
Year of Device (16,17,18,etc.): 18
Department:  PW
Type:  NB
Year:  18
NameSearch:  PWNB18
Prefix:  PWNB
Searcher:  System.DirectoryServices.DirectorySearcher
Last:
DigitLength:  0
NewComputerName:  PWNB1
Create another computer account? (y/n): n
PS C:\Temp>

添加变量时我在做什么错?我的语法有误吗?

0 个答案:

没有答案