Get-Aduser -Filter will not accept a variable

前端 未结 7 797
挽巷
挽巷 2020-11-22 02:09

I\'d like to check if a user account already exists in the system.

$SamAc = Read-Host \'What is your username?\'
$User = Get-ADUser -Filter {sAMAccountName -         


        
7条回答
  •  温柔的废话
    2020-11-22 02:52

    This one bit me when I first started to work with the ActiveDirectory module, and it was a pain to figure out.

    The -Filter parameter for the ActiveDirectory module cmdlets is actually looking for a string. When you do {sAMAccountName -eq "$SamAc"} as the value, it is actually looking for "sAMAccountName -eq ""`$SamAc"""

    Basically, Powershell parses the parameter and turns its value into a string, and will not interpolate the variable. Try building the string before hand, and it should work.

    Something like this:

    $SamAc = Read-Host 'What is your username?'    
    $filter = "sAmAccountname -eq ""$SamAc"""
    $User = Get-ADUser -Filter $filter
    

提交回复
热议问题