SamTech 365

Power Platform, Copilot & SharePoint guides by Samir Daoudi

PowerShell Scripts for SharePoint, Microsoft Teams, Microsoft 365 and Azure

Practical PowerShell scripts for SharePoint Online and Server, Microsoft Teams, Microsoft 365 groups and Azure web apps, explained step by step.
SharePoint PowerShell Site Collections Extract – SharePoint PowerShell - Extract a list of all Site collections to a .csv fil

PowerShell is still the fastest way to audit, bulk-update and govern SharePoint, Microsoft Teams, Microsoft 365 and Azure. This page collects the practical PowerShell scripts I’ve written and used on client projects over the years, grouped by workload, so you can find the one you need in one place.

Each script includes a short explanation. Test scripts in a non-production tenant or farm first, and run them with an account that has only the permissions it needs.

Contents

Getting started with PowerShell for Microsoft 365

Start here if you’re new to scripting Microsoft 365. These notes cover reading input from text and CSV files, connecting to Microsoft 365, and creating security groups.

Note for 2026: the legacy MSOnline and AzureAD modules mentioned in some older scripts have been retired. For identity, user and group tasks, use the Microsoft Graph PowerShell SDK (Connect-MgGraph) instead. The logic of the scripts stays the same; only the cmdlets change.

PowerShell for Office 365: getting started

In this post we will get started with PowerShell for Office 365, before digging into more complex details related to the administration fo SharePoint, Exchange Online, Office365 Users…etc, let’s first start by getting some basic knowledges about PowerShell.

1- Setting up your environment

Windows

For windows users, most of the Windows editions > Windows 7 SP1, will have PowerShell installed by default, if not, you can enable it  by following this simple article from Microsoft

https://docs.microsoft.com/en-us/powershell/scripting/getting-started/starting-windows-powershell?view=powershell-7

MacOS

My preferred Device and OS ? (Sorry MS, I tried all the surface devices, but can’t separate from my Mac ?)

  • To Install PowerShell,  you can simply open a terminal and run
brew cask install powershell

This assuming you have brew installed on your MacOS, if not, here is how you can install it : https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-macos?view=powershell-7#about-brew

  • To start PowerShell, just type the following command
pwsh
  • To check for an update, and install the latest version of PowerShell
brew update
brew cask upgrade powershell

2- Getting started with PowerShell

Be re-assured, you are not expected and might not be able to remember all the commands, properties, members …etc available in PowerShell (if you do, you need to get a life ?).

However, you can easily get help from PowerShell, using some of the existant commands such as :

  • Get-Command
    • This command allows you to list all the commands available in PowerShell, you can filter by a sub string, for example, if I am looking for all the commands with the word Host, I can do:
      Get-Command *Host
  • Get-Help
    • This command allows you to get the details of a specific command, for example, I want to know what does the Get-PSDrive command do and how can I use it (which parameters does it expect and what results does it return), for this, I can simply type:
      Get-Help Get-SPDrive

      Which will return the following output

      PowerShell for Office 365: getting started

    • If you want to see the online help for this command, you can simply type:
      Get-Help Get-SPDrive -Online
  • Get-Member
    • This command allows you to list all the properties & methods for a specific command. For example, I want to see the members and properties of the Get-Service command, I can simply type:
    • Get-Service | Get-Member

       

3- Update the help

If the help you get from Get-Help is not up to date, or the Get-Help can’t find a specific command (this is very frequent when you install a new module), you can simply update the help section which will download all the files and details of the available commands, simply type:

Update-Help

I will skip the part where we talk about how to Write-Host, do a loop, declare a variable …etc, as this is just a quick introduction before we jump into the more serious things related to Office365.

I believe there are plenty of ressources online if you want to improve your PowerShell skills, but for me, I will just give you what we need to jump to the next step which is way more fun ?.

4- Create a function

You can easily create a function and call from different places in your code.

Please be aware that similarly to JavaScript the function needs to be declared before you call it.

function Add ($a, $b)
{
    $result = $a+$b
    Write-Host "The result is $result"
}

5- Call a function

You can simply do:

add 3,4

6- Reference another .PS1 file

Let’s say you have your library of functions (Send Email, Write to Windows Log, Encrypt …etc.) you can reference your functions.PS1 file from another .PS1 script and call the functions listed in that file. For this, just type in your Main.ps1

. ./functions.ps1

What’s next ?

In the next post, I will take you through the modules you need to install to be able to authenticate and connect to your Office365 tenant and be able to administer it properly.

Reading input from TXT and CSV files

In Today’s article we will have a look at how you can read data from the two main filetypes you can feed your PowerShell Script.

1- From a TXT file

A text file is useful if you want to provide a list of entries, each row will contain one piece of information, I will say, that this is the simplest and easiest way to feed information to your .PS1 script.

Let’s suppose we have a list of items file called “ListItems.txt“, which will look like this:

PowerShell (Part 2) - Feeding files

Your code which will loop over each line and output the result will look like this:

$List= Get-Content ListItems.txt
foreach ($item in $List) {
    Write-Host $item
}

 

When we run this script :

PowerShell (Part 2) - Feeding files

2- From a CSV file

If you want to have multiple information in your input files (example a list of products), you can use a CSV file.

My input file “listitems.csv” look like this:

PowerShell (Part 2) - Feeding files

And the script to read each line and output each column will be :

$List= Import-CSV ListItems.csv
foreach ($item in $List) {
    Write-Host $item.Product
    Write-Host $item.Description
    Write-Host $item.Price
    Write-Host "------------"
}

Please note that we can use the column name as a property of the $item (which is the line ref in our scenario)

PowerShell (Part 2) - Feeding files

Setting up your environment for Office 365 administration

In order to start using PowerShell for Office365 Admin tasks, you need to following :

Or you can also install the module directly from PowerShell as follow:

Install-Module MSOnline
  • You need to have Office365 Administrator Rights.
  • A 64-bit machine
  • At least Windows 7 SP1+ or Windows Server 2008R2+

 

Once you have installed the pre-requisites, you need to

1- Import the module into PowerShell

For this, simply type:

Import-Module MSOnline

PowerShell (Part 3) - Setting up your environment for Office365

2- Get Connection Credentials

In order to create a credential object, we can do:

$cred= Get-Credential

Once you run this command, you will be prompted to enter your username and password. Please be aware that at this stage there is no validation of the username and password.

PowerShell (Part 3) - Setting up your environment for Office365

3- Establish Connection

Now, to connect to your tenant, just type:

Connect-MsolService -Credential $cred

Note that we pass the $cred object which contains the username and password supplied in the previous step.PowerShell (Part 3) - Setting up your environment for Office365

If the connection is successful, you won’t see any output.

4- List all users in your tenant

In order to test that we are properly connected to our tenant, we can simply list all the users by doing :

Get-MsolUser

Which will output a table of PrincipalName, DisplayName and isLicensed boolean.

PowerShell (Part 3) - Setting up your environment for Office365

Essential PowerShell commands for Office 365

Now that we know how to set up our PowerShell environment for Office 365, we will look at the available commands.

It is impossible to cover all the commands in a series of article, this is why, I will concentrate on the most important ones, the commands that you need the most.

Once you are comfortable with these commands, you can find a lot of resources and help online, you can simply check the Microsoft Docs.

Most of the commands have a Verb (Get, Set) and a Noun.

Most of the PowerShell Office365 commands look like All the commands look like <Verb>-Msol<Noun>

Get–MsolUser,  New–MsolLicenceOptions.

1- List all the users in Office365 Tenant

As we’ve seen in the previous article, you can list all the users in you tenant by simply running the following command.

Get-Msoluser

Essential PowerShell commands for Office 365

 

If I wanted to filter my users by department, I could have done:

Get-MsolUser -Department IT

We can filter by any property of the user object (e.g. -City Algiers).

1.1 Export the users list

If you want to export the users list to a .txt file or a .csv, you can simply do:

Get-MsolUser > users.txt

Essential PowerShell commands for Office 365

 

2- Update a user details

You can simply change any of the properties of a user object, this can be achieved by simply running the following command:

Set-MsolUser -UserPrincipalName samir.daoudi@logisam.net -LastName "Daoudi" -DisplayName "Samir D"

In this example, I have changed my own Last name and display name in my Dev Office 365 Tenant.Essential PowerShell commands for Office 365

 

PS: In the Office 365 Admin center might take couple of seconds to show the update accounts.

 

  1. Get the Office 365 Licences

If we want to list the different licences that we have in our office 365 tenant including the active, consumed and warning Units, we can simply run the following command:

Get-MsolAccountSku

Essential PowerShell commands for Office 365

 

If we wanted to see the status of these licences, and display whether they are all activated and used, we can simply do :

$sku = Get-MsolAccountSku
$sku.ServiceStatus

Essential PowerShell commands for Office 365

 

3- Create a new user in Office365

In order to create a new user in your Office365 tenant, you can simply use the New-MsolUser command, which take couple of

New-MsolUser -UserPrincipalName netrm@logisam.net -DisplayName "Net RM" -FirstName "Net" -LastName "RM" -LicenseAssignment logisam:FLOW_FREE -UsageLocation CA

We need to define some mandatory properties, such as the UserPrincipleName, FirstName, LastName , but most  importantly the LicenceAssignment and the Usage Location.

PS: You can’t create a user without the UsageLocation property.

Essential PowerShell commands for Office 365

 

4- Limiting  Licence Usage with PowerShell

We can create a custom licence pack, which will contain only the products we want to assign to the user.

$NewSku= New-MsolLicenseOptions -AccountSkuId logisam:O365_BUSINESS_PREMIUM -DisabledPlans EXCHANGE_S_FOUNDATION, VISIOONLINE

Now, to set this newly created custom licence, we can simply do:

Set-MsolUserLicense -UserPrincipalName "netrm@logisam.net" -LicenseOptions $NewSku

 

Creating security groups and adding members

Now we can create start looking at the more serious stuffs, such as creating security groups and assigning users

1- Create a Security Group

In order to create a security group, we can simple do:

New-MsolGroup -DisplayName "SocialMedia" -Description "Social Media"

PowerShell (Part 5) - Security Groups

 

2- Retrieve a Security Group

We can either do a Get-MsolGroup which will list all the groups, or a better and cleaner way doing is by filtering by a specific keyword

Get-MsolGroup | Where-Object {$_.DisplayName -eq "SocialMedia"}

PowerShell (Part 5) - Security Groups

 

3- List a Security Group members

If you want to display the users in a certain Security Group, we can simply do:

$LogiSam = Get-MsolGroup | Where-Object {$_.DisplayName -eq "LogiSam"}
Get-MsolGroupMember -GroupObjectId $LogiSam.ObjectId

PowerShell (Part 5) - Security Groups

4- Add a member to a Security Group

In order to add a new member to an existing Security Group, we can do:

PowerShell (Part 5) - Security Groups

Create users and assign licences with PowerShell

In this article, we will look at how to create users in your Office365 tenant using PowerShell.

The scenario we will be looking at is the following:

A request from the HR department to create multiple users from a list of new joiners of the company.

We will be using mainly the command New-MsolUser, which takes a variety of parameters. Create users and assign licences with PowerShell
A typical input file, will look like this:

 

Create users and assign licences with PowerShell

1. Connect to your Office365 Tenant

Already covered in a previous post, you can review how you can setup and connect to your Office365 Tenant  PowerShell (Part 3) – Setting up your environment for Office365

Import-Module MSOnline
$Cred=Get-Credential 
Connect-MSolservice -Credential $Cred

2. Import the CSV File

$users=import-csv 'C:\PowerShell\users.csv'

foreach ($user in $users) {
$FirstName = $user.FirstName
$LastName = $user.LastName
$Country = $user.Country
$City = $user.City
$Title = $user.Title
$Department = $user.Department
$Office = $user.Office
....
}

You can review this post, to know more about how to feed files to your PowerShell Script PowerShell (Part 2) – Feeding files

3.Create the users and set the properties

Now, we need to loop over each row, get the column values, which will be used later to create the users using the New-MSolUser commandlet.

foreach ($user in $users) {
$FirstName = $user.FirstName
$LastName = $user.LastName
$Country = $user.Country
$City = $user.City
$Title = $user.Title
$Department = $user.Department
$Office = $user.Office

$DisplayName= $LastName + ", " + $FirstName
$UserName = $FirstName+"." + $LastName+"@logisam.net"
New-MsolUser -DisplayName $DisplayName -UserPrincipalName $UserName -FirstName $FirstName -LastName $LastName -Country $Country -City $City -Title $Title -UsageLocation $Country -LicenseAssignment "logisam:POWER_BI_STANDARD"
}

Here is the output you get once you run this script.

Create users and assign licences with PowerShell

As you can see, the passwords for these accounts will be in the output screen.

If you log back to your Office365 Admin portal, you will see your newly created and licensed users.

 

Create users and assign licences with PowerShell

 

Microsoft Teams PowerShell scripts

These scripts use the MicrosoftTeams module to audit and govern Teams at scale.

List all Microsoft Teams with PowerShell

Last week, I have been faced with a serious issue for which I had to act very quickly.

A typical SharePoint search started showing content from different teams, which have been all set as public teams.

A direct result of quickly jumping into using Teams due to the current pandemic and the need for remote work enabling, without enough time to think about Teams Governance or the security aspect of the content.

I am sure, this is the case of many organisations.

The problem was to find all the public teams and quickly lock them down to private teams and private channels.

Doing this via the Teams Admin portal would have taken days, so I had to write a PowerShell Script to first list all the public teams, then switch them to private after internal review.

 

List all the teams

Requirements

The following PowerShell script requires the following:

  1. Microsoft Teams module for powershell  available from:
    1. Install the Microsoft Teams module via PowerShell Gallery(recommended option).
    2. Install the Microsoft Teams PowerShell module via Manual Download.
  2. Having Teams or Tenant admin rights.

Once these two requirements were in place, time for the action:

The Script

 

$Result = ""  
$Results = @() 
$Path = "./Teams Report_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv"
Write-Host Exporting all Teams report...
$Count = 0
Get-Team | foreach {
    $TeamName = $_.DisplayName
    Write-Progress -Activity "`n     Processed Teams count: $Count "`n"  Currently Processing: $TeamName"
    $Count++
    $Visibility = $_.Visibility
    $MailNickName = $_.MailNickName
    $Description = $_.Description
    $Archived = $_.Archived
    $GroupId = $_.GroupId
    $ChannelCount = (Get-TeamChannel -GroupId $GroupId).count
    $TeamUser = Get-TeamUser -GroupId $GroupId
    $TeamMemberCount = $TeamUser.Count
    $TeamOwnerCount = ($TeamUser | ? { $_.role -eq "Owner" }).count
    $Result = @{'Teams Name' = $TeamName; 'Team Type' = $Visibility; 'Mail Nick Name' = $MailNickName; 'Description' = $Description; 'Archived Status' = $Archived; 'Channel Count' = $ChannelCount; 'Team Members Count' = $TeamMemberCount; 'Team Owners Count' = $TeamOwnerCount }
    $Results = New-Object psobject -Property $Result
    $Results | select 'Teams Name', 'Team Type', 'Mail Nick Name', 'Description', 'Archived Status', 'Channel Count', 'Team Members Count', 'Team Owners Count' | Export-Csv $Path -NoTypeInformation -Append
}
Write-Progress -Activity "`n     Processed Teams count: $Count "`n"  Currently Processing: $TeamName" -Completed
if ((Test-Path -Path $Path) -eq "True") {
    Write-Host `nReport available in $Path -ForegroundColor Green
}

 

Export all Microsoft Teams members and owners to CSV

In this script, we will look at exporting all Microsoft Teams’ Owners and Members to a CSV file.

This extract might help to communicate with all the owners, in my previous example, we had to send a notification to all the owners, telling them that the teams will be switched from Public to Private.

 

List all the teams’ owners and memebrs

Requirements

The following PowerShell script requires the following:

  1. Microsoft Teams module for powershell  available from:
    1. Install the Microsoft Teams module via PowerShell Gallery(recommended option).
    2. Install the Microsoft Teams module via Manual Download.
  2. Having Teams or Tenant admin rights.

Once these two requirements were in place, time for the action:

 

The script

$Result = ""  
$Results = @() 
$Path = "./All Teams Members and Owner Report_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv"
Write-Host Exporting all Teams members and owners report...
$Count = 0
Get-Team | foreach {
    $TeamName = $_.DisplayName
    Write-Progress -Activity "`n     Processed Teams count: $Count "`n"  Currently Processing: $TeamName"
    $Count++
    $GroupId = $_.GroupId
    Get-TeamUser -GroupId $GroupId | foreach {
        $Name = $_.Name
        $MemberMail = $_.User
        $Role = $_.Role
        $Result = @{'Teams Name' = $TeamName; 'Member Name' = $Name; 'Member Mail' = $MemberMail; 'Role' = $Role }
        $Results = New-Object psobject -Property $Result
        $Results | select 'Teams Name', 'Member Name', 'Member Mail', 'Role' | Export-Csv $Path -NoTypeInformation -Append
    }
}
Write-Progress -Activity "`n     Processed Teams count: $Count "`n"  Currently Processing: $TeamName" -Completed
if ((Test-Path -Path $Path) -eq "True") {
    Write-Host `nReport available in $Path -ForegroundColor Green
}

 

Set all Microsoft Teams to private

In this script, we will look at setting all the Teams to private. As a lot of users would have created Teams without bothering to think who needs to be added to them.

A quick fix to this potential risk (of data leak), is to set all the teams to private and then work with the Teams’ Owners to set the right members for each team.

In the previous script, I was able to export all the teams’ owners and members to a csv file, which can be used to drive the comms.

Set all the teams to private

Requirements

The following script requires the following:

  1. Microsoft Teams module for powershell  available from:
    1. Install the Microsoft Teams PowerShell module via PowerShell Gallery(recommended option).
    2. Install the Microsoft Teams PowerShell module via Manual Download.
  2. Having Teams or Tenant admin rights.

Once these two requirements were in place, time for the action:

 

The script

 

Get-Team | foreach {
     $GroupId=$_.GroupId
     Set-Team -GroupId $GroupId -Visibility Private
}

 

SharePoint Online PowerShell scripts

Scripts for SharePoint Online audits and governance. See also extracting SharePoint external users with PowerShell and applying a custom colour theme to SharePoint Online.

Export all SharePoint site collections to a CSV file

Currently conducting a SharePoint Security audit project, I thought others might benefit from a series of PowerShell scripts that allow you to extract useful insights and details regarding your SharePoint online.

The first script is a simple PowerShell script that enables you to export a list of all your SharePoint site collections to a .csv file.

The extract contains the following details:

  • Site URL
  • Storage Usage
  • Admins
  • Is Connected to Teams: A boolean value which distinguishes Teams Sites VS SharePoint Sites
  • Teams Channel Type (if applicable)
  • Site Title
  • Site Template
  • M365 Group ID
  • Number of subsites.
#Connect to Admin Center
Connect-SPOService -Url "https://yourtenant-admin.sharepoint.com"
 
#Get All site collections
$SiteCollections = Get-SPOSite -Limit All
$SiteReport = @()
 
#Iterate through each site
ForEach ($site in $siteCollections) {
    # Generate a report of site collection properties
    $siteReport += [PSCustomObject]@{
        URL = $Site.Url
        StorageUsage = $Site.StorageUsageCurrent
        Admins= $Site.Owner
        IsConnectedToTeams = $Site.IsTeamsConnected
        TeamsChannelType=$Site.TeamsChannelType
        Title=$Site.Title
        Template=$Site.Template
        GroupId=$Site.GroupId
        SubSitesCount=($Site.WebsCount-1)
    }
}
$SiteReport | Export-Csv -Path "C:\SPAudit\SiteCollections.csv" -NoTypeInformation

 

SharePoint Server (on-premises) PowerShell scripts

These scripts target SharePoint Server farms using the SharePoint Management Shell (Microsoft.SharePoint.PowerShell). They still help when you audit legacy farms before a migration to SharePoint Online.

List all SharePoint sites and output them to a text file

Here is a simple and quick powershell script to enumerate all the sub sites in SharePoint and output the results to a text file

 

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”) > $null

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$websvcs = $farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.SharePoint.Administration.SPWebService]}
$webapps = @()

#$List = @()

foreach ($websvc in $websvcs)
{
    foreach ($webapp in $websvc.WebApplications)
    {      
            foreach ($site in $webapp.Sites)
            {
                write-host $site.URL
                  foreach ($web in $site.AllWebs)
                  {
                      write-host $web.URL  “,” $web.TITLE       
              $web.URL + “,” + $web.TITLE | out-file -filepath C:\list_of_sites.txt -append                  
              
                }

             }

     }
}
go

List SharePoint sites with the users in their Owners groups

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”) > $null

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$websvcs = $farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.SharePoint.Administration.SPWebService]}
$webapps = @()

foreach ($websvc in $websvcs)
{
foreach ($webapp in $websvc.WebApplications)
{
foreach ($site in $webapp.Sites)
{
write-host $site.URL
foreach ($web in $site.AllWebs)
{
write-host $web.URL
foreach ($group in $web.Groups)
{
$G = $group.Name
if ($G -match “owner”)
{
write-host ”  –>” $G
foreach ($user in $group.Users)
{
write-host ”     –>” $user.Name
write-host “”
}
}
}
}
}

}
}
GO

Activate, deactivate and list SharePoint features

Starting to love PowerShell more and more (thx to Shehzad & Ryan) 😉
I was more a C# coder than a script writer, however every day, I can see the power behind the machine (Daoudi Samir).

In this article, I wanted to summarize some of the useful powershell commands related to Features manipulation.

List all installed features on the farm
It’s really straight forward using the Get-SPFeature command to return all installed features. To provide a little more readability to the output it can be sorted as follows:
By feature display name alphabetically,

1 Get-SPFeature | Sort -Property DisplayName

By feature ID,

1 Get-SPFeature | Sort -Property Id

By feature display name alphabetically and grouped by scope,

1 Get-SPFeature | Sort -Property Scope,DisplayName | FT -GroupBy Scope DisplayName,Id

And to write this to a file to allow for viewing in Notepad, Excel etc,

1 Get-SPFeature | Sort -Property Scope,DisplayName | FT -GroupBy Scope DisplayName,Id > c:\AllInstalledFeatures.txt

List all activated site scoped features
Especially in the case of hidden features it’s sometimes necessary to track down if a feature is active on a site collection. Here’s a quick way of seeing which features are activated for an SPSite:

1 Get-SPFeature -Site http://sitecollectionurl | Sort DisplayName | FT DisplayName,Id

List all activated web scoped features
And only slightly modified from the Get-Help Get-SPFeature -examples text, here is a command to list all web activated featres for a site collection:

1 Get-SPSite http://sitecollectionurl | Get-SPWeb -Limit ALL | %{ Get-SPFeature -Web $_ } | Sort DisplayName -Unique | FT DisplayName,Id

Azure and IIS provisioning with PowerShell

Infrastructure scripts for deploying web applications. For virtual machines, see provisioning Azure VMs with PowerShell.

Create an Azure Web App with PowerShell

In this article, I will show you how to quickly create an Azure Web App using Powershell as an alternative of using the portal or Azure CLI.

The creation of an azure web app has three steps.

Step 1: Create a resource group

As your application will be running within a resource group, it is logical to create Azure Web Apps a new one (if you don’t want to hook the app to an existing resource group).

Step 2: Create an app service plan

Depending on whether you will be deploying a small or large application, for dev or production purposes, you have to select the appropriate service plan.

If you want to know the different options you have, please visit https://azure.microsoft.com/en-gb/pricing/details/app-service/windows/

You can either pick the free & shared service plan, standard Azure Web Apps or premium, the previous link explains in detail the differences in performances and cost between these plans.

Step 3: Create your app

At this stage, we have everything we need, we just create the app and attach it to the resource group and assign it a service plan.

# Create variables
$webappname = "mywebapp$(Get-Random)"
$rgname = 'webapps3-dev-rg'
$location = 'westus2'

# Create a resource group
New-AzResourceGroup -Name $rgname -Location $location

# Create an App Service plan in S1 tier
New-AzAppServicePlan -Name $webappname -Location $location -ResourceGroupName $rgname -Tier S1

# Create a web app
New-AzWebApp -Name $webappname -Location $location -AppServicePlan $webappname -ResourceGroupName $rgname

 

Provision an IIS server and web application

In this article, I will share with you my PowerShell script which I have been using to deploy an ASP.Net application I built (as SaaS) initially, which got a lot of requests to be deployed locally.

The application in question is ClicMedic (a medical software management) –> more details at www.clicmedic.com

This is my PowerShell script in two main steps :

1- Provision IIS

Set-ExecutionPolicy Bypass -Scope Process
Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole
Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServer
Enable-WindowsOptionalFeature -Online -FeatureName IIS-CommonHttpFeatures
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpErrors
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpRedirect
Enable-WindowsOptionalFeature -Online -FeatureName IIS-ApplicationDevelopment
Enable-WindowsOptionalFeature -online -FeatureName NetFx4Extended-ASPNET45
Enable-WindowsOptionalFeature -Online -FeatureName IIS-NetFxExtensibility45
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HealthAndDiagnostics
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpLogging
Enable-WindowsOptionalFeature -Online -FeatureName IIS-LoggingLibraries
Enable-WindowsOptionalFeature -Online -FeatureName IIS-RequestMonitor
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpTracing
Enable-WindowsOptionalFeature -Online -FeatureName IIS-Security
Enable-WindowsOptionalFeature -Online -FeatureName IIS-RequestFiltering
Enable-WindowsOptionalFeature -Online -FeatureName IIS-Performance
Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerManagementTools
Enable-WindowsOptionalFeature -Online -FeatureName IIS-IIS6ManagementCompatibility
Enable-WindowsOptionalFeature -Online -FeatureName IIS-Metabase
Enable-WindowsOptionalFeature -Online -FeatureName IIS-ManagementConsole
Enable-WindowsOptionalFeature -Online -FeatureName IIS-BasicAuthentication
Enable-WindowsOptionalFeature -Online -FeatureName IIS-WindowsAuthentication
Enable-WindowsOptionalFeature -Online -FeatureName IIS-StaticContent
Enable-WindowsOptionalFeature -Online -FeatureName IIS-DefaultDocument
Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebSockets
Enable-WindowsOptionalFeature -Online -FeatureName IIS-ApplicationInit
Enable-WindowsOptionalFeature -Online -FeatureName IIS-ISAPIExtensions
Enable-WindowsOptionalFeature -Online -FeatureName IIS-ISAPIFilter
Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpCompressionStatic
Enable-WindowsOptionalFeature -Online -FeatureName IIS-ASPNET45

 

2- Create the web site

Here I am just creating a new web site on my newly provisioned IIS server,

My website will be available on port 1002

md "c:\inetpub\wwwroot\YOURSITE"
$site = $site = new-WebSite -name "YOURSITENAME" -Port 1002 -PhysicalPath "c:\inetpub\wwwroot\YOURSITE"  -force

 

PowerShell for Microsoft 365: FAQ

Which PowerShell modules do I need for Microsoft 365?

The most common are Microsoft Graph PowerShell (users, groups and licences), MicrosoftTeams, Microsoft.Online.SharePoint.PowerShell or PnP.PowerShell (SharePoint Online), ExchangeOnlineManagement and Az (Azure).

Can I run these scripts from Power Automate?

Yes. You can run PowerShell from an Azure Automation runbook and call it from a Power Automate flow. This is handy for scheduled audits. See the Power Automate tutorial for the basics.

More scripts are in the PowerShell category.

Discover more from SamTech 365

Subscribe now to keep reading and get access to the full archive.

Continue reading