我的任务是在2016 Windows Server上为Active Directory创建一组安全组。目前我有这个代码
$CSVLocation = Read-Host -Prompt "Please enter the path of CSV file"
$Groups = Import-CSV $CSVLocation
foreach ($Group in $Groups) {
$Groupname = Get-ADGroup -Identity $Group.Group
if ($Groupname -eq $null) {
New-ADGroup -Name $Group.Group -Path $group.GroupLocation -GroupScope $Group.GroupType
}
else {
echo "Group existes"
}
}
如果该组不存在,则代码正在尝试创建组,如果确实存在,则跳过CSV中的条目。到目前为止,所有这一切都会导致Get-ADGroup错误无法找到该组,然后跳过它的创建。
CSV格式如下:
Group,GroupType,GroupLocation
Group01,Universal,"OU=Test,DC=Example,DC=Local"
Group02,Universal,"OU=Test,DC=Example,DC=Local"
Group03,Universal,"OU=Test,DC=Example,DC=Local"
错误讯息:
Get-ADGroup : Cannot find an object with identity: 'AU-CTX-RDP' under: 'DC=Example,DC=local'.
At C:\Users\Administrator\Desktop\Scripts\Import Groups.ps1:10 char:14
+ $Groupname = Get-ADGroup -Identity $Group.Group
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (AU-CTX-RDP:ADGroup) [Get-ADGroup], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADGroup
答案 0 :(得分:2)
如果查询不存在的组,则会出现terminatig错误。所以脚本执行会停止。为避免这种情况,您可以使用-ErrorAction SilentlyContinue
。这样它应该实际工作
$CSVLocation = Read-Host -Prompt "Please enter the path of CSV file"
$Groups = Import-CSV $CSVLocation
foreach ($Group in $Groups) {
if (-not (Get-ADGroup -Filter "Name -eq '$($group.Group)'" -ErrorAction SilentlyContinue)) {
New-ADGroup -Name $Group.Group -Path $group.GroupLocation -GroupScope $Group.GroupType
}
else {
"Group '$($Group.Group)' already exists"
}
}
答案 1 :(得分:0)
运行此脚本在Powershell中创建批量用户,任务将在30秒内完成
New-ADGroup“-名称-GroupScope -GroupSecurity -GroupName”-路径“ OU = OUWhereIStoreMyGroups”-说明