简体   繁体   中英

Powershell - Adding users to AD group from a CSV file

I know this has been done to death but im useing this as a learning experience with powershell. Could someone take a look at my code and tell me where i am going wrong? Noob code warning!

# 
# Add User to an AD Group
# 
# 

# get arguements and quit if they dont exist 
$CSV = $args[0]
$GROUP = $args[1]
if (! $CSV) {
Write-Host "Please format this command as 'AddUsersToGroup <csv file> <AD group>'"
Write-Host "CSV file must have the header 'UserName' with AD usernames following"
exit
}


# Read csv file for users and add to AD group
Import-module ActiveDirectory  
Import-CSV "$CSV" | % {  

# Get existing users from AD group
$ExistingGroup = "Get-ADGroupMember $GROUP | Select-Object SamAccountName"

# create new array removing existing users from the csv
$NewGroup = $ExistingGroup | where {$CSV -notcontains $_}

# add the users to the AD Group from the new array
Add-ADGroupMember -Identity $NewGroup -Member $_.UserName
exit
}

try delete double quote here:

$ExistingGroup = Get-ADGroupMember $GROUP | Select-Object SamAccountName

with quote you're assign a string value to variable not the results of your commands

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