1

would any of you be able to help me with the below code

$pcname = "jwang"


#We set $test as a string to be called later
$test = get-adcomputer -filter "name -like '$pcname'" | select -ExpandProperty name

#We define a null string to test our IF statement
$nothing = $null
$number = 1

if ($test -ne $null) {
    Write-Host "$pcname is currently in use"
    for($number = 1; ($test = get-adcomputer -filter "name -like '$pcname + $number'" | select -ExpandProperty name) -ne $null; $number++ ){
        Write-Host $pcname + $number
    }
}
else {
    Write-host "AD lookup complete, new PC name will be $pcname"
}

The IF statement works correctly, but the trouble starts when I add the nested FOR loop.

The end goal is to have AD tell me if the name is available or not.

Right now in AD there is

JWANG JWANG1 JWANG2 JWANG3 JWANG4

I want the for loop to eventuelly tell me that "JWANG5" is available, any help is appreciated, thank you

nick asdf
  • 85
  • 4

1 Answers1

0

The immediate problem with your code is that $pcname + $number - an expression - isn't enclosed in $(...), the subexpression operator inside your expandable (double-quoted) string ("...").

Therefore, use $($pcname + $number) or, relying on mere string interpolation, $pcname$number

An aside re testing for $null:

  • It is advisable to make $null the LHS for reliably null testing (if ($null -ne $test)), because on the RHS it acts as a filter if the LHS happens to be an array - see about_Comparison_Operators.

  • However, often - such as when objects are being returned from a command, you can simply use implicit to-Boolean conversion (if ($test)) - see the bottom section of this answer for the complete rules.


Taking a step back:

Querying AD multiple times is inefficient, and since you're already using the -like operator, you can use it with a wildcard pattern to find all matching names at once:

$pcname = 'jwang'

# Note the use of "*" to match all names that *start with* $pcname
$names = get-adcomputer -filter "name -like '$pcname*'" | select -ExpandProperty name

if ($names) { # at least one name found
    Write-Host "$pcname is currently in use"

    # Find the highest number embedded in the matching names.
    $seqNums = [int[]] ($names -replace '\D')
    # The new sequence number is the next number following the currently highest.
    $nextSeqNum = 1 + [Linq.Enumerable]::Max($seqNums)
    
    # Form the new name and output it.
    $pcname + $nextSeqNum

}
else {
    Write-host "AD lookup complete, new PC name will be $pcname"
}
mklement0
  • 382,024
  • 64
  • 607
  • 775