PowerShell Script to Automate New AD Group Membership - powershell

Can anyone share ideas for a PowerShell script that will create a new AD global security group and then populate it with all user objects that share a specific attribute?

Use the ActiveDirectory module.
$group_name = 'dudez'
New-ADGroup -Name $group_name `
-GroupCategory Security `
-GroupScope Global `
-Path "CN=Users,DC=foo,DC=local" `
-Description "Members of this group have identified as men."
$dudes = (Get-ADUser -Filter "...").DistinguishedName
Add-ADGroupMember -Identity $group_name -Members $dudes
First line creates the group. Second builds the list of users you want in the group. Third line adds the users to the group.
You should be able to modify this to suit your needs.

Related

Remove AzureAD user from all groups -powershell

I've been trying to remove all of the groups(M365,DL,security etc.) from a user.
I was trying to use this script but I'm getting errors when removing DLs(reasonably).
$Groups = Get-AzureADUserMembership -ObjectId $userID
foreach($Group in $Groups.ObjectId){
Remove-AzureADGroupMember -ObjectId $Group -MemberId $userID
}
My problem is that I have no way to get the type of the group and treat it with the correct command accordingly. When trying to use MSOL to get the type I saw that M365 groups are also being shown as a distribution list, So I'm not able to use this method.
Any advice or luck with that?
Thanks!
Edit:
This is how the groups are showing up, identical but not actually as it requires different command to remove the group.
365 group and DL
Considering that Azure AD group memberships can be removed via Remove-AzureAdGroupMember while Exchange Online memberships via Remove-DistributionGroupMember, executing both commands via a try..catch is probably the most efficient way to meet the OP's requirements.
The code below does just that (remove the comment before the Confirm parameter to skip confirmation.)
Connect-AzureAD
Connect-ExchangeOnline
$userid = (Get-AzureADuser -objectid "test.user#testdomain.test").objectid
$Groups = Get-AzureADUserMembership -ObjectId $userID
foreach($Group in $Groups){
try {
Remove-AzureADGroupMember -ObjectId $Group.ObjectID -MemberId $userID -erroraction Stop
}
catch {
write-host "$($Group.displayname) membership cannot be removed via Azure cmdlets."
Remove-DistributionGroupMember -identity $group.mail -member $userid -BypassSecurityGroupManagerCheck # -Confirm:$false
}
}
Note: proper code formatting does help.
I have tried with same script in my environment to remove an user from the groups and it removed successfully .
Azure portal->Groups->Enter your Group name
In my Azure Active directory ,I have Microsoft group type with 5 users:
In my Security Group type I have 4 users:
I tried with particular user like imran khan to remove from these two groups.
First you need to connect with azureAD using this command :
Import-Module AzureAD
$Credential = Get-Credential
Connect-AzureAD -Credential $Credential
Now I tried with same commands:
$userID = 'user object ID'
$Groups = Get-AzureADUserMembership -ObjectId $userID
foreach($Group in $Groups.ObjectId){
Remove-AzureADGroupMember -ObjectId $Group -MemberId $userID
}
Response:
Which returned empty that means which I removed successfully a user from the group.
Reference:
Compare groups - Microsoft 365 admin | Microsoft Docs

Script to create multiple AD groups and set email (exchange is not used)

Powershell novice here. I need a script to create bulk AD groups and set the email address for the group. We do not use exchange. I have not been able to find good examples when not using exchange.
$Example = get-content c:\temp\Example.txt
foreach($Example in $Example){
New-ADGroup -Name "$Example.###" -SamAccountName "$Example.###" -Email "$Example.####Anywhere.com" -ParentContainer "OU=THERE,OU=Organization,DC=HERE,DC=NET" -GroupType "Security" -GroupScope "Global"
}
New-AdGroup doesn't have a parameter Email. You will have to use
-OtherAttributes #{mail = "$Example.####Anywhere.com"}
PS. If the dot after the variable leads to problems, you can also format like
-OtherAttributes #{mail = ('{0}.####Anywhere.com' -f $Example)}

New-mailbox script, with zipcode and P.O. Box values added to mailbox user account. possible?

I am using the following powershell code for creating new mailboxes in my organization.
$users = Import-CSV C:\mailboxes.csv
$users| foreach {
$Password = convertto-securestring $_.password -asplaintext -force
new-mailbox -name $_.name -alias $_.alias -FirstName $_.Firstname -LastName $_.Lastname -userPrincipalName $_.userPrincipalName -PrimarySmtpAddress $_.PrimarySmtpAddress -Database $_.database -RetentionPolicy "b3a83dc4-e471-4d05-b357-25535aa027af" -OrganizationalUnit $_.OrganizationalUnit -Password $Password –ResetPasswordOnNextLogon:$false
}
Is there a way to insert a static text/value to this "zip code" and "po box" boxes, on the new active directory user, created along with this mailboxes?
for example , zip code should contain: "0101010101" and P.O Box should contain "000"
Your assistance is most appreciated
One option is to use Set-ADUser from the ActiveDirectory module. At the beginning of your script (before any loops), you can run the following if you have the module available to your current session.
Import-Module ActiveDirectory
After your New-Mailbox command, you can add the Set-ADUser command:
Set-ADUser -Filter "UserPrincipalName -eq '$($_.userprincipalname)'" -PostalCode "01010101" -POBox "000"
Sometimes AD replication can cause inconsistencies with multiple commands against AD objects. To get around that, you would typically use the -Server parameter to consistently target a domain controller that will see all of your read and write operations. The alternative (a slower one) is to run the AD user modifications after all of the mailboxes have been created and data has replicated to the AD Site you would be targeting.
AdminOfThings - Thanks for your reply.
So tell me,
Considering your last comment about the AD User modification conflict that i might occur,
i`m thinking some sort of "time delay" code might resolve such issues.
would it be logical to add something like "Start-Sleep" command to add a delay between
the "new-mailbox" and "Set-ADUser" commands as you suggested?
if so can you...write down how my script should like exactly, adding all things together please?
Thanks.

Remove full access permissions of all disabled users on shared mailboxes with exchange management shell

I’m looking for a powershell exchange script to remove Full access permissions of all disabled users on all shared mailboxes in a specific OU.
This is what I got so far
Remove-MailboxPermission -Identity Sharedmailbox -AccessRights Fullaccess -InheritanceType all -user DisabledUser -Confirm:$false | where {$_.UseraccountControl -like "*accountdisabled*"}
Its seems to work but I’m not sure about the last piece of het script if it will check for “accountdisabled”
Then I created a variable so it will check only one specific OU
$ou = Get-ADUser -SearchBase "OU=Functional Mailboxes,OU=Generalaccounts,DC=DOMAIN,DC=COM" -Filter * foreach ($user in $ou)
Remove-MailboxPermission -Identity "$ou" -AccessRights Fullaccess -InheritanceType all -Confirm:$false | where {$_.UseraccountControl -like "*accountdisabled*"}
The script is checking the right OU but I'm still looking for the last part where it will automatically remove full access permissions of the disabled users ONLY.
Can someone show me the way?
Instead of trying to screen for disabled users after removing the mailbox permissions (which is what your Remove-MailboxPermission ... | Where-Object ... appears to be intended to do - except that the way you wrote it, it's only checking for disabled state after removing the permissions), try selecting for the disabled accounts first, then passing only the disabled accounts to Remove-MailboxPermission:
Get-ADUser -SearchBase ... -filter {Enabled -eq $false} | Remove-Mailbox ...
(replacing ... with the appropriate SearchBase or parameters for Remove-Mailbox, using $_ for the identity of the ADUser whose mailbox permissions you're removing.)

List group memberships for AD users

Using the following Powershell snippet I get the names of the group memberships for the current user:
$groups = [System.Security.Principal.WindowsIdentity]::GetCurrent().Groups
foreach($i in $groups){
$i.Translate([System.Security.Principal.NTAccount]).value
}
How can I modify this such I can supply the user account name as parameter?
Thanks,
Uwe
If you have access to the ActiveDirectory module, I'd suggest you use Get-ADUser. In case you can't use that module, you could use the System.DirectoryServices.AccountManagement assembly:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$username = read-host -prompt "Enter a username"
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ct, $username)
$groups = $user.GetGroups()
foreach($i in $groups){
$i.SamAccountName
}
You can download from Quest site this PSSnapin: Quest.ActiveRoles.ADManagement. (ActiveRoles Management Shell for Active Directory )
Is freeware and the you can do:
(get-qaduser username).memberof
To get the list of direct groups membership for the user 'username'
get-help is your best friend:
PS> get-help *member*
Name Category Synopsis
---- -------- --------
Export-ModuleMember Cmdlet Specifies the module members that are exported.
Add-Member Cmdlet Adds a user-defined custom member to an instance of a Windows PowerShell object.
Get-Member Cmdlet Gets the properties and methods of objects.
Add-ADGroupMember Cmdlet Adds one or more members to an Active Directory group.
Add-ADPrincipalGroupMembership Cmdlet Adds a member to one or more Active Directory groups.
Get-ADGroupMember Cmdlet Gets the members of an Active Directory group.
Get-ADPrincipalGroupMembership Cmdlet Gets the Active Directory groups that have a specified user, computer, group, or ser...
Remove-ADGroupMember Cmdlet Removes one or more members from an Active Directory group.
Remove-ADPrincipalGroupMembership Cmdlet Removes a member from one or more Active Directory groups.
so:
$username = "someusername"
get-adprincipalgroupmembership $username | select name