Search code examples
powershellactive-directoryadmin

Find missing prefix for computer name


I am trying to write a script that will automatically find the full asset tag based on the ID of the computer.

For example:

The PC ID is: PC0001

$computerID = PC0001;

But the full asset tag that I need is: WKSPC0001

But these asset tags might have different prefixes, for example DSTPC0002, TBLPC0003 etc. But they all have common pattern: Prefix+PC+ID (the ID is unique and there is no repetition).

I am trying to figure out how to write a query for that in PowerShell but I cant figure it out. I've tried:

$current = Get-ADComputer -Filter {Name -like "*$computerId.text"} |
           Select -Property Name

But I was having issues to get it to work.

What am I doing wrong?


Solution

  • A few observations.

    • You want $computerId to be a string, so $computerID = "PC0001";
    • The filter expression for Get-ADComputer is expected to be a string also, using curly braces here is wrong. So Get-ADComputer -Filter "..."
    • Powershell can expand variable values in strings, but it only does that in double-quoted strings. "Name -like '$variable'" will work, but 'Name -like "$variable"' won't.
    • There is no .text in your $computerId variable. It's a plain string.

    Knowing that, try:

    $current = Get-ADComputer -Filter "Name -like '*$computerId'"
    

    Other notes

    Don't do ... | Select Name unless you really must. Storing the computer object itself will be more versatile. You can do $current.Name when you need it anytime.

    Querying the AD with a filter that begins with a wildcard is slow. Try to avoid.

    If you have a fixed number of possible prefixes, an LDAP filter like the following will be much faster:

    $current = Get-ADComputer -LDAPFilter "(|(cn=WKS$computerId)(cn=DST$computerId)(cn=TBL$computerId))"