Can I used Get-ADComputer with some sort of RegEx type filter to only get computers with names which match specific criteria?

Darren Rose 311 Reputation points
2022-07-05T13:32:48.21+00:00

Hi

Our computer names vary depending on location and I want to be able to query AD using PowerShell and Get-ADComputer and to be able to filter the results so I get a list of just the machines from a certain office, using the normal -Filter method isn't working for me, so wondered if I can somehow use RegEx?

For example - one office may have all machines starting with A2 and then four more digits e.g. A24565 and another office would have A3 and then four more digits e.g. A34102, we also have other letters B, C, D and in odd cases the letter is followed by two known numbers and then four other digits A12 e.g. A126754

So I would supply letter and first (sometimes second) digit e.g. A2 or A12 and want filter to find all machines in AD which match so A2 would find A21234, A21235, A25454, A26787, A247575 etc, A12 would find A121234, A121111, A122222, A125678 etc

Hope this makes sense and someone can advise.

Thanks

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2022-07-05T14:56:00.773+00:00

    The regex to handle this is pretty simple:

    $firstpart = "A1"  
      
    "A11234" -match "^$firstpart\d{4}$"     # TRUE  
    "A121234" -match "^$firstpart\d{4}$"    # FALSE  
      
    $firstpart = "A12"  
      
    "A121234" -match "^$firstpart\d{4}$"   # TRUE  
    "A12123" -match "^$firstpart\d{4}$"    # FALSE  
    "A11234" -match "^$firstpart\d{4}$"    # FALSE  
    

    You can't use the -Filter to do all of this, use the "$firstpart" to limit the Get-ADComputer and then Select-Object to do the differentiation:

    Get-ADComputer -Filter "name -like '$firstpart*'" |  
        Where-Object {$_.name -match "^$firstpart\d{4}$"}  
    

    EDIT: added missing "*" to the filter string, AND added the missing <dollar sign><underbar><period> before the "name" in Where-Object.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.