Powershell-将用户从CSV文件添加到广告组

Powershell-将用户从CSV文件添加到广告组,powershell,powershell-2.0,Powershell,Powershell 2.0,我知道这件事已经做得很惨了,但我用它来学习powershell。有人能看看我的代码,告诉我哪里出了问题吗?Noob代码警告 # # 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

我知道这件事已经做得很惨了,但我用它来学习powershell。有人能看看我的代码,告诉我哪里出了问题吗?Noob代码警告

# 
# 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
}

请尝试在此处删除双引号:

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

使用quote可将字符串值分配给变量,而不是命令的结果

请尝试删除双引号:

$ExistingGroup = Get-ADGroupMember $GROUP | Select-Object SamAccountName
使用quote将字符串值分配给变量,而不是命令的结果

Add-ADGroupMember:无法将“System.Object[]”转换为“Microsoft.ActiveDirectory.Management.ADGroup”类型,需要按参数“Identity”进行数据转换。不支持指定的方法。在C:\temp\AddUsersToGroup.ps1:27 char:28+Add-ADGroupMember-Identity Add-ADGroupMember:无法将“System.Object[]”转换为类型“Microsoft.ActiveDirectory.Management.ADGroup”,需要按参数“Identity”进行数据转换。不支持指定的方法。在C:\temp\AddUsersToGroup.ps1:27 char:28+添加ADGroupMember-Identity