PowerShell: NEW-ADGroup /在Active Directory中创建多个组/ -Path参数问题.



简而言之,错误如下:错误下面是脚本:

#
Import-Module ActiveDirectory

#
$ADGroups = Import-Csv C:tempNewGroups.csv -Delimiter ";"
#Create group in "Users"
$OU = "CN=Users"
$Path2 = "CN=Users,DC=master,DC=int"
# Loop through each row containing group details in the CSV file
foreach ($Group in $ADGroups) {
#Read group data from each field in each row and assign the data to a variable as below
$groupName = $Group.groupname
$SAM = $Group.SAMName
$gCategory = $Group.grouptype
$gScope = $Group.groupscope
$dispName = $Group.teamname
$Path = $Group.path
$desc = $Group.description
# Check to see if the user already exists in AD
if (Get-ADGroup -F { SamAccountName -eq $groupName }) {

# Group existance warning
Write-Warning "A $groupName group  already exists in Active Directory."
}
else {
Write-Host "This is SAM: $SAM"
Write-Host "This is Path: $Path"

New-ADGroup `
-Path $Path `
-Name "$groupName" `
-GroupScope $gScope `
-SamAccountName $SAM `
-GroupCategory $gCategory `
-DisplayName $dispName `
-Description  $desc

# If group is created, show message.
Write-Host "The $groupName group is created." -ForegroundColor Cyan
}
}
Read-Host -Prompt "Press Enter to exit"

脚本png版本这是。csv文件:CSV文件

问题在于"Path"参数。如果我只跳过它,则会添加组,显然CN=Users将是默认的,这与MS web: https://learn.microsoft.com/en-us/powershell/module/activedirectory/new-adgroup?view=windowsserver2022-ps上描述的完全相同。但我在很多方面都尝试过使用"路径"这个词。变量甚至不止一个,CN=Users和DC=…但它总是倾向于添加"name"中的内容;参数到路径为CN。它组合了"Name"与"Path"在错误屏幕上有两个CN:"CN=Designers,CN=Users,DC=masters,DC=int"我已经尝试使用双引号或没有引号传递变量到路径参数-相同的结果。我还手动输入了路径,省略了使用变量将值传递给path -相同。我不明白为什么?是否读取。csv文件不正确?如果我用以下简单的脚本:工作更简单的脚本一点问题都没有……我发现的文章中,用户已经传递的值路径参数实际上相同的方式:Powershell与活动目录创建组没有问题……

看看您在评论中回答的内容,我认为错误源于您使用所有这些反引号使用New-ADGroupcmdlet的方式。(特别是第一个反号)。

尝试在需要很多参数的cmdlet上使用Splatting。

这样你就不需要那些可怕的反引号,而代码又保持清晰和易于维护。

Import-Module ActiveDirectory
$ADGroups = Import-Csv -Path 'C:tempNewGroups.csv' -Delimiter ";"
# Loop through each row containing group details in the CSV file
foreach ($Group in $ADGroups) {
$groupName = $Group.Groupname  # for convenience
if (Get-ADGroup -Filter "SamAccountName -eq '$groupName'") {
# Group existance warning
Write-Warning "A $groupName group already exists in Active Directory."
}
else {
# build a Hashtable for splatting the parameters 
# (no need to put all in separate variables first)
$groupParams = @{
Path           = $Group.Path
Name           = $groupName
DisplayName    = $Group.TeamName
SamAccountName = $Group.SAMName
Description    = $Group.Description
GroupScope     = $Group.Groupscope
GroupCategory  = $Group.Grouptype
ErrorAction    = 'Stop'
}
# create the new group
try {
New-ADGroup @groupParams
Write-Host "The $groupName group is created." -ForegroundColor Cyan
}
catch {
# write the error to console and proceed with the next group
Write-Warning "Error: $($_.Exception.Message)"
}
}
}