How to remove users that have roles scoped to a specific Azure AD Administrative Unit via Powershell - powershell

I am trying to understand the correct PowerShell command to remove one or more users which have a role granted to them which is scoped over the members of an Administrative Unit.
For example, a Help Desk Employee that is empowered with Authentication Administrator over an AU that contains all the staff at their office location.
It would appear that the correct way to do this using Azure AD Powershell would be to use Remove-AzureADMSScopedRoleMembership but I cannot find any documentation on what inputs are desired for this command or if this is even the right method to reach the desired outcome.
Documentation: https://learn.microsoft.com/en-us/powershell/module/azuread/remove-azureadmsscopedrolemembership?view=azureadps-2.0
Iterations I have tried:
Remove-AzureADMSScopedRoleMembership -id "Object ID of user with scoped role" -ScopedRoleMembershipId "/administrativeUnits/ObjectId of AU"
Remove-AzureADMSScopedRoleMembership : Error occurred while executing RemoveMSScopedRoleMembership
Code: BadRequest
Message: Resource not found for the segment
Remove-AzureADMSScopedRoleMembership -id "Object ID of AU with scoped roles" -ScopedRoleMembershipId "Object ID of user with scoped role"
Remove-AzureADMSScopedRoleMembership : Error occurred while executing RemoveMSScopedRoleMembership
Code: BadRequest

I have reproduced in my environment and got expected results as below and followed Microsoft-Document:
Firstly, I have added a scopedrole as below:
Connect-AzureAD
$User = Get-AzureADUser -SearchString "Display Name of User"
$Role = Get-AzureADDirectoryRole | Where-Object -Property DisplayName -EQ -Value "User Administrator"
$RoleMember = New-Object -TypeName Microsoft.Open.AzureAD.Model.RoleMemberInfo
$Unit = Get-AzureADAdministrativeUnit | Where-Object -Property DisplayName -Eq -Value Test
$RoleMember.ObjectId = $User.ObjectID
Add-AzureADScopedRoleMembership -ObjectId $unit.ObjectId -RoleObjectId $Role.ObjectId -RoleMemberInfo $RoleMember
I have taken ScopedRoleMembershipId from microsoft Graph api using below request:
https://graph.microsoft.com/v1.0/directory/administrativeUnits/{admin-unit-id}/scopedRoleMembers
Then used below command to remove user and I followed Microsoft-Document:
Remove-AzureADScopedRoleMembership -ObjectId $unit.ObjectId -ScopedRoleMembershipId "08ovlLXBT0CMQ7kJaZRJU"
Try to follow the above process user will be removed as mine got.

Related

Using MgGraph PowerShell 1.0 - Update-MgGroup -AdditionalProperties how to update the resourceBehaviorOptions option?

The education institution, I am helping, uses the Moodle Plugin Microsoft 0365 Integration which I believe uses the latest MgGraph v1.0 to create Microsoft 365 Teams Groups.
The Moodle plugin creates Microsoft 365 Teams Groups but some Settings can not be updated on the Admin Exchange Center after its creation, It returns an Error.
The property to be set being
The error received is not really helping
This Microsoft 365 Teams Group uses the HiddenMembership Visibility since MS Teams Classes can also be used and for privacy reasons this visibility is used. Unfortunately, the PHP code created by the Moodle MS Plugin adds more security features that prevents the groups from sending emails to each other since the above property can not be updated.
To get more information about the error, I tried to use MgGraph to set the Setting programmatically
$params = #{
AutoSubscribeNewMembers = $true
}
Update-MgGroup -GroupId $groupid -BodyParameter $params
Than I go the below error:
AutoSubscribeNewMembers parameter can't be true when SubscriptionEnabled
is set to false on the group.
Looking all around, I finally found where the SubscriptionEnabled value is set.
((get-MgGroup -GroupId $groupid).AdditionalProperties).resourceBehaviorOptions
Outputs :
SubscriptionDisabled
SharePointMemberReadonly
CalendarMemberReadOnly
WelcomeEmailDisabled
SubscribeNewGroupMembers
HideGroupInOutlook
ConnectorsDisabled
AllowOnlyMembersToPost
I tried to remove that value from the Group's AdditionalProperties.resourceBehaviorOptions but get this error.
$resourceBehaviorOptionsParams = #{
"SubscriptionDisabled" = "false";
}
$additionalParams = #{
resourceBehaviorOptions = $resourceBehaviorOptionsParams
}
Update-MgGroup -GroupId $groupid -AdditionalProperties $additionalParams
Error
An unexpected 'StartObject' node was found for property named 'resourceBehaviorOptions' when
| reading from the JSON reader. A 'StartArray' node was expected.
How can I remove the SubscriptionDisabled Option from the resourceBehaviorOptions section ?
I tried to reproduce the same in my environment and got same error like below
The error usually occurs if you don't have proper license like
Exchange Online or the subscription is disabled on that teams group.
When I ran the same MgGraph commands as you to know more about error, I got same response like below:
Connect-MgGraph
$groupid = "f2210ee6-451a-496b-8b39-c2xxxxxxxf"
$params = #{
AutoSubscribeNewMembers = $true
}
Update-MgGroup -GroupId $groupid -BodyParameter $params
Response:
When I tried the same script as you to remove the SubscriptionDisabled Option, I got same error like below:
$groupid = "f2210ee6-451a-496b-8b39-c289xxxxxdaf"
$resourceBehaviorOptionsParams = #{
"SubscriptionDisabled" = "false";
}
$additionalParams = #{
resourceBehaviorOptions = $resourceBehaviorOptionsParams
}
Update-MgGroup -GroupId $groupid -AdditionalProperties $additionalParams
Response:
To resolve the error, you can enable subscription for that teams group using below Exchange Online commands:
Connect-ExchangeOnline
Set-UnifiedGroup -Identity "Devi Team" -SubscriptionEnabled:$true
Response:
After enabling the subscription, I ran below command to enable AutoSubscribeNewMembers like this:
Set-UnifiedGroup -Identity "Devi Team" -AutoSubscribeNewMembers:$true
Response:
When I checked the same in Exchange Admin Center, option enabled successfully like below:
You can also enable "Allow external senders to email this group" option if needed from Portal like this after enabling subscription:

How to get a list of members and their Active assignment role in Azure AD?

I would like to do a validation of members who have an "Active assignment" role in Azure AD. Is there a way to know if the role was granted by a group or directly? How could I get the information into my script? Thank you for your help
connect-azuread
$roles = Get-AzureADDirectoryRole | select objectid, displayname
ForEach($role in $roles){
Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId | select #{n="Azure role";e={$role.DisplayName}}, displayname
}
You found the easiest solution using powershell.I check with Ms graph it is bit difficult than powershell. I also removed one of the statement from your code which is not required .
I tested in my environment working fine for me.
connect-azuread
$roles = Get-AzureADDirectoryRole
ForEach($role in $roles){
Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId | select #{n="Azure role";e={$role.DisplayName}}, displayname
}
output:

New-UnifiedGroup doesn't work with ErrorAction

I am using the code below to create a public group using powershell in O365:
Try
{
New-UnifiedGroup -AccessType Public -Alias $groupIdentity -DisplayName $groupDisplayName -Owner $smtpAddress
}
Catch
{
# Some exception handling statements
}
But I don't see it reaching to catch in case of failure.
After investigation a little, I got to know that -ErrorAction stop needs to be used at the end of the command for it to reach to catch.
But When I do the below:
New-UnifiedGroup -AccessType Public -Alias $groupIdentity -DisplayName $groupDisplayName -Owner $smtpAddress -ErrorAction stop
this fails with the error below:
The "ErrorAction" parameter can't be used on the "New-UnifiedGroup" cmdlet because it isn't present in the role definition for the current user. Check the management roles assigned to you, and try again.
But again I have Global Admin role assigned to me so I have no idea what I am doing wrong.
The error you have received is saying that you're not authorized to run that command with that specific parameter. You need to be assigned permissions before you can run this cmdlet.
Although this topic lists all parameters for the cmdlet, you may not have access to some parameters if they're not included in the permissions assigned to you. To find the permissions required to run any cmdlet or parameter in your organization, see Find the permissions required to run any Exchange cmdlet.
To check if you're able to run any cmdlet with specific parameter you can use the following script:
# Define what you're looking for
$user = 'joey#contoso.com'
$cmdlet = 'New-UnifiedGroup'
$param = 'ErrorAction'
# Find all your assignments
$assignments = Get-ManagementRoleAssignment -RoleAssignee $user -Delegating $false
# Find cmdlets you can run and filter only the one you specified
$assignments.role | Foreach-Object {Get-ManagementRoleEntry "$_\*" | Where-Object {$_.Name -eq $cmdlet -and $_.Parameters -contains $param}}
In last line we're iterating all the roles assigned to you and checking role entries. Their format is RoleName\CmdletName so we're using * (wildcard) to get all. After last pipeline you're filtering only the results you want using Where-Object cmdlet.
Joey Cai's answer explains how to check if you're allowed to run the cmdlet with specific parameter.
I have checked it on my O365 tenant and apparently I'm not allowed to use -ErrorAction in New-UnifiedGroup so it seems to be default setting in Office 365. As a workaround, I'd use the following to temporarily change error action preference:
$previousErrorAction = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
New-UnifiedGroup -AccessType Public -Alias $groupIdentity -DisplayName $groupDisplayName -Owner $smtpAddress
$ErrorActionPreference = $previousErrorAction

How to connect with PowerShell using external user creds to another tenant in Azure?

I have "external user" from TenantA AD added to TenantB in Azure and added as "owner" to one of B subscriptions.
How can I connect with PowerShell using that external user to TenantB subscription?
Login-AzureRmAccount/Add-AzureRmAccount while using external users' UPN in -Credential and specifying tenantId/subscriptionId of TenantB gives me error:
add-azurermaccount : The provided account <...> does not have access to subscription ID "<...>". Please try logging in with
different credentials or a different subscription ID.**
Looking at Get-MsolUser output of TenantB, I can see external user from tenantA in the following form:
PS C:\> get-msoluser
UserPrincipalName DisplayName isLicensed
----------------- ----------- ----------
<username>_tenantA.onmicrosoft.com#EXT##tenantB.onmicrosoft.com <..> False
I would start with clearing the cached credentials using:
Get-AzureAccount | ForEach-Object { Remove-AzureAccount $_.ID -Force }
Then use Login-AzureRmAccount and enter the credentials for TenantA. You should be able to switch the subscription using.
Select-AzureRmSubscription -SubscriptionName

Check if user is a member of the local admins group on a remote server

The user is a member of the AD security group "Domain\Sql Admins", and the security group "Domain\Sql Admins" is a member of the local Administrators group on a Windows Server.
I have tried the following PowerShell script:
$u = "Username"; net localgroup administrators | Where {$_ -match $u}
This script will only return the user if it is added directly to the admin group. Do I have to cycle through all of the groups in the admin group until I find my user? Or is there another way?
Check out this article, by Boe Prox on the Microsoft Hey Scripting Guy blog. He describes how to check if the user is a local administrator or not.
http://blogs.technet.com/b/heyscriptingguy/archive/2011/05/11/check-for-admin-credentials-in-a-powershell-script.aspx
This article points to a Test-IsAdmin function that was posted onto the TechNet Gallery.
http://gallery.technet.microsoft.com/scriptcenter/1b5df952-9e10-470f-ad7c-dc2bdc2ac946
The function contains the following code, which returns $true or $false.
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
PowerShell 5.1 (Windows Server 2016) contains Get-LocalGroupMember cmdlet.
$user = "$env:COMPUTERNAME\$env:USERNAME"
$group = 'Administrators'
$isInGroup = (Get-LocalGroupMember $group).Name -contains $user
Using the SID:
([Security.Principal.WindowsIdentity]::GetCurrent().Groups | Select-String 'S-1-5-32-544')
Or using a "Well-known" security identifier name:
([Security.Principal.WindowsIdentity]::GetCurrent().Groups.IsWellKnown('BuiltinAdministratorsSid') -eq $true)
if you want to get all the SIDs and their names, please check this page: https://support.microsoft.com/en-us/help/243330/well-known-security-identifiers-in-windows-operating-systems
If you happen to be using the PowerShell Community Extension you can use the Test-UserGroupMembership command e.g.:
Test-UserGroupMembership Administrators