O365, Manage Distribution List group with Powershell - azure

Hope you're having a great day so far!
I'm using O365 Online, and I'm trying to Add a user to a distribution list group with Powershell, to automate user creation.
here are my steps
Connect to MolService : Connect-MsolService
I get the ObjectID of the distribution group.
$GroupeID = Get-MsolGroup -ObjectId $SupervisorGroup.ObjectId
I get the user ObjectID
ObjectIDUser = Get-MsolUser -ObjectId $user.ObjectId
I'm adding the user to the group
Add-MsolGroupMember -GroupObjectId $GroupeID.ObjectId -GroupMemberObjectId $Object.ObjectId -GroupMemberType User
But here is the error:
Add-MsolGroupMember : You cannot update mail-enabled groups using this cmdlet. Use Exchange Online to perform
this operation.
At line:11 char:2
+ Add-MsolGroupMember -GroupObjectId $GroupeID.ObjectId -GroupMemberOb ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [Add-MsolGroupMember], MicrosoftOnlineException
+ FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.MailEnabledGroupsNotSupportedException
,Microsoft.Online.Administration.Automation.AddGroupMember

As the error states: You cannot use the MSOL Cmdlets with Mail Enabled Objects, Use the Exchange Online Cmdlets for that:
Here's an helper function to load the Office 365 Exchange Cmdlets:
Function Load-365ExchangeShell
{
Param(
[System.Management.Automation.PSCredential]
$Cred
)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Cred -Authentication Basic -AllowRedirection
Import-PSSession $Session -WarningAction SilentlyContinue -DisableNameChecking
}
Use it like this:
$Cred = Get-Credential
Load-365ExchangeShell -Cred $Cred
Then use the relevant cmdlet (Add-DistributionGroupMember):
Add-DistributionGroupMember -Identity "DistributionGroupID_here" -Member "UserToAddID_here"
Note: for future use you better use the Updated Exchange Online V2
Module instead of the above method, as the old commands are
deprecated...
See this link

Related

Get-PnPTenantSite : Attempted to perform an unauthorized operation

Currently we get an access token and then pass this token to PowerShell script to loop across all ODFB personal sites.
$url = "https://XXXXX-admin.sharepoint.com"
$conn = Connect-PnPOnline -Url $url -AccessToken $access_token -ReturnConnection
$sitecollections = Get-PnPTenantSite -IncludeOneDriveSites:$true -Filter "Url -like '-my.sharepoint.com/personal/'" -Connection $conn | Select-Object -ExpandProperty Url
foreach ($site in $sitecollections)
{
....
}
It worked successfully for years until it was broken a while ago.
I tried different versions of PnP PowerShell:
PnP version
Error
SharePointPnPPowerShellOnline 3.21.2005.2 (currently used)
Get-PnPTenantSite : Attempted to perform an unauthorized operation.
SharePointPnPPowerShellOnline 3.29.2101.0
Get-PnPTenantSite : The current connection holds no SharePoint context.
PnP.PowerShell 1.10.28
Get-PnPTenantSite : Attempted to perform an unauthorized operation.
If I change script to use an user/password instead the access token, the script works without problems:
$url = "https://XXXXX-admin.sharepoint.com"
$User = "admin#mydomain.com"
$PWord = ConvertTo-SecureString -String "Password" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$conn = Connect-PnPOnline -Url $url -Credentials $Credential -ReturnConnection
$sitecollections = Get-PnPTenantSite -IncludeOneDriveSites:$true -Filter "Url -like '-my.sharepoint.com/personal/'" -Connection $conn | Select-Object -ExpandProperty Url
foreach ($site in $sitecollections)
{
....
}
So the error happens when the script connects to SP Online using an access token.
Perhaps the some things were changed. But what exactly? Have some scope to be added when an access token is requested?
Or have some new permissions to be added for the application in Azure AD?
Update:
Modified the script (added Write-Output "Connection is:" $conn | fl) to provide more details about connection and got the difference in ConnectionType property when SharePointPnPPowerShellOnline 3.21.2005.2 is used:
When an access token is used (and the script doesn't work properly), ConnectionType : O365
When an access token is used (and the script works fine), ConnectionType : TenantAdmin

Creating azure ad group with group types "Unified" and "DynamicMembership" fails in azure powershell function

I am using AzureAdPreview moudule and with the help of this I am trying to create a group with types "Unified" as well as "DynamicMembership".
So as per microsoft doc this is the command I have used
Import-Module AzureADPreview -UseWindowsPowerShell
$tenantId = <my tenant id>
$clientId = <my client id>
$thumbprint = <my thumbprint>
Connect-AzureAD -TenantId $tenantId -ApplicationId $clientId -CertificateThumbprint $thumbprint
New-AzureADMSGroup -Description $description -DisplayName `
$displayName -MailEnabled $true -SecurityEnabled $true `
-MailNickname $nickName -GroupTypes "DynamicMembership", "Unified"
-MembershipRule '(user.department -contains "tech")' -MembershipRuleProcessingState $true
But I am getting always invalid value provided in grouptypes error.
In an sligtly different approach, I have tried creating the group first with unified type, and then queried back the same group and appended grouptype to "DynamicMembership",I expected that to work but that also didn't make any difference.
Just like this -
New-AzureADMSGroup -Description $description -DisplayName `
$displayName -MailEnabled $true -SecurityEnabled $true `
-MailNickname $nickName -GroupTypes "Unified"
$grp = Get-AzureADMSGroup -SearchString $displayName
if($grp -ne $null)
{
[System.Collections.ArrayList]$groupTypes = $grp.GroupTypes
$groupTypes.Add($dynamicGroupTypes)
Set-AzureAdMsGroup -Id $grp.Id `
-GroupTypes $dynamicGroupTypes `
-MembershipRuleProcessingState "On" `
-MembershipRule $memberShipRule
}
Can you tell what I am doing wrong, this is working fine in a windows powershell. I am not able to understand what is malformed about that grouptypes.
• You are making some basic mistakes in the command that you are using for creating a ‘Unified’ and ‘Dynamic’ group through using powershell command in the Azure function. The command execution in Azure function involves the use of ‘AzureADPreview’ module only. Thus, you will have to uninstall and remove the ‘AzureAD’ module from your list of modules installed in powershell. For this purpose, execute the below command first: -
Remove-Module AzureAD -ErrorAction SilentlyContinue
Once done, then install the AzureADPreview module as you have done in your stated command. Then, execute the ‘Connect-AzureAD’ command as you have done. Then, execute the command as stated by me below for errorless execution as it is from start to end. Please do not forget to declare the other variables that you did in your question description for ‘Client ID’, ‘Tenant ID’ and ‘Thumbprint’: -
$tenantId = 'my tenant id'
$clientId = 'my client id'
$thumbprint = 'my thumbprint'
$description = ‘Description of the group’
$displayName = ‘Display Name to be given’
$nickName = ‘Any name of the group’
Connect-AzureAD -TenantId $tenantId -ApplicationId $clientId -CertificateThumbprint $thumbprint
New-AzureADMSGroup -Description $description -DisplayName $displayName -MailEnabled $true -SecurityEnabled $true -MailNickname $nickName -GroupTypes "DynamicMembership", "Unified" -MembershipRule “(user.department -contains “"tech"”)” -MembershipRuleProcessingState “On”
Once the above command is executed as it is, your command will be executed successfully in Azure function without any error or issue.

How to activate Privileged Access Groups using Powershell?

I am trying to activate my privileged access groups using powershell however so far unable to do so. All the examples either in MS Docs site or google search only have examples regarding instruction to activate roles using powershell for PIM.
Has anyone been successful or have an idea how to get privileged access groups activated using powershell?
Here is what i tried:
#variables
$upn = ""
$tenantId = ""
$reason = "Test"
$groupId = "" #privileged access groups Id retrieved from Azure Portal > Groups > <group which has roles>
#MFA setup
if(!(Get-Module | Where-Object {$_.Name -eq 'PowerShellGet' -and $_.Version -ge '2.2.4.1'})) { Install-Module PowerShellGet -Force }
if(!(Get-Package msal.ps)) { Install-Package msal.ps }
# Get token for MS Graph by prompting for MFA
$MsResponse = Get-MSALToken -Scopes #("https://graph.microsoft.com/.default") -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -RedirectUri "urn:ietf:wg:oauth:2.0:oob" -Authority "https://login.microsoftonline.com/common" -Interactive -ExtraQueryParameters #{claims='{"access_token" : {"amr": { "values": ["mfa"] }}}'}
# Get token for AAD Graph
$AadResponse = Get-MSALToken -Scopes #("https://graph.windows.net/.default") -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -RedirectUri "urn:ietf:wg:oauth:2.0:oob" -Authority "https://login.microsoftonline.com/common"
Connect-AzureAD -AadAccessToken $AadResponse.AccessToken -MsAccessToken $MsResponse.AccessToken -AccountId: $upn -tenantId: $tenantId
$roleDefinitionCollection = Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadRoles" -ResourceId $resource.Id -Filter "subjectId eq '$grouipId'"
#set schedule
$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 = (Get-Date).AddHours($activateTime).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
$subject = Get-AzureADUser -Filter "userPrincipalName eq '$upn'"
foreach ($roleDefinition in $roleDefinitionCollection) {
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId AadRoles -Schedule $schedule -ResourceId $resource.Id -RoleDefinitionId $roleDefinition.RoleDefinitionId -SubjectId $subject.ObjectId -AssignmentState "Active" -Type "UserAdd" -Reason $reason
}
This returns error message:
Open-AzureADMSPrivilegedRoleAssignmentRequest : Error occurred while executing OpenAzureADMSPrivilegedRoleAssignmentRequest
Code: RoleAssignmentDoesNotExist
Message: The Role assignment does not exist.
InnerError:
RequestId: b6e750c4-acf4-4032-84ea-29d74fbc53ac
DateTimeStamp: Fri, 25 Mar 2022 19:00:10 GMT
HttpStatusCode: NotFound
HttpStatusDescription: Not Found
HttpResponseStatus: Completed
At line:2 char:5
+ Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId AadRole ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Open-AzureADMSP...signmentRequest], ApiException
+ FullyQualifiedErrorId : Microsoft.Open.MSGraphBeta.Client.ApiException,Microsoft.Open.MSGraphBeta.PowerShell.OpenAzureADMSPrivilegedRoleAssignmentRequest
These were some of the sites that i referred: (all only have example to activate the role)
http://www.anujchaudhary.com/2020/02/connect-to-azure-ad-powershell-with-mfa.html
https://learn.microsoft.com/en-us/azure/active-directory/privileged-identity-management/powershell-for-azure-ad-roles#activate-a-role-assignment
https://www.youtube.com/watch?v=OVfwO8_eDjs
Edit: Sorry I misread some part of your question actually.
In fact, you should adapt the provider id to "aadGroups" in order to use the group features.
This should help you to be on track depending on your environment:
$groupId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$upn="myyupn#domain.com"
Connect-AzureAD
$resource = Get-AzureADMSPrivilegedResource -ProviderId aadGroups
$subject = Get-AzureADUser -Filter "userPrincipalName eq '$upn'"
# here you will require some additionnal filtering depending on your environment
$roleDefinitionCollection = Get-AzureADMSPrivilegedRoleDefinition -ProviderId "aadGroups" -ResourceId $groupId
#this works only when pimed in my case:
#$roleDefinitionCollection = Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadGroups" -ResourceId $resource.id -Filter "ResourceId eq '$groupId' and AssignmentState eq 'Eligible'"
$reason = "test"
foreach ($roleDefinition in $roleDefinitionCollection) {
$schedule = New-Object Microsoft.Open.MSGraph.Model.AzureADMSPrivilegedSchedule
$schedule.Type = "Once"
$schedule.Duration="PT1H"
$schedule.StartDateTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId "aadGroups" -Schedule $schedule -ResourceId $groupId -RoleDefinitionId $roleDefinition.id -SubjectId $subject.ObjectId -AssignmentState "Active" -Type "UserAdd" -Reason $reason
}
When you try to assign the Role, it will be
You Can't be assigned for a duration of less than five minutes.
You Can't be removed within five minutes of it being assigned
Here is your script, you need to wait for 5 minutes for every iteration to create a Group Role Assignment
foreach ($roleDefinition in $roleDefinitionCollection) {
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId AadRoles -Schedule $schedule -ResourceId $resource.Id -RoleDefinitionId $roleDefinition.RoleDefinitionId -SubjectId $subject.ObjectId -AssignmentState "Active" -Type "UserAdd" -Reason $reason
# wait for 5 minutes
Start-Sleep -s 300
}
Refer here for more information

A parameter cannot be found that matches parameter name 'PasswordPolicies' in Powershell

I was trying to set the password for an Azure user to not expire forever. In the process I tried below commands
Get-AzADUser -ObjectId <valid Azure user> | Select-Object UserprincipalName,#{
>> N="PasswordNeverExpires";E={$_.PasswordPolicies -contains "DisablePasswordExpiration"}
>> }
UserPrincipalName PasswordNeverExpires
----------------- --------------------
<valid Azure user> False
To set PasswordNeverExpires to True, I executed below command
Set-AzADUser -ObjectId <valid Azure user> -PasswordPolicies DisablePasswordExpiration
But it throws an error as below:
Update-AzADUser : A parameter cannot be found that matches parameter name 'PasswordPolicies'.
At line:1 char:51
+ ... ADUser -ObjectId <valid Azure user> -PasswordPolicies Disable ...
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Update-AzADUser], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.Azure.Commands.ActiveDirectory.UpdateAzureADUserCommand
Can someone help me on this issue please.
Thanks,
Sri Ram.
Az Powershell doesn't provide the setting password policy feature.
Use Azure AD Powershell instead.
Set-AzureADUser -ObjectId <user ID> -PasswordPolicies DisablePasswordExpiration
If you are concerned about having to log in to Azure AD Powershell again, you can connect a session using an existing token associated with the active azure context.
For example:
# login
Connect-AzAccount -Tenant {your tenant}
# perform other Azure operations...
$currentAzureContext = Get-AzContext
$tenantId = $currentAzureContext.Tenant.Id
$accountId = $currentAzureContext.Account.Id
Connect-AzureAD -TenantId $tenantId -AccountId $accountId
Then you can run Set-AzureADUser cmd.

Authenticated with "Login-AzureRmAccount -ServicePrincipal" but no subscription is set?

I've successfully created a self-signed certificate with application & service principle using the New-AzureRmADApplication and New-AzureRmADServicePrincipal cmdlets.
I can execute the login using this command after retrieving the certificate:
Login-AzureRmAccount -ServicePrincipal -CertificateThumbprint $cert.Thumbprint -TenantId $tenantID -ApplicationId $applicationID
However, the SubscriptionId/SubscriptionName attributes of this authentication display as blank:
Environment : AzureCloud
Account : ********************
TenantId : ********************
SubscriptionId :
SubscriptionName :
CurrentStorageAccount :
Subsquently, this command works!
$secret = Get-AzureKeyVaultSecret -VaultName $vaultName -Name $keyName
What is confusing to me is that I am able to retrieve a AzureKeyVaultSecret in my DEV subscription, but I do not understand how this cmdlet knows which of my subscriptions to use??? I intend to create the same vault in my PROD subscription, but first need to understand how this ServicePrincipal/Certificate authentication knows which subscription to pull from and/or how to manipulate it?
I can say that when I created the App/ServicePrincipal, I logged in specifying the "DEV" subscription like so:
$subscriptionName = "DEV"
$user = "user#company.com"
$password = "*****"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($user, $securePassword)
Login-AzureRmAccount -Credential $credential -SubscriptionName $subscriptionName

Resources