Powershell script to add group

Анатолий Косарев 1 Reputation point
2021-05-18T16:47:38.4+00:00

Hello everyone, my English is not very good, so I use a translator) So: I'm writing a script to automatically add a user to a group according to his department, but since the department and group name are in different languages, I use transliteration, if you don't use it, everything works well , please tell me where is my error? here is part of my script

[string[]] $GroupList = Get-AdUser -Filter * -Properties Department -SearchBase $userou | Select-Object -ExpandProperty Department -Unique | ForEach-Object {Translittolat($_)}

Foreach ($Group In $GroupList)
{
#$users=@()
$removeMember=@()
$addMember=@()

$ADGroup = Get-ADGroup -Identity $group -Properties Members,Name




$DeptFilter = "Department -eq '$Group'"
    [string[]] $GroupListeng = Get-AdUser -Filter * -Properties Department -SearchBase $userou | Select-Object -ExpandProperty Department -Unique
foreach ($groupe in $GroupListeng){
$deptra = "Department -eq '$Groupe'"
$Users = @(Get-AdUser -Filter "$deptra" -Properties Department -SearchBase $userou)
}
foreach ($user in $users)
{

$removeMember = @($ADGroup.Members | Where-Object {$PSItem -notin $Users.distinguishedName} )

if ($removeMember)
{
    Remove-ADGroupMember -Identity $ADGroup.DistinguishedName -Members $removeMember -Confirm:$false -Verbose
}


$addMember = $Users | Where-Object {$PSItem.distinguishedname -notin $ADGroup.Members}

if ($addMember)
{
    Add-ADGroupMember -Identity $ADGroup.DistinguishedName -Members $addMember -Verbose
}

}
}

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,273 questions
{count} votes