2

With following script I'd like to add a group to an AD user, but it doesn't do it, and I get no error.

param($Userid,$AdditionalGroup)

# Get user
$User = Get-ADUser `
    -Filter "SamAccountName -eq $Userid"

# Add comment
Add-ADGroupMember `
    -Identity $AdditionalGroup `
    -Members $User
Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Michael
  • 6,823
  • 11
  • 54
  • 84

3 Answers3

2

Filtering like that didn't work for me (and generated an error), however adding ' before and after $Userid did the trick.

param($Userid,$AdditionalGroup)

# Get user
$User = Get-ADUser `
    -Filter "SamAccountName -eq '$Userid'"

# Add comment
Add-ADGroupMember `
    -Identity $AdditionalGroup `
    -Members $User
notjustme
  • 2,376
  • 2
  • 20
  • 27
1

As you're only doing a straight -eq match on sAMAccountName you don't need to use -Filter, the Identity param will accept this along with other inputs:

  • A distinguished name
  • A GUID (objectGUID)
  • A security identifier (objectSid)
  • A SAM account name (sAMAccountName)

(documentation link)

Which makes your code very simple:

$User = Get-ADUser -Identity $Userid

To simplify it even further, you don't even need to use Get-ADUser at all!

Add-ADGroupMember -Members (link) accepts the same parameters as I mentioned for Identity ...

So you can use $UserID directly:

param($Userid,$AdditionalGroup)

Add-ADGroupMember -Identity $AdditionalGroup -Members $UserID
Community
  • 1
  • 1
henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
0

This will also work (without the single quotes):

$User = Get-ADUser -Filter {SamAccountName -eq $Userid}
henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
mOjO
  • 98
  • 6
  • 1
    Yes, but it's [better to avoid the use of script blocks as the `-Filter` argument](https://stackoverflow.com/a/44184818/45375) – mklement0 Mar 15 '18 at 09:37
  • 1
    Funny, @mklement0 you beat me to it while I was looking for that particular post of yours. :) – notjustme Mar 15 '18 at 09:38
  • 1
    $Mind = "BLOWN!" – mOjO Mar 15 '18 at 09:49
  • 1
    you know. this is probably why i so constantly get ticked off with the -Filter parameter and instead just end up using | ?{$_.whatever -eq "whatever"} instead. – mOjO Mar 15 '18 at 09:56