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
}
Add-ADGroupMember : Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADGroup' require d by parameter 'Identity'. Specified method is not supported. At C:\temp\AddUsersToGroup.ps1:27 char:28 + Add-ADGroupMember -Identity <<<< $NewGroup -Member $_.UserName + CategoryInfo : InvalidArgument: (:) [Add-ADGroupMember], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember