Search code examples
powershell-3.0

How to use a variable in a filter parameter?


I am trying to pull some properties from the bitlocker active directory object, which I can do just fine using PowerShell and typing all the info in. for example

Get-ADObject -filter 'CN -like "*A3F850A4*"' `
             -Properties CanonicalName,msFVE-RecoveryPassword

Works just fine to pull the properties, but I can't figure out how to use a variable in -filter parameter and get it to return any info, this is the code I have tried.

[string]$passwordId = Read-Host `
                  "What is the first 8 charcters of the recovery password id?"
Get-ADObject -filter {CN -like $passwordId} ` 
             -Properties CanonicalName,msFVE-RecoveryPassword

Any help would be greatly appreciated, especially any info on using variables in scripts. Thanks.


Solution

  • AD cmdlets filters don't really act as usual PowerShell syntax.

    I would suggest using -LdapFilter instead (it's more portable to other tools, and most often don't differ so much from PowerShell-ish filters):

    Get-ADObject -LdapFilter "(cn=*$passwordId*)"
    

    In case you insist on using -Filter: just make sure that you will get correct string first:

    $likePattern = "*$passwordId*"
    Get-ADObject -Filter {cn -like $likePattern}
    

    Or use string notation (with some extra quotes) instead:

    Get-ADObject -Filter "cn -like '*$passwordId*'"
    

    But again: these filters won't work outside MS AD module, LDAP filter can be used in every tool I've seen for searching AD (including ADSISearcher and Quest cmdlets for AD).