Skip to content

Instantly share code, notes, and snippets.

@plamber
Last active April 23, 2021 14:07
Show Gist options
  • Select an option

  • Save plamber/9e78bd478d0cb07804737dc668bde0df to your computer and use it in GitHub Desktop.

Select an option

Save plamber/9e78bd478d0cb07804737dc668bde0df to your computer and use it in GitHub Desktop.
Replace owner in a Microsoft Group
# This script replaces an owner with a different person in all Microsoft 365 Groups
$oldUser = "oldUserUpn"
$newUser = "newUserUpn"
# Parameters end
$m365Status = m365 status
if ($m365Status -eq "Logged Out") {
# Connection to Microsoft 365
m365 login
}
# configure the CLI to output JSON on each execution
m365 cli config set --key output --value json
m365 cli config set --key errorOutput --value stdout
m365 cli config set --key showHelpOnFailure --value false
function Get-CLIValue {
[cmdletbinding()]
param(
[parameter(Mandatory = $true, ValueFromPipeline = $true)]
$input,
[parameter(Mandatory = $false)]
$convertFromJson = $true
)
if ($convertFromJson) {
try {
return $input | ConvertFrom-Json
}
catch {
}
}
if ($input.StartsWith("Error:")) {
$errorMessage = $input.Replace("Error: ", "")
throw $errorMessage
}
return $input
}
function Replace-Owner {
[cmdletbinding()]
param(
[parameter(Mandatory = $true)]
$oldUser,
[parameter(Mandatory = $true)]
$newUser
)
$groupsToProcess = m365 aad o365group list | Get-CLIValue
$i = 0
$groupsToProcess | ForEach-Object {
$group = $_
$i++
Write-Host "Processing Group ($($group.id)) - $($group.displayName) - ($i/$($groupsToProcess.Length))" -ForegroundColor DarkGray
$hasOwner = $null
# verify if the old user is in the owners list
$hasOwner = m365 aad o365group user list --groupId $group.id --query "[?userType=='Owner' && userPrincipalName=='$oldUser'].[id]" | Get-CLIValue
if ($hasOwner -ne $null) {
Write-Host "Found $oldUser" -ForegroundColor Green
try {
Write-Host "Granting $newUser owner rights"
m365 aad o365group user add --groupId $group.id --userName $newUser --role Owner | Get-CLIValue
}
catch {
Write-Host $_.Exception.Message -ForegroundColor White
}
try {
Write-Host "Removing $oldUser permissions..."
m365 aad o365group user remove --groupId $group.id --userName $oldUser --confirm $false | Get-CLIValue
}
catch {
Write-Host $_.Exception.Message -ForegroundColor Red
continue
}
}
}
}
Replace-Owner $oldUser $newUser
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment