我下面的代码无法获取“ $groupname ”列表并在 ADD-ADGroupmember 步骤中运行它。我尝试了一种不同的方式,但我最终还是得到了一台显示在不同组中的计算机。我想要做的就是随机将计算机添加到选定数量的组中,并且只允许将每台唯一计算机分配到一个组中?有什么想法吗?
$logfile = "results-$((Get-Date).ToString('MM-dd-yyyy_hhmmtt')).log"
Get-Date | Out-File $logfile
$groupnameprefix = "Automated"
$organizationalunitpath="OU paths go here. There are multiple"
$grouporganizationalunitpath = "OU paths for AD Security Groups go here"
$NumberofComputersPerGroup = "300"
# This is a list of computer names that will be used to generate group names
$Patch_Groups = @(
"_Group_1",
"_Group_2",
"_Group_3",
"_Group_4"
)
# Get all computers from the specified organizational unit
[System.Collections.Generic.List[object]] $computers = $organizationalunitpath |
ForEach-Object { Get-ADComputer -Filter * -SearchBase $_ }
# Create the new group
foreach ($Patch_Group in $Patch_Groups){
# Generate the group name by concatenating the prefix and the Patch Group name with spaces removed
$groupname = $groupnameprefix + $Patch_Group.Replace(" ","")
try {
# Create the group using the generated name and the specified organizational unit path
New-ADGroup -Name $groupName -path $grouporganizationalunitpath -GroupScope Global -verbose
}
catch {
$message = "ADGroup $groupName already exists"
$message | Out-File $logfile -Append
Write-Warning $message
Write-Warning $_.Exception.Message
$_.Exception.Message | Out-File $logfile -Append
}
try {
$AddComputerstoRandomADGroups = Get-Random -input $computers -count 300
$computers = $computers | where {$_ -notin $AddComputerstoRandomADGroups}
Add-ADGroupMember -Identity $groupname -Members $AddComputerstoRandomADGroups -verbose
}
catch {
$message = ' A problem occurred trying to add Members'
$message | Out-File $logfile -Append
Write-Warning $message
Write-Warning $_.Exception.Message
$_.Exception.Message | Out-File $logfile -Append
}
}
OK,忽略我之前写的,我现在看到发生了什么。
代码的 Get-Random 位不是选择随机计算机,它只是选择一个随机数并将其传递到管道中。
假设 $computers 不比 :
更复杂$computers=@()
$computers="computer1","computer2","computer3","computer4","computer5","computer6","computer7","computer8"
然后这段代码就可以了:
$AddComputerstoRandomADGroups = Get-Random -input $computers -count 4
$computers = $computers | where {$_ -notin $AddComputerstoRandomADGroups}
Add-ADGroupMember -Identity $groupname -Members $AddComputerstoRandomADGroups -verbose
在这种情况下,从当前 $computers 中的 8 台计算机中随机选择 4 台计算机,然后更新 $computers 变量以等于 $computers 中的所有内容,除了分配给 $AddComputerstoRandomADGroups 的那些计算机,这样它们就不会在未来的迭代中被选中。