Local Users Search Filter

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Milos Ostojic Milos Ostojic 10 months ago.

  • Author
    Posts
  • #34957
    Profile photo of Milos Ostojic
    Milos Ostojic
    Participant

    I'm creating a LocalUser module based on System.DirectoryServices.AccountManagement namespace and can't make filter to work.
    I'm using following code
    `
    Add-Type -AssemblyName System.DirectoryServices.AccountManagement
    $ctype = [System.DirectoryServices.AccountManagement.ContextType]::Machine
    $context = [System.DirectoryServices.AccountManagement.PrincipalContext]::new($ctype,$env:COMPUTERNAME)
    $user = [System.DirectoryServices.AccountManagement.UserPrincipal]::new($context)
    $user.SamAccountName = "*"
    $filter = [System.DirectoryServices.AccountManagement.PrincipalSearcher]::new()
    $filter.QueryFilter = $user
    $filter.FindAll()

    `
    Ant it works only if property asigned to UserPrincipal object is *. *a, a*, or even a full name of the user, without wildcards, just doesn't work. The same thing happens when I'm using '?'. Help?
    Thanks

  • #34968
    Profile photo of Liam Kemp
    Liam Kemp
    Participant

    Hi Milos,
    I'm assuming you mean at this point

     $user.SamAccountName = "*" 

    From what I can see, this is exactly how it should operate. Without the wildcards, essentially what you are doing is looking for any users whose SamAccountName is exactly equal to whatever you put there. I note it also seems to be case sensitive.
    If you are looking to get input from the user for what to search for, it would be trivial to store that user input in a variable, and then wrap the variable with wildcard i.e.

     $input = Read-Host
    $user.SamAccountName = "*$input*"
    

    Hope this is of some help. I don't know if there is another way. You can get some of the user information using the Win32_UserAccount. wmi/cim object
    If you can explain exactly what you are wanting to achieve, I/someone might be able to find a better answer.

    Cheers

  • #34970
    Profile photo of Milos Ostojic
    Milos Ostojic
    Participant

    I'm building a cmdlet, something like get-aduser (or more like get-qaduser because of the way filtering should work). $samaccountname is passed as parameter but for some reason searcher works only with '*' or '?' when it finds all users. When I pass SAM without wildcards or a few letters with wildcards he finds nothing. I didn't know that it's case sensitive though, so thanks for that. Enabled, badpwdcount and other properties that have no need for wildcards work well...

    Thanks again

  • #35039
    Profile photo of Milos Ostojic
    Milos Ostojic
    Participant

    Actually not being aware of case sensitiveness was the root of my problem. It all works now. Thank you again!

You must be logged in to reply to this topic.