0

I am trying to obtain the machine name from the user name which makes up part of the machine name, using PowerShell and Active Directory. Our PC naming convention is like this: XXXZZZ01BLOGGSJ where the last characters after the last number is the username of the PC owner.

I know that to derive the user name from the PC name using REGEX, I can do this:

"XXXZZZ01BLOGGSJ" -replace '\D*\d*(\w*)', '$1'

(result is BLOGGSJ)

What I need to be able to do is derive the computer name from the username via Active directory and have tried this and various version of this:

"BloggsJ" | % { Get-ADComputer -Server blahblah.com -Filter {name -like "xxxzzz*"} | ? "$_.Name -replace '\D*\d*(\w*)', '$1' -eq '$_'" } | select  Name

This fails with no result and I am struggling to find the correct method of doing this, any help please?

mjsqu
  • 5,151
  • 1
  • 17
  • 21
IanB
  • 271
  • 3
  • 13
  • Do you have to pipe the name into it? It'd be simpler to do something like `$UserName = 'BloggsJ'; Get-ADComputer -Server blahblah.com -Filter "name -like 'xxxzzz'" | Where {$_.Name -match $UserName} | Select -Expand Name` – TheMadTechnician Nov 26 '19 at 02:13
  • As an aside: It's best to [avoid the use of script blocks (`{ ... }`) as `-Filter` arguments](https://stackoverflow.com/a/44184818/45375). – mklement0 Nov 26 '19 at 02:36
  • Thanks @TheMadTechnician - I need to pipe it due to bulk resolutions. I will try to adapt your meth using foreach-object – IanB Nov 26 '19 at 03:10
  • I managed it like this: $UserList | %{$UserName = $_ ; Get-ADComputer -Server blahblah.com -Filter "name -like 'xxxzzz*'" | ? {$_.Name -match $UserName}} | Select -Expand Name Thanks a lot! :-) – IanB Nov 26 '19 at 07:41
  • 1
    You might find your script performs better if you capture the result of Get-ADComputer into a variable so you only query Active Directory once. At present you're running your AD query for every user, but almost certainly getting the same list of computers each time. – mclayton Nov 26 '19 at 09:26

0 Answers0