Manage Azure and Microsoft 365 services with PowerShell and CLI
Most of the points in Azure and Office 365 you can administrate with their management web portals, but for some stuff and details you had to use the PowerShell or CLI, not to mention if you want to automate some processes.
Azure PowerShell documentation
https://docs.microsoft.com/en-us/powershell/azure/?view=azps-5.5.0
Azure PowerShell is a set of cmdlets for managing Azure resources directly from the PowerShell command line. Azure PowerShell is designed to make it easy to learn and get started with, but provides powerful features for automation. Written in .NET Standard, Azure PowerShell works with PowerShell 5.1 on Windows, and PowerShell 7.x and higher on all platforms.
Azure Command-Line Interface (CLI) documentation
https://docs.microsoft.com/en-us/cli/azure/
The Azure command-line interface (Azure CLI) is a set of commands used to create and manage Azure resources. The Azure CLI is available across Azure services and is designed to get you working quickly with Azure, with an emphasis on automation.
Choosing the right tooling for Azure and side by side Azure CLI and PowerShell commands
https://devblogs.microsoft.com/premier-developer/choosing-the-right-tooling-for-azure-and-side-by-side-azure-cli-and-powershell-commands/
If you want an entirely cross-platform tooling that will work exactly the same on Mac, Linux, and Windows, use the Azure CLI. In general, the Azure CLI tends to be shorter, easier to remember commands, and it is much easier to pick up this language than PowerShell. The PowerShell commands can get quite lengthy.
Manage Microsoft 365 with PowerShell
https://docs.microsoft.com/en-us/microsoft-365/enterprise/manage-microsoft-365-with-microsoft-365-powershell?view=o365-worldwide
In the following post I want to put some basic cmdlets together you could really need for your daily work.
I will update and add further cmdlets to this post consistently, so far I will start with the basics and a few user cmdlets.
- Managing Azure Ressources
- Connect-AzAccount
- Azure Cloud Shell – Managing Azure Ressources
- PowerShell Modules/APIs to manage Azure and Office 365
- Overview of Microsoft Graph
- Conclusion about the different PowerShell Modules to manage Azure and Office 365
- Login/Logout Azure AD with PowerShell
- Connect to all Microsoft 365 services in a single PowerShell window
- User management with PowerShell
- Company Settings
- Manage Teams
- Manage Exchange Online
- Management Exchange Online Hybrid Relationship
- Manage SharePoint Online
- PowerShell Comparison Operators
Managing Azure Ressources
Connect-AzAccount
Aliases
Login-AzAccount
Add-AzAccount
Get-Alias -Name *AzAccount* | Select Name,ReferencedCommand
Source: https://adamtheautomator.com/connect-azaccount/
Azure Cloud Shell – Managing Azure Ressources
Overview of Azure Cloud Shell
https://docs.microsoft.com/en-us/azure/cloud-shell/overview
Azure Cloud Shell is an interactive, authenticated, browser-accessible shell for managing Azure resources. It provides the flexibility of choosing the shell experience that best suits the way you work, either Bash or PowerShell.
You can access the Cloud Shell in three ways:
- Direct link: Open a browser to https://shell.azure.com.
- Azure portal: Select the Cloud Shell icon on the Azure portal
- Code snippets: On docs.microsoft.com and Microsoft Learn, select the Try It button that appears with Azure CLI and Azure PowerShell code snippets:
Azure CLI: az Login , az account show
az login az login -u <myUsername> # login directly to an different tenant as the default if multiple assigned to this account. az login -u <myUsername> -t <customerTenantId-or-Domain> How to Change Tenants? az account set --subscription <customerSubscriptionId> Azure PowerShell: Get-AzSubscription
PowerShell Modules/APIs to manage Azure and Office 365
To manage Azure AD and Office 365 you can choose currently between three PowerShell modules/APIs MSOnline, Azure AD and Microsoft Graph.
Microsoft Graph PowerShell is the new one and should be used now!
The first PowerShell module to manage Azure AD was the MSOnline V1 PowerShell module with the -Msol cmdlets like Get-MSolUser
Till September 2020, Azure Active Directory PowerShell for Graph (AzureAD) was the recommended PowerShell module from Microsoft to manage Azure AD.
https://docs.microsoft.com/en-us/powershell/module/azuread
The Azure Active Directory PowerShell for Graph module can be downloaded and installed from the PowerShell Gallery, www.powershellgallery.com. The gallery uses the PowerShellGet module. The PowerShellGet module requires PowerShell 3.0 or newer and requires one of the following operating systems:
Windows 10 Windows 8.1 Pro Windows 8.1 Enterprise Windows 7 SP1 Windows Server 2016 TP5 Windows Server 2012 R2 Windows Server 2008 R2 SP1
PowerShellGet also requires .NET Framework 4.5 or above. You can install .NET Framework 4.5 or above from here.
Install-Module -Name AzureAD
Connect-AzureAD
Azure Active Directory PowerShell for Graph: Version release history
https://docs.microsoft.com/en-us/powershell/azure/active-directory/ad-pshell-v2-version-history
You will also find a reference to all cmdlets for the Azure Active Directory PowerShell for Graph module under https://docs.microsoft.com/en-us/powershell/module/azuread
Now as mentioned above since September 2020 the Azure AD Graph API is also deprecated.
https://docs.microsoft.com/en-us/graph/migrate-azure-ad-graph-planning-checklist
Azure AD Graph API is now deprecated. We will continue to provide technical support and security updates but will no longer provide feature updates. Starting June 30th, 2022, we will end support for Azure AD Graph and will no longer provide technical support or security updates. Apps using Azure AD Graph after this time will no longer receive responses from the Azure AD Graph endpoint.
So therefore you should now use the new Microsoft Graph and Microsoft Graph PowerShell Module.
Install the new Microsoft Graph PowerShell Module
The modules are also available on the PowerShell Gallery.
Install-Module -Name Microsoft.Graph
Connect-MgGraph -Scopes “User.Read.All”,”Group.ReadWrite.All”
Get started with the Microsoft Graph PowerShell SDK
https://docs.microsoft.com/en-us/graph/powershell/get-started
Overview of Microsoft Graph
https://docs.microsoft.com/en-us/graph/overview
Microsoft Graph is the gateway to data and intelligence in Microsoft 365. It provides a unified programmability model that you can use to access the tremendous amount of data in Microsoft 365, Windows 10, and Enterprise Mobility + Security. Use the wealth of data in Microsoft Graph to build apps for organizations and consumers that interact with millions of users.
What’s in Microsoft Graph?
Microsoft Graph exposes REST APIs and client libraries to access data on the following Microsoft cloud services:
- Microsoft 365 services: Delve, Excel, Microsoft Bookings, Microsoft Teams, OneDrive, OneNote, Outlook/Exchange, Planner, SharePoint, Workplace Analytics.
- Enterprise Mobility and Security services: Advanced Threat Analytics, Advanced Threat Protection, Azure Active Directory, Identity Manager, and Intune.
- Windows 10 services: activities, devices, notifications, Universal Print (preview).
- Dynamics 365 Business Central.
To find out more, see Major services and features in Microsoft Graph.
Conclusion about the different PowerShell Modules to manage Azure and Office 365
So as now Microsoft Graph PowerShell is the up to date module to manage Azure AD and Office 365, I will focus on these cmdlets but also list some old ones.
The Microsoft Graph module has introduced a prefix to all the Microsoft Graph cmdlets to reduce the chance of conflicts with existing modules.
So for example instead calling Get-User, you will now need to use with the Microsoft Graph module Get-MgUser.Get started with the Microsoft Graph PowerShell SDK
https://docs.microsoft.com/en-us/graph/powershell/get-started
Microsoft Graph REST API v1.0 reference
https://docs.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0
Login/Logout Azure AD with PowerShell
MSOnline (Microsoft Azure Active Directory Module for Windows PowerShell module)
Connect-MsolService
Azure Active Directory PowerShell for Graph module
Connect-AzureAD
Disconnect-AzureAD
Microsoft Graph PowerShell
Connect-MgGraph -Scopes “User.Read.All”,”Group.ReadWrite.All”
Disconnect-MgGraphhttps://docs.microsoft.com/en-us/graph/powershell/get-started#determine-required-permission-scopes
Each API in the Microsoft Graph is protected by one or more permission scopes. The user logging in must consent to one of the required scopes for the APIs you plan to use
Use theConnect-MgGraph
command to sign in with the required scopes
You can add additional permissions by repeating theConnect-MgGraph
command with the new permission scopes.
Microsoft Graph permissions reference
https://docs.microsoft.com/en-us/graph/permissions-reference
Connect to all Microsoft 365 services in a single PowerShell window
When you use PowerShell to manage Microsoft 365, you can have multiple PowerShell sessions open at the same time. You might have different PowerShell windows to manage user accounts, SharePoint Online, Exchange Online, Skype for Business Online, Microsoft Teams, and the Security & Compliance center.
This scenario isn’t optimal for managing Microsoft 365, because you can’t exchange data among those windows for cross-service management. This article describes how to use a single instance of PowerShell to manage Microsoft 365 accounts, Skype for Business Online, Exchange Online, SharePoint Online, Microsoft Teams, and the Security & Compliance Center.
https://docs.microsoft.com/en-us/microsoft-365/enterprise/connect-to-all-microsoft-365-services-in-a-single-windows-powershell-window
This article currently only contains the commands to connect to the Worldwide (+GCC) cloud. Notes provide links to articles about connecting to the other Microsoft 365 clouds.
- You need to install the modules that are required for Azure Active Directory (Azure AD), Exchange Online, SharePoint Online, Skype for Business Online and Teams:
- PowerShell must be configured to run signed scripts for Skype for Business Online and the Security & Compliance Center. Run the following command in an elevated PowerShell session (a PowerShell session that you Run as administrator).
Set-ExecutionPolicy RemoteSigned
Follow these steps to connect to all the services in a single PowerShell window when you’re using just a password for sign-in.
Login Azure AD
$credential = Get-Credential
Run this command to connect to Azure AD by using the Azure Active Directory PowerShell for Graph module.
Connect-AzureAD -Credential $credential
Connect to a specific tenant if your user is assigned to multiple tenants
Connect-AzureAD -Credential $credential -TenantId “contoso.com”
change the tenant with the same user
Connect-AzureAD -TenantId “contoso.com”
Or if you’re using the Microsoft Azure Active Directory Module for Windows PowerShell module, run this command.
Connect-MsolService -Credential $credential
PowerShell Core doesn’t support the Microsoft Azure Active Directory Module for Windows PowerShell module and cmdlets with Msol in their name. You must run these cmdlets from PowerShell.
Run these commands to connect to SharePoint Online. Specify the organization name for your domain. For example, for “litwareinc.onmicrosoft.com”, the organization name value is “litwareinc”.
Connect to SharePoint Online
First install the Microsoft Online SharePoint PowerShell module if not already done.
https://www.powershellgallery.com/packages/Microsoft.Online.SharePoint.PowerShell
Install-Module -Name Microsoft.Online.SharePoint.PowerShell
$orgName=”<for example, litwareinc for litwareinc.onmicrosoft.com>”
$credential = Get-Credential
Connect-SPOService -Url https://$orgName-admin.sharepoint.com -Credential $Credential
Run these commands to connect to Skype for Business Online. A warning about increasing the WSMan NetworkDelayms
value will appear the first time that you connect. Ignore it.
Skype for Business Online Connector is currently part of the latest Teams PowerShell module. If you’re using the latest Teams PowerShell public release, you don’t need to install the Skype for Business Online Connector.
Connect to Skype for Business Online
Import-Module MicrosoftTeams
$credential = Get-Credential
$sfboSession = New-CsOnlineSession -Credential $credential
Import-PSSession $sfboSession
Migrating from Skype for Business Online Connector to the Teams PowerShell module
https://docs.microsoft.com/en-US/microsoftteams/teams-powershell-move-from-sfbo
Skype for Business Online Connector connections will be rejected starting May 17, 2021. Please contact Microsoft Support for help and support for migrating to Teams PowerShell Module.
How to Migrate
Install the latest Teams PowerShell module. For steps, see Install Microsoft Teams PowerShell.
Uninstall Skype For Business Online Connector. To do this, in Control Panel, go to Programs and Features, select Skype for Business Online, Windows PowerShell Module, and then select Uninstall.
In your PowerShell scripts, change the module name that’s referenced in Import-Module from SkypeOnlineConnector or LyncOnlineConnector to MicrosoftTeams.
When using Teams PowerShell Module 2.0 or later, update your scripts that refers New-CsOnlineSession to Connect-MicrosoftTeams.Import-PsSession is no longer required to establish a Skype for Business Online Remote PowerShell Session as that is done implicit when using Connect-MicrosoftTeams.
!!! Important !!!
If you’re using the latest Teams PowerShell public preview release, you don’t need to install the Skype for Business Online Connector!
The Skype for Business Online commands have been merged with the Teams PowerShell module since version 1.1.6.
If you’re using the Public Preview version of Teams PowerShell, we strongly recommend that you first uninstall Skype for Business Online Connector.
You can find the latest preview version at PowerShell Gallery or in PowerShell by running “Find-Module MicrosoftTeams -AllowPrerelease -AllVersions”
Install-Module -Name MicrosoftTeams -AllowPrerelease -Force
Microsoft Teams PowerShell Overview
https://docs.microsoft.com/en-us/MicrosoftTeams/teams-powershell-overview
Comparison how to connect with Skype for Business online connector vs. Teams PowerShell Module 2.0 and later
# When using the Skype for Business online connector # Establishing a session Import-Module SkypeOnlineConnector [LyncOnlineConnector] $credential = Get-Credential $SkypeSession = New-CsOnlineSession -Credential $credential Import-Session $SkypeSession # Example getting tenant details Get-csTenant # Disconnecting and closing the Session Get-PsSession $SkypeSession | Remove-PsSession # When using Teams PowerShell Module 2.0 or later # Establishing a session Import-Module MicrosoftTeams $credential = Get-Credential Connect-MicrosoftTeams -Credential $credential # Example getting tenant details Get-csTenant # Disconnecting and closing the Session Disconnect-MicrosoftTeams
Run these commands to connect to Teams PowerShell.
Connect to Teams
Import-Module MicrosoftTeams
$credential = Get-Credential
Connect-MicrosoftTeams -Credential $credential
# Disconnect from the Microsoft Teams environment.
Disconnect-MicrosoftTeams
To connect to Microsoft Teams clouds other than Worldwide, see Connect-MicrosoftTeams.
Sign in using MFA and modern authentication
If your account uses multi-factor authentication, use the steps in this section.
Connect-MicrosoftTeams -AccountId <UPN>
Run this command to connect to Exchange Online.
To connect to Exchange Online for Microsoft 365 clouds other than Worldwide, see Connect to Exchange Online PowerShell.
Connect to Exchange Online
If not already installed, you first need to install the Exchange Online PowerShell module.
https://www.powershellgallery.com/packages/ExchangeOnlineManagement
Install-Module -Name ExchangeOnlineManagement
To force to upgrade to a new release
Install-Module -Name ExchangeOnlineManagement -Force
Import-Module ExchangeOnlineManagement
$credential = Get-Credential
Connect-ExchangeOnline -Credential $credential -ShowProgress $true
Alternatively, run these commands to connect to the Security & Compliance Center.
$acctName=”<UPN of the account, such as belindan@litwareinc.onmicrosoft.com>”
Import-Module ExchangeOnlineManagement
Connect-IPPSSession -UserPrincipalName $acctName
# Disconnect the remote PowerShell session
Disconnect-ExchangeOnline
Here are the commands for all the services except Security & Compliance Center in a single block when you use the Azure Active Directory PowerShell for Graph module. Specify the name of your domain host and run them all at the same time.
Connect to All services
$orgName="<for example, litwareinc for litwareinc.onmicrosoft.com>" $credential = Get-Credential Connect-AzureAD -Credential $credential Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking Connect-SPOService -Url https://$orgName-admin.sharepoint.com -credential $credential Import-Module MicrosoftTeams $sfboSession = New-CsOnlineSession -Credential $credential Import-PSSession $sfboSession Import-Module ExchangeOnlineManagement Connect-ExchangeOnline -Credential $credential -ShowProgress $true Import-Module MicrosoftTeams Connect-MicrosoftTeams -Credential $credential
User management with PowerShell
So as now Microsoft Graph PowerShell is the up to date module to manage Azure AD and Office 365, I will focus on this cmdlets but also list some old ones.
Manage Microsoft 365 user accounts, licenses, and groups with PowerShell
https://docs.microsoft.com/en-us/microsoft-365/enterprise/manage-user-accounts-and-licenses-with-microsoft-365-powershell
MSOnline
To display the full list of user accounts
Get-MsolUser
List user accounts with errors.
Get-MsolUser -HasErrorsOnly
To retrieve the errors on user object
$errors = (get-msoluser -userprincipalname “jdoe@braintesting.de”).Error
$errors | foreach-object {“`nService: “+ $_.ErrorDetail.Name.split(“/”)[0]; “Error Message: “+ $_.ErrorDetail.ObjectErrors.ErrorRecord.ErrorDescription}
List specific user
Get-MsolUser -UserPrincipalName jdoe@braintesting.de | fl UserPrincipalName,ObjectId
For the list of unlicensed users
Get-MsolUser -UnlicensedUsersOnly
View accounts based on a common property
Get-MsolUser | Where {$_.UsageLocation -eq $Null}
Get-MsolUser | Where {$_.City -eq “Stuttgart”}
To see all of the properties for user accounts, use the Select cmdlet and the wildcard character (*) to display them all for a specific user account
Get-MsolUser -UserPrincipalName jdoe@braintesting.de | Select *
Azure Active Directory PowerShell for Graph module
https://docs.microsoft.com/en-us/powershell/module/azuread/set-azureaduser
List specific user
Get-AzureADUser -SearchString mrath@braintesting.de | fl UserPrincipalName,OnPremisesSecurityIdentifier,ObjectId$user = Get-AzureADUser -ObjectId mrath@braintesting.de
Change UPN
Get-AzureADUser -ObjectId <ObjectID of the User> | fl
Set-AzureADUser -ObjectId <ObjectID of the User> -UserPrincipalName John.Nokes@domain.tld
Change Displayname
Get-AzureADUser -ObjectId <ObjectID of the User> | fl
Set-AzureADUser -ObjectId <ObjectID of the User> -Displayname ‘John Nokes’
alternative instead of each time copying the ObjectID you can use a variable:
$user = Get-AzureADUser -ObjectId John.Nokes@domain.tld
$user.DisplayName = ‘John Nokes’
Set-AzureADUser -ObjectId John.Nokes@domain.tld -Displayname $user.Displayname
Check which Recipient Object (User, Group, all mail enabled objects) have assigned a specific Email Alias (Proxy)
Get-Recipient | where {$_.EmailAddresses -match “user@domain.tld”} | fL Name, RecipientType,emailaddresses
List Azure AD User SIDs by using Azure AD PowerShell module
$credential = Get-Credential Connect-AzureAD -Credential $credential function Convert-ObjectIdToSid { param([String] $ObjectId) $d=[UInt32[]]::new(4);[Buffer]::BlockCopy([Guid]::Parse($ObjectId).ToByteArray(),0,$d,0,16);"S-1-12-1-$d".Replace(' ','-') } # Get and convert all Azure Users: Get-AzureADUser | ForEach { [pscustomobject] @{ Name= $_.DisplayName; Sid=Convert-ObjectIdToSid($_.ObjectId)}} #Get and convert Azure User with the UPN jdoe@braintesting.de Get-AzureADUser -SearchString jdoe@braintesting.de | ForEach { [pscustomobject] @{ Name= $_.DisplayName; Sid=Convert-ObjectIdToSid($_.ObjectId)}}
Microsoft Graph PowerShell
List all users in Tenant
Get-MgUser
List specific user
Get-MgUser -Filter “displayName eq ‘Marcus Rath'”
Get-MgUser -Filter “UserPrincipalName eq ‘mrath@braintesting.de'”
List the user’s joined Teams
$user = Get-MgUser -Filter “UserPrincipalName eq ‘mrath@braintesting.de'”
$team = Get-MgUserJoinedTeam -UserId $user.ID
or limit the output of Teams with
$team = Get-MgUserJoinedTeam -UserId $user.ID -Filter “displayName eq ‘Sales and Marketing’
List Team channels
Get-MgTeamChannel -TeamId $team.Id
$channel = Get-MgTeamChannel -TeamId $team.Id -Filter “displayName eq ‘General'”
or with the comparison operator -like
Get-MgUserJoinedTeam -UserId $user.ID | Where-Object {$_.DisplayName -like “Team*”}
Changing the primary email address / Alias of an Microsoft 365 Group (Unified Group)
Get-UnifiedGroup -Identity <groupname> | fl
Set-UnifiedGroup -Identity <groupname> -PrimarySmtpAddress “teams-group@domain.tld”
Set-UnifiedGroup -Identity <groupname> -alias “teams2-group@domain.tld”
# Remove proxy/alias
Set-UnifiedGroup -Identity <groupname> -emailaddresses @{remove=”teams2-group@domain.tld”}
Overview of Microsoft 365 Groups (Unified Groups) for administrators
https://docs.microsoft.com/en-us/microsoft-365/admin/create-groups/office-365-groups?view=o365-worldwide
Skype for Business Online
Get-CsOnlineUser -Identity jdoe
Set-CsUser -Identity jdoe
Exchange Online
List all Mailboxes sorted by size
Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Select-Object DisplayName, @{Name="TotalItemSizeGB"; Expression={[math]::Round(($_.TotalItemSize.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1GB),0)}}, ItemCount | Sort-Object -Property TotalItemSizeGB -Descending
Company Settings
MSOnline
self-service sign-up enable/disable
https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/directory-self-service-signupThe following command will allow users to perform self-service sign-up, but only if those users already have an account in Azure AD (in other words, users who would need an email-verified account to be created first cannot perform self-service sign-up)
Set-MsolCompanySettings -AllowEmailVerifiedUsers $false -AllowAdHocSubscriptions $true
Manage Teams
New-CsOnlinePSTNGateway
https://docs.microsoft.com/en-us/powershell/module/skype/new-csonlinepstngateway
New-CsOnlinePSTNGateway -Fqdn sbc-ms365.braintesting.de -SipSignalingPort 5061 -MaxConcurrentSessions 100 -ForwardCallHistory $true -MediaBypass $true -Enabled $true
Manage Exchange Online
Get-Mailbox
https://docs.microsoft.com/en-us/powershell/module/exchange/get-mailbox
Get-Mailbox -Identity <UserPrincipalName> | fl
Get-Mailbox -Identity jdoe@braintesting.de | fl ExchangeGUID,Name,Alias,UserPrincipalName,DisplayName,EmailAddresses,PrimarySmtpAddress,Identity
Get-User
https://docs.microsoft.com/en-us/powershell/module/exchange/get-user?view=exchange-ps
Get-MailUser
https://docs.microsoft.com/en-us/powershell/module/exchange/get-mailuser?view=exchange-ps
Get-Recipient
https://docs.microsoft.com/en-us/powershell/module/exchange/get-recipient?view=exchange-ps
Set-User
https://docs.microsoft.com/en-us/powershell/module/exchange/set-user?view=exchange-ps
Set-MailUser
https://docs.microsoft.com/en-us/powershell/module/exchange/set-mailuser?view=exchange-ps
Management Exchange Online Hybrid Relationship
Get-OrganizationRelationship
https://docs.microsoft.com/en-us/powershell/module/exchange/get-organizationrelationship
This cmdlet is available in on-premises Exchange and in the cloud-based service. Some parameters and settings may be exclusive to one environment or the other.
Use the Get-OrganizationRelationship cmdlet to retrieve settings for an organization relationship that has been created for federated sharing with other federated Exchange organizations or for hybrid deployments with Exchange Online.
Get-IntraOrganizationConnector
https://docs.microsoft.com/en-us/powershell/module/exchange/get-intraorganizationconnector
This cmdlet is available in on-premises Exchange and in the cloud-based service. Some parameters and settings may be exclusive to one environment or the other.
Use the Get-IntraOrganizationConnector cmdlet to view the settings of Intra-Organization connectors.
$cred=Get-Credential Connect-MsolService -Credential $cred $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $cred -Authentication Basic –AllowRedirection Import-PSSession $session Get-OrganizationRelationship -Identity "O365 to On-premises" #delete with Remove-OrganizationRelationship -Identity "O365 to On-premises" # Gracefully disconnect from Azure Active Directory Remove-PSSession $Session
Manage SharePoint Online
Lock and unlock sites
Get-SPOSite -Identity <SiteURL> | fl LockState
Set-SPOSite -Identity <SiteURL> -LockState Unlock
Where: SiteURL is the URL of the site that you want to lock or unlock and State is one of the following values:
- Unlock to unlock the site and make it available to users.
- ReadOnly to prevent users from adding, updating, or deleting content. A message will appear on the site stating that the site is under maintenance and is read-only.
- NoAccess to prevent users from accessing the site and its content. If you’ve provided a NoAccessRedirectUrl value for your organization (below), traffic will be redirected to the URL you specified. If you haven’t set this URL, a 403 error will be displayed.
If the site was closed and made read-only through a site closure policy, the PowerShell command to unlock the site will not work.
Set-SPOTenant -NoAccessRedirectUrl 'https://www.contoso.com'
For more info about the LockState parameter, see Set-SPOSite. For more info about the NoAccessRedirectUrl parameter, see Set-SPOTenant.
Source: https://learn.microsoft.com/en-us/sharepoint/manage-lock-status
PowerShell Comparison Operators
About Comparison Operators
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7