简体   繁体   中英

Adding groups to AD user with a ps1 script

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

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

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

这也将起作用(不使用单引号):

$User = Get-ADUser -Filter {SamAccountName -eq $Userid}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM