How to create a Dynamic Office 365 Group - azure

I am new to Exchange Online, and Azure, but Ive been asked if we can create O365 groups in Exchange Online, using the New-UnifiedGroup and Set-UnifiedGroup cmdlets. Then they want to be able to make those groups dynamic, based upon certain criteria. Is this even possible, or do I skip Exchange Online entirely, and in Azure use the New-AzureADMSGroup cmdlets to create a dynamic group.
Any help is appreciated.
Thanks.

Yes, you could create an Office 365 group with AzureAD PowerShell cmdlet New-AzureADMSGroup and you need to install AzureAD module first.
For example, This command creates a new dynamic group with the following rule:
user.department -contains "Marketing"
The double quotation marks are replaced with single quotation marks.
The processing state is On. This means that all users in the directory
that qualify the rule are added as members to the group. Any users
that do not qualify are removed from the group.
New-AzureADMSGroup -DisplayName "Dynamic Group 01" -Description "Dynamic group created from PS" -MailEnabled $False -MailNickName "group" -SecurityEnabled $True -GroupTypes "DynamicMembership" -MembershipRule "(user.department -contains ""Marketing"")" -MembershipRuleProcessingState "On"
More references: https://techcommunity.microsoft.com/t5/Azure-Active-Directory-Identity/New-enhancements-to-the-AzureAD-PowerShell-2-0-preview-Manage/ba-p/245153
and https://blog.hubfly.com/office-365/useful-powershell-cmdlets-to-administer-office-365-groups-part-1

Ok, so here is the solution we came up with.
Requires AzureADPreview module, current version as of today 2.0.2.17
The AzureAD Module wont work, as it is missing parameters required for group membership.
Requires a Connection into AzureAD, and also Exchange Online.
The account you connect with need to be an Exchange Administrator in Exchange Online, and an User Administrator in AzureAD.
In our example we want an Office group, that is dynamic, and the membershipRule based upon extensionattribute12.
#***********************************************************************
$ADUser = "samAccountName#yourdomain"
$ADPassword = 'the password'
$ADPwd = $ADPassword | ConvertTo-SecureString -AsPlainText -Force
$UserCredential = new-object system.management.automation.pscredential $ADuser, $ADPwd
#***********************************************************************
"Connect AzureAD"
Connect-AzureAD -Credential $UserCredential
"Connect to Exchange Online"
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking
#######################################
function ConvertStaticGroupToDynamic
{
Param([string]$groupId, [string]$dynamicMembershipRule)
$dynamicGroupTypeString = "DynamicMembership"
#existing group types
[System.Collections.ArrayList]$groupTypes = (Get-AzureAdMsGroup -Id $groupId).GroupTypes
if($groupTypes -ne $null -and $groupTypes.Contains($dynamicGroupTypeString))
{
throw "This group is already a dynamic group. Aborting conversion.";
}
#add the dynamic group type to existing types
$groupTypes.Add($dynamicGroupTypeString)
#modify the group properties to make it a static group: i) change GroupTypes to add the dynamic type, ii) start execution of the rule, iii) set the rule
Set-AzureAdMsGroup -Id $groupId -GroupTypes $groupTypes.ToArray() -MembershipRuleProcessingState "On" -MembershipRule $dynamicMembershipRule
}
#######################################
$ExtAtt12 = "Marketing"
$NewGroupName = "O365-OfficeGroupTest"
"[$NewGroupName] create group"
New-UnifiedGroup -DisplayName $NewGroupName
Set-UnifiedGroup $NewGroupName -UnifiedGroupWelcomeMessageEnabled:$false
$ID = (Get-UnifiedGroup $NewGroupName).ExternalDirectoryObjectId
sleep 15 # Allow time for Exchange Online to Sync with AzureAD
ConvertStaticGroupToDynamic -groupId $ID -dynamicMembershipRule "(User.extensionattribute12 -eq ""$ExtAtt12"")"

Related

I am looking to create a PowerShell script that revokes the user's Azure AD refresh tokens and disable the user's devices

I am looking for some guidance on combining a PowerShell script that combines the following scripts:
Connect-AzureAD
Revoke-AzureADUserAllRefreshToken -ObjectId johndoe#contoso.com
Get-AzureADUserRegisteredDevice -ObjectId johndoe#contoso.com | Set-AzureADDevice -AccountEnabled $false
What I am hoping to achieve is to combine all three cmdlets to a single script that my staff can run, where it will prompt for the user name that we wish to run the script upon. Assuming I need to add $ObjectID = Read-Host -Promptsomewhere in this script.
Thank you in advance for any advice or guidance on how to do this.
Assuming I understood your question and you just wanted a way to assemble all that together in the correct order, here it is.
# Use one or the other depending on if you want to use the username or objectID
$Username = Read-Host -Prompt
#$ObjectId = Read-Host -Prompt
Connect-AzureAD
# Use one or the other depending on if you want to use the username or objectID
$User = Get-AzureADUser -SearchString $Username
#$User = Get-AzureADUser -ObjectId $ObjectId
if ($null -ne $User) {
Revoke-AzureADUserAllRefreshToken -ObjectId $User.ObjectId
Get-AzureADUserRegisteredDevice -ObjectId $User.ObjectId | Set-AzureADDevice -AccountEnabled $false
} else {
Write-Warning "No user found with the specified criteria"
}

Is there any PowerShell script or command to get a report of all the user's access role in tenant wise from Azure portal?

I am preparing the report which contains all the users access level tenant wise from the azure.
is there any one command or script to get all the users access level from Azure tenant ?
That is a little be trick: The PS library for Azure is different from the PS library for the AD. You must cross informations.
You must get all users from you AD using the command above and save as variable
$allUsers = Get-ADUsers -Filter *
Now you can navigate to all subscriptions into your tenant, all resource groups and resources and for each and every one get the IAM (who came with the objectId of the user) and cross with the variable $allUsers to identify everyone.
The sample is not the best but maybe can help you:
Connect-AzAccount
$listIAM = New-Object System.Collections.ArrayList
$listSubscriptions = Get-AzSubscription
foreach($subscription in $listSubscriptions){
Set-AzContext -SubscriptionId $subscription.SubscriptionId
# Now you have all roleAssignements for this subscription
$subscriptionIAM = Get-AzRoleAssignment -Scope /subscriptions/$subscription.SubscriptionId
$listIAM.Add($subscriptionIAM) | Out-Null
# Navigate into resource groups
$listResourceGroups = Get-AzResourceGroup
foreach($resourceGroup in $listResourceGroups){
$rgIAM = Get-AzRoleAssignment -ResourceGroupName $resourceGroup.ResourceGroupName
$listIAM.Add($rgIAM) | Out-Null
# Navigate into resources
$listResources = Get-AzResource -ResourceGroupName $resourceGroup
foreach($resource in $listResources){
$rIAM = Get-AzRoleAssignment -Scope $resouce.ResourceId
$listIAM.Add($rIAM) | Out-Null
}
}
}
You can do this in either PowerShell or the Graph API. Both methods are in preview (the graph API calls are under the beta branch).
#Get the user
$userId = (Get-AzureADUser -Filter "userPrincipalName eq 'alice#contoso.com'").ObjectId
#Get direct role assignments to the user
$directRoles = (Get-AzureADMSRoleAssignment -Filter "principalId eq '$userId'").RoleDefinitionId
Prerequisites
AzureADPreview module when using PowerShell
Microsoft.Graph module when using PowerShell
Admin consent when using Graph Explorer for Microsoft Graph API
https://learn.microsoft.com/en-us/azure/active-directory/roles/list-role-assignments-users

Azure PIM PowerShell Script

On Azure Portal we can grant Contributor role to Subscription using PIM for limited period of time.
Like 1 - 2 - 3 hours.
Those are called eligible assignments.
Anyone has tried assigning eligible assignments using powershell ?
As per my research -- AZureADPreview module is present.
(https://learn.microsoft.com/en-us/azure/active-directory/privileged-identity-management/powershell-for-azure-ad-roles )
But it is still under preview and doens't have full functionality.
I think the functionality has already been mentioned in the doc, give a sample here to elaborate on the specific usage.
For example, you want to assign the Application Administrator role to a user, then the script should be:
Note: The -ResourceId parameter uses your AAD tenant id <tenant-id>.
$role = Get-AzureADMSPrivilegedRoleDefinition -ProviderId aadRoles -ResourceId "<tenant-id>" | Where-Object {$_.DisplayName -eq 'Application Administrator'}
$schedule = New-Object Microsoft.Open.MSGraph.Model.AzureADMSPrivilegedSchedule
$schedule.Type = "Once"
$schedule.StartDateTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
$schedule.endDateTime = "2021-07-25T20:49:11.770Z"
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId aadRoles -Schedule $schedule -ResourceId "<tenant-id>" -RoleDefinitionId $role.Id -SubjectId "<object-id of user or group>" -AssignmentState "Eligible" -Type "AdminAdd"
Check in the portal:

Find SITEID in sharepoint admin center

I am looking for the siteID in admin center of sharepoint and I cannot find it. I can get it via graphAPI but I need to find it via admin center as well, and the reason is our customer has multi-tenant application and they want each tenant enter their own sharepoint/graphAPI settings in the application.
I don't believe it is possible to get the site Id for SharePoint Online sites from the SPO admin center. You can use Microsoft Graph, SharePoint Online PowerShell, Client Side Object Model (CSOM), and more. Additionally if you navigate to a site in a browser and append "/_api/site" to the URL you can see the Guid for the site, but you'll need to parse the XML response.
It seems that there is not a way to get site id in CA.
I write a pnp powershell script to get all site id for your reference.
$username = "amos#contoso.onmicrosoft.com"
$password = "Password"
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)
$TenantSiteURL = "https://contoso-admin.sharepoint.com/"
$CSVFilePath = "C:\Temp\AllSitesData.csv"
#Connect to Tenant Admin Site
Connect-PnPOnline -Url $TenantSiteURL -Credentials $cred
$sites=Get-PnPTenantSite -Detailed
$listItemData=#()
foreach($site in $sites){
Connect-PnPOnline -Url $site.Url -Credentials $cred
#Get the site collection with ID property
$Site = Get-PnPSite -Includes ID
$listItemData += New-Object PSObject -Property #{
"Site Url" = $site.Url
"Site Collection ID" = $Site.Id
}
}
$listItemData |Export-Csv -NoTypeInformation -Path $CSVFilePath
As stated above, you need access to the admin center. Instead of using Get-PnPTenantSite, use
(Get-PnPListItem -List DO_NOT_DELETE_SPLIST_TENANTADMIN_AGGREGATED_SITECOLLECTIONS -PageSize 5000) | Where-Object { <#YOUR CRITERIA#> }

Office365: Follow in inbox powershell

Is there a way to write PowerShell command to "Follow in inbox" to a group?
or maybe Microsoft Graph API?
I am trying through the code to implement this feature, but can't see any documentation.
In office 365 every user that joins a group can use the dropdown to select Follow in inbox or Stop following in inbox:
here an image example of follow in inbox
I dont know a possiblity to do that via Powershell. You can set it in the AdminCenter gui of Office365 in the group settings.
See here: https://learn.microsoft.com/en-us/office365/admin/create-groups/create-groups?view=o365-worldwide#how-following-group-email-works
Update:
It seems that you can do it with the Graph API: https://learn.microsoft.com/en-us/graph/api/group-update?view=graph-rest-1.0
Function "UpdateGroup" and the Setting "autoSubscribeNewMembers".
Note: This will only take effect for new members not for existing ones!
Thank you, Hannes
This is a PowerShell I wrote:
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session
<#Get all Office 365 Groups that AutoSubscribeNewMembers disabled#>
$O365Groups = Get-UnifiedGroup | Where-Object{$_.AutoSubscribeNewMembers -eq $false}
<#Iterate through the Groups, enabling the AutoSubscribeNewMember#>
foreach ($group in $O365Groups)
{
Set-UnifiedGroup $group.Identity -AutoSubscribeNewMembers:$true
}
<#Close the Session#>
Remove-PSSession $Session
Works fine only for new member in the group
I was searching for the opposite command, to unsubscribe a user manually from powershell due to an external user receiving the emails for a group that were unnecessary to send externally.
Here are the powershell commands, connected to Exhange Online Powershell version 2:
View subscribers:
Get-UnifiedGroupLinks -Identity <email address> -LinkType Subscribers
Add subscribers:
Add-UnifiedGroupLinks -Identity <email address> -LinkType Subscribers -Links <comma separated list of email addresses>
Remove subscribers:
Remove-UnifiedGroupLinks -Identity <email address> -LinkType Subscribers -Links <comma separated list of email addresses>
Documentation
I have been working on some sample commands for this exact topic: Unsubscribe-FollowInInbox.ps1 (for full list of code samples)
Some samples:
#Check subscription status for ALL unified groups
Get-UnifiedGroup | Format-Table Name,*subscribe* -AutoSize
Here is PowerShell to make all "members" in to "subscribers" (aka Follow In Inbox)
##########################################
# Loop 1 - SUBSCRIBE all group members #
##########################################
#Store the team name in a variable. Change this to match your team.
#To find this for your team, use (Get-UnifiedGroup *test-team*).PrimarySmtpAddress
$teamname = "test-team#example.com"
#Find all the members of the Unified Group "test-team" and store their UserMailbox objects in a variable called "members"
$members = Get-UnifiedGroup $teamname | Get-UnifiedGroupLinks -LinkType Member
#Create a variable to keep track of how many members we have subscribed or unsubscribed
$membercount = ($members.Count)
#Loop through the list of members and add a subscriber link for each one
foreach ($member in $members)
{
#Decrement the member count
$membercount--
#Write progress to the PowerShell window
Write-Host "Adding subscriber link for user $($member.PrimarySmtpAddress), $membercount users remaining"
#Add the UnifiedGroupLink to make each user a subscriber
Add-UnifiedGroupLinks -Identity $teamname -Links $($member.PrimarySmtpAddress) -LinkType Subscriber -Confirm:$false
}

Resources