Home > OS >  Regex in Get-ADComputer -Filter
Regex in Get-ADComputer -Filter

Time:07-26

Im trying to filter a very specific group of computers in my network via Powershell. I have a ps1 script that filters those computer accounts with this regex pattern ^ORD\d{3}\$$ and it's working right now in a scheduled task.

The thing is that I have tried to filter with that pattern in "Get-ADComputer -Filter " but it doesn't work.

I have tried so many times and the best i can get is this pattern ORD*$. As you may see, it's not even close of what I want.

Here goes my question, Which regex caracters or special caracters can I use in a -Filter parameter?

Thanks in advance.

CodePudding user response:

The GetADComputer's '-filter' filter is an LDAPFilter see details here

https://docs.microsoft.com/en-us/previous-versions/windows/server/hh531527(v=ws.10)

So it doesn't support regex, but what you can do is get a list of all the computers

https://morgantechspace.com/2016/02/get-list-of-computers-in-ad-using-powershell.html

then do the regex on the result list

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-string?view=powershell-7.2

Get-ADComputer -Filter * -Properties * |
Select -Property Name | 
Export-CSV "C:\tmp\we-are-all-machines.csv" -NoTypeInformation -Encoding UTF8

Select-String -Path "C:\tmp\we-are-all-machines.csv" -Pattern "^ORD\d{3}\$$"
  • Related