2026-05-05 · Season 2
PowerShell Automation for Azure and Microsoft 365 with Matthew Dowst [MVP]
![PowerShell Automation for Azure and Microsoft 365 with Matthew Dowst [MVP]](https://d3wo5wojvuv7l.cloudfront.net/t_rss_itunes_square_1400/images.spreaker.com/original/3d2181a51a724450b43c98a50760ce1a.jpg)
You use PowerShell to automate all things across Azure and Microsoft 365. This tool gives you flexibility and control, whether you are an administrator or a developer. Matthew Dowst [MVP] notes that PowerShell’s design supports both simple and complex automation. Its object-oriented nature helps you manage tasks with transparency and security.
| Factor | Description |
|---|---|
| Central Organization | You centrally organize and manage PowerShell scripts, including change history. |
| Execution Monitoring | PowerShell tracks which scripts you execute, with what settings and rights, for better control. |
| User Permissions | You define who can run scripts, which ensures accountability and security. |
| Reporting and Evaluation | Central reporting gives you insight into script quality and usage for ongoing improvement. |
PowerShell helps you reduce errors, optimize resources, and scale operations. With automation, you save time and improve consistency in your IT environment.
Key Takeaways
- PowerShell automates tasks in Azure and Microsoft 365, providing flexibility and control for administrators and developers.
- Set up the right accounts and permissions before automating tasks to ensure smooth and secure script execution.
- Use the least privilege principle when assigning permissions to enhance security and accountability in your automation.
- Regularly update PowerShell modules to access the latest features and maintain security in your automation scripts.
- Test your scripts in a safe environment before deploying them to prevent unintended changes and errors.
- Implement error handling in your scripts to manage issues effectively and ensure reliable automation.
- Use runbooks to automate complex workflows, allowing for parallel execution and improved efficiency in task management.
- Monitor and log your automation processes to identify inefficiencies and enhance the overall performance of your scripts.
Prerequisites for PowerShell Automation
Before you start automating tasks in azure and Microsoft 365, you need to set up the right accounts, permissions, and tools. This foundation ensures your scripts run smoothly and securely.
Accounts and Permissions
Azure account setup
You need an azure account with the right permissions to manage resources. Most automation tasks require access at the subscription or resource group level. The table below shows common actions and the minimum permissions you need:
| Action | Permission | Minimum Scope |
|---|---|---|
| Write new deployment | Microsoft.Resources/deployments/* | Subscription |
| Write new resource group | Microsoft.Resources/subscriptions/resourceGroups/write | Subscription |
| Create new default Workspace | Microsoft.OperationalInsights/workspaces/write | Resource group |
| Create new Account | Microsoft.Automation/automationAccounts/write | Resource group |
| Link workspace and account | Microsoft.OperationalInsights/workspaces/write, Microsoft.Automation/automationAccounts/read | WorkspaceAutomation account |
| Create MMA extension | Microsoft.Compute/virtualMachines/write | Virtual Machine |
| Create saved search | Microsoft.OperationalInsights/workspaces/write | Workspace |
| Create scope config | Microsoft.OperationalInsights/workspaces/write | Workspace |
| Onboarding state check - Read workspace | Microsoft.OperationalInsights/workspaces/read | Workspace |
| Onboarding state check - Read linked workspace property of account | Microsoft.Automation/automationAccounts/read | Automation account |
| Onboarding state check - Read solution | Microsoft.OperationalInsights/workspaces/intelligencepacks/read | Solution |
| Onboarding state check - Read VM | Microsoft.Compute/virtualMachines/read | Virtual Machine |
| Onboarding state check - Read account | Microsoft.Automation/automationAccounts/read | Automation account |
| Onboarding workspace check for VM1 | Microsoft.OperationalInsights/workspaces/read | Subscription |
| Register the Log Analytics provider | Microsoft.Insights/register/action | Subscription |
You should always use the least privilege principle. Assign only the permissions needed for each task.
Microsoft 365 account setup
For Microsoft 365 automation, you need an account with admin rights. Global Administrator or specific roles like Exchange Administrator or SharePoint Administrator work best. Make sure your account has multi-factor authentication enabled for extra security.
PowerShell Modules
Azure PowerShell install
You must install the azure PowerShell module to manage azure resources. Use the following command to install it:
Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force
Keep your modules updated. The system checks for updates regularly to ensure you have the latest features and security patches. Here are some default update settings:
| Setting | Default Value | Description |
|---|---|---|
| MDMaxBackgroundUpgradePeriod | 7.00:00:00 | Controls the background update period for PowerShell function apps. |
| MDNewSnapshotCheckPeriod | 01:00:00 | Specifies how often the PowerShell worker checks for updates. |
| MDMinBackgroundUpgradePeriod | 1.00:00:00 | Minimum time between upgrade checks. |
Microsoft Graph SDK
Install the Microsoft Graph PowerShell SDK to automate Microsoft 365 services. This module lets you manage users, groups, and licenses across your environment. Use the following command:
Install-Module Microsoft.Graph -Scope CurrentUser
Security Setup
Role assignments
Assign roles carefully in azure and Microsoft 365. Use built-in roles like Contributor or Reader for azure resources. For Microsoft 365, assign only the roles needed for automation tasks. This approach limits risk and keeps your environment secure.
MFA configuration
Enable multi-factor authentication (MFA) for all accounts used in automation. MFA adds a strong layer of protection against unauthorized access.
Tip: Enforce strict execution policies in powershell, such as 'AllSigned', to control which scripts can run. Sign your scripts to ensure their integrity. Always use secure coding techniques, like input validation and avoiding hard-coded credentials.
By following these prerequisites, you set a strong foundation for automating azure and Microsoft 365 with powershell. You protect your environment and ensure your automation runs reliably.
Create and Configure Azure Automation

Setting up automation in azure starts with a solid foundation. You need to create and configure azure automation accounts before you can automate tasks across your environment. This process ensures you have the right structure and permissions for reliable workflows.
Azure Automation Account
Account creation steps
You begin by signing in to the azure portal with an account that has the right permissions. Follow these steps to create and configure azure automation:
- Sign in to the azure portal as a member of the subscription Administrators role and Co-Administrator.
- Select + Create a Resource from the portal menu.
- Search for Automation and select it from the results.
- On the Basics tab, enter the required information for your automation account.
- Adjust settings as needed or select Review + create to use the default options.
You must have permissions equal to the Owner role for Microsoft.Automation resources. This access lets you manage and configure all aspects of the azure automation account.
Permission setup
Assign permissions carefully when you create and configure azure automation. Use built-in roles like Owner or Contributor for users who need to manage automation accounts. Limit access to only those who require it. This approach protects your azure environment and keeps automation secure.
Tip: Always review role assignments after you create and configure azure automation service. Remove unnecessary permissions to follow the principle of least privilege.
Module Management
Modules are the building blocks of automation in azure. They let you reuse code, streamline workflows, and adapt scripts to different conditions. Good module management improves the reliability and scalability of your automation.
Importing modules
You can import modules into your azure automation account to extend its capabilities. Use the azure portal or powershell to add modules that support your automation needs. Modules help you avoid repeating code and reduce errors in your workflows.
Common challenges can occur during module import. Sometimes, a module may get stuck in the Importing state or fail to load if it has missing dependencies. If you update too many modules at once, the process may suspend or cause errors. Always check module structure and dependencies before importing.
Updating modules
Keep your modules up to date to maintain security and performance. Regular updates ensure your automation scripts use the latest features. Use the azure portal or powershell to update modules in your azure automation account. If a module fails to update, check for resource group naming issues or structural problems.
Note: Test your automation after each module update. This step helps you catch issues early and keeps your workflows running smoothly.
When you create and configure azure automation service, you set the stage for advanced tasks like create new runbook, resource provisioning, and large-scale management. Careful planning and regular maintenance help you get the most from azure automation.
Automate All Things with PowerShell Scripts
You can automate all things in Azure and Microsoft 365 by building, testing, and publishing PowerShell scripts. This approach lets you manage resources, users, and services efficiently. Matthew Dowst [MVP] often highlights how you can start with simple scripts and expand them into powerful automation solutions. You gain control, consistency, and speed when you automate all things with PowerShell workflow runbook processes.
Script Creation
Azure VM management
You can automate all things related to Azure virtual machines using PowerShell runbooks. For example, you might want to create, manage, or update VMs without manual steps. PowerShell runbooks let you automate tasks like provisioning new VMs, scheduling shutdowns, and applying patches in bulk.
| Use Case | Description |
|---|---|
| VM Provisioning | Automate the creation of virtual machines using cmdlets like New-AzVM. |
| Scheduled Shutdowns | Deallocate VMs on a schedule to save costs during non-business hours. |
| Bulk Patching | Automate the process of stopping VMs, applying updates, and restarting them. |
You can create a runbook that checks for VMs tagged as "Development" and shuts them down after business hours. This method saves money and ensures resources are only active when needed.
Microsoft 365 user automation
PowerShell runbooks help you automate all things in Microsoft 365, especially user management. You can create a runbook to onboard new users, assign licenses, and set up mailboxes in one step. This process standardizes onboarding and reduces errors.
| Use Case Area | Description |
|---|---|
| User Onboarding | Secure, delegated user creation with role-based access. |
| Directory Reporting | Automate scheduled AD reports with easy-to-read HTML output. |
| Communication Management | Centralized management of out-of-office settings for multiple users. |
You can also automate Active Directory user creation and mailbox provisioning. PowerShell runbooks make these tasks repeatable and reliable.
Resource provisioning
You can automate all things related to resource provisioning in Azure and Microsoft 365. PowerShell runbooks let you deploy and configure resources like storage accounts, networks, and security groups. You can create a runbook that provisions resources based on templates or tags, ensuring consistency across your environment.
Some best practices for script creation include:
- Start small and expand gradually by automating simple tasks before moving to complex workflows.
- Use tags for resource management to make scripts dynamic, such as shutting down VMs tagged as "Development".
- Implement proper security controls by securing credentials with Azure Key Vault and avoiding hardcoding sensitive information.
- Test scripts in a non-production environment to prevent unintended changes.
- Continuously monitor automated processes to identify and address inefficiencies.
Testing and Debugging
PowerShell ISE/VS Code
You should always test your scripts before using them in production. PowerShell Integrated Scripting Environment (ISE) and Visual Studio Code help you write, test, and debug scripts. You can use the Run Selection option in ISE to execute parts of your script for debugging. Set breakpoints to pause execution and inspect variables. The Set-PSDebug cmdlet lets you step through your code line by line.
- PowerShell ISE provides a user-friendly interface for running commands and debugging scripts.
- Set-PSDebug helps you trace script execution.
- Breakpoints let you halt execution and check variable values.
Error handling
Effective error handling is essential when you automate all things with PowerShell runbooks. You can use try-catch-finally blocks to manage errors and perform cleanup actions. Log errors for later analysis and use the $Error variable for detailed information. Configure $ErrorActionPreference to control how your script responds to errors.
- Proactively validate input parameters and environment prerequisites to prevent runtime errors.
- Use advanced parameter attributes like [ValidateSet()], [ValidatePattern()], or [ValidateScript()] to enforce strict validation rules.
- Fine-tune error response behaviors with -ErrorAction and -ErrorVariable for granular control.
- Implement tailored retry mechanisms with exponential backoff to minimize failures.
- Centralize monitoring to gain insights into your automation environment.
Runbooks and Scheduling
Azure Automation runbooks
PowerShell workflow runbook solutions let you automate all things in Azure and Microsoft 365. You can create a runbook to execute commands in parallel, which improves efficiency. The Parallel keyword allows multiple commands to run at the same time, reducing execution time for repetitive tasks.
To create powershell runbooks, follow these steps:
- Open your Azure Automation account.
- Select "Runbooks" and choose "Create a runbook".
- Enter a name, select "PowerShell" as the type, and write your script.
- Save and publish the runbook.
You can create powershell runbooks for tasks like VM provisioning, user onboarding, or resource cleanup. PowerShell runbooks support both simple and complex workflows, making it easy to automate all things across your environment.
Scheduled tasks
Scheduling powershell runbooks increases operational efficiency. You can automate routine operations like starting or stopping VMs, backing up data, or running maintenance scripts. Scheduled tasks help you deploy and configure multiple resources consistently. They also enforce compliance and security standards automatically.
- Automate routine operations with scheduled powershell runbooks.
- Deploy and configure resources across your environment.
- Enforce compliance and security standards.
- Keep systems up-to-date with minimal manual intervention.
- Trigger automated actions based on specific events or alerts.
- Extend automation to on-premises systems and other cloud platforms.
PowerShell workflow runbook automation lets you create sophisticated scenarios that span multiple systems and services. You can automate all things, from simple user onboarding to complex resource management, using powershell runbooks as the backbone of your strategy.
Tip: Matthew Dowst [MVP] recommends starting with small scripts and building up to more complex powershell runbooks. This approach helps you learn, reduces risk, and ensures your automation grows with your needs.
Authentication and Secure Access

You must secure your automation scripts to protect your Azure and Microsoft 365 environments. Authentication and input validation are essential for reliable and safe operations. This section explains how you can use service principals, manage credentials, and validate parameters for effective automation.
Script Authentication
Azure service principals
Azure service principals allow you to automate tasks without using your personal account. You create a service principal and assign only the permissions needed for your script. This method follows the principle of least privilege. You should use managed identities when possible. If you use service principals, store client secrets in Azure Key Vault, rotate them often, and prefer certificates or federated credentials over client secrets.
To ensure secure usage of Azure service principals in PowerShell automation, leverage managed identities whenever possible. If service principals must be used, store client secrets in Azure Key Vault, rotate them frequently, and prefer federated credentials or certificates over client secrets. Implement least privilege access by granting only necessary permissions at the offering, resource group, or subscription level.
Secure credential storage
You must avoid hardcoded passwords in your scripts. Secure storage solutions help you protect sensitive information. The table below shows common methods for storing credentials:
| Method | Advantages | Considerations |
|---|---|---|
| Azure Key Vault | Fine-grained access control, centralized logging, HSM backing | Requires Azure authentication, higher complexity |
| PowerShell Vault Module | Encrypted secrets, cross-platform compatibility | Needs proper setup for different environments |
| Environment Variables | Temporary storage, easy CI/CD integration | Secrets lost after session, risk of exposure |
You can use Azure Key Vault for centralized management and logging. The PowerShell vault module encrypts secrets and keeps them out of your code. Environment variables provide temporary storage but may expose secrets if not handled carefully.
Tip: Use secure strings to encrypt passwords and Windows Credential Manager for local automation. Always choose a solution that fits your environment and security needs.
Input Parameters
Parameter validation
You must validate input parameters to ensure your scripts run safely. Proper validation prevents errors and protects your environment from invalid or malicious input. Define your inputs before writing logic. This practice makes your scripts reusable and reliable.
- Use [ValidateSet()] to restrict values to a specific list.
- Apply [ValidatePattern()] to enforce formats like email addresses.
- Implement [ValidateScript()] for custom validation rules.
Parameter-driven design helps you create tools that work for many scenarios, not just one-time tasks.
Dynamic execution
Dynamic execution lets your scripts adapt to different environments. You can detect if your script runs interactively or in Azure Automation. Set the correct execution context based on this detection. Manage permissions with flags to ensure your script has what it needs to run.
- Detect environment and adjust execution context.
- Manage permissions based on where the script runs.
- Handle input and output differently in headless environments like Azure Automation.
You improve reliability and security by validating parameters and adapting execution. These practices help you build robust automation solutions with PowerShell.
Scaling Azure Automation
As your environment grows, you need to scale your automation to manage many azure resources across different teams, departments, or even tenants. PowerShell gives you the tools to handle large-scale tasks in both azure and Microsoft 365. You can automate processes for hundreds or thousands of resources, making your cloud operations more efficient and reliable.
Bulk Operations
Azure resource management
When you manage many azure resources, bulk operations become essential. PowerShell lets you update, configure, or monitor multiple resources at once. You can use the latest module versions to get better performance and new features. Service principal or app-only authentication helps you avoid interactive logins, which is important for automation in the cloud.
To speed up your tasks, use parallel processing. This method lets you perform actions on several azure resources at the same time. You can also use the -ResultSize parameter to limit data and improve efficiency. Service-side filtering helps you target only the resources you need.
Tip: Schedule large jobs during off-peak hours to avoid hitting rate limits or throttling in azure. Always validate your input and log every action for better reliability.
Microsoft 365 user/group automation
You can automate user and group management in Microsoft 365 using PowerShell. Bulk operations let you create, update, or remove users and groups quickly. Align your scripts with governance standards to keep your cloud environment secure and organized. Use the AzureAD module for PowerShell 5 or the Azure Az module for PowerShell 7, depending on your setup. Understand the differences between these modules to choose the right one for your needs.
Treat your automation scripts like production code. Test them before running in your main environment. Schedule large jobs to manage rate limits and ensure smooth operations.
Resource Tagging
Tagging strategies
Resource tagging is a powerful way to organize and manage azure resources. Tags help you identify ownership, application, environment, cost center, and data classification. Consistent tagging makes it easy to filter and report on resources across your cloud environment. Inconsistent tagging can lead to confusion and wasted time.
You should create clear naming conventions for tags. Use tags to group azure resources by project, department, or environment. This practice supports automated reporting and management tasks.
| Tag Key | Example Value | Purpose |
|---|---|---|
| Owner | ITDept | Identify resource owner |
| Environment | Production | Track resource usage |
| CostCenter | 12345 | Manage cloud spending |
Note: Leverage dashboards and favorites in azure for quick navigation. Document which subscriptions belong to which customer for better tracking.
License assignment
Automating license assignment in Microsoft 365 saves time and reduces errors. You can use PowerShell scripts to assign or remove licenses for many users at once. This approach ensures everyone has the right access and helps you manage costs in the cloud. Combine license management with tagging to track which users or groups have specific licenses.
Scaling your automation with PowerShell lets you manage complex cloud environments with confidence. You gain control over azure resources, improve efficiency, and support your organization’s growth.
Troubleshooting and Best Practices
When you automate Azure and Microsoft 365, you will face challenges. You can solve most issues by following best practices for runbooks, workflow, and security. This section helps you troubleshoot common problems and improve your automation.
Common Issues
Module compatibility
You may find that some PowerShell modules do not work as expected in Azure Automation. Module compatibility problems can stop your runbooks or workflow from running. Always check that your modules match the version in your automation account. Update modules often to keep your workflow smooth. If you see errors, review the module structure and dependencies.
Permission errors
Permission errors can block your runbooks from accessing resources. Assign only the permissions your workflow needs. Use the least privilege principle for security. If your runbooks fail, check role assignments and make sure your account or service principal has access to all required resources.
Here is a table of common issues and solutions:
| Issue | Solution |
|---|---|
| Unable to create a new Automation job in the West Europe region. | This happens because of scalability limits. Follow Microsoft’s troubleshooting steps for this region. |
| Runbook bugs or Azure Automation issues. | Review Microsoft’s troubleshooting guide for runbooks. |
| Runbook output and message issues. | Learn how to retrieve runbook output and messages for better workflow tracking. |
| PowerShell module issues in Azure Automation. | Update modules and check for compatibility problems. |
Security and Efficiency
Logging and monitoring
You should enable all PowerShell logging. This includes module logging, script block logging, and transcription. Set your log size to at least 150 MB. Collect events from Microsoft-Windows-PowerShell/Operational and PowerShellCore/Operational. Send logs to your SIEM or XDR for better monitoring. Block scripts from untrusted sources and restrict execution policy to signed scripts. These steps protect your resources and improve security.
Script optimization
You can optimize your runbooks and workflow by following these steps:
- Use Try, Catch, and Finally for error handling.
- Validate parameters to prevent errors.
- Use cmdlets instead of .NET methods for better performance.
- Avoid unnecessary loops and select only the properties you need.
- Review your scripts often to keep them efficient.
Just Enough Administration (JEA) limits user access to approved cmdlets. Enforce constrained language mode to disable risky features. Keep PowerShell updated and review logging settings for security.
Expert Insights
Real-world examples
Matthew Dowst [MVP] shows how PowerShell automation changes the way you manage resources. He uses runbooks and workflow to help teams automate tasks quickly. His work in Azure Managed Services proves that you can move from reactive to proactive operations with the right automation.
Recommendations
Dowst recommends that you start small. Build simple runbooks and expand your workflow as you learn. Focus on freeing your team from repetitive tasks. Use automation to let your team work on more important projects. Always test your runbooks before using them in production. Document your workflow and keep your scripts organized.
Tip: Track your automation jobs and costs. Use tags to group resources and monitor usage. This helps you manage your cloud spending and keeps your workflow efficient.
By following these best practices, you can troubleshoot issues, improve security, and get the most from your PowerShell automation. You will build reliable runbooks and workflow that scale with your resources.
PowerShell gives you the tools to automate Azure and Microsoft 365 with speed and reliability. You improve operational efficiency by automating resource provisioning and audits. You adapt your scripts to meet enterprise needs and minimize downtime. Start with small scripts, then expand to complex automation using Microsoft Graph and Azure Automation.
- Pursue PowerShell certifications to boost your skills.
- Apply automation in real-world scenarios for better efficiency.
- Commit to continuous learning and join community forums.
Follow experts like Matthew Dowst [MVP] for advanced tips.
FAQ
How do you start an Azure virtual machine using a runbook?
You can start an azure virtual machine by creating a runbook in your automation account. Add code to the runbook that uses the Start-AzVM cmdlet. Test and publish the runbook to automate the process. Use managed identity for secure authentication.
What is a runbook job and how does it help with process automation?
A runbook job is an instance of a runbook that runs in Azure Automation. You use runbook jobs to automate tasks like configuration, management, and monitoring. This approach improves process automation and reduces manual work.
Why should you use managed identity in your runbook?
Managed identity provides secure authentication for your runbook. You avoid storing credentials in your code. Managed identity lets your runbook access Azure resources safely. This method supports better configuration and management.
How do you add code to the runbook for Microsoft 365 management?
You add code to the runbook by opening the editor in your automation account. Write PowerShell scripts that handle user management, license assignment, or reporting. Use runbook parameters to make your scripts flexible. Test and publish the runbook for reliable process automation.
What are the best practices for configuration and management in runbooks?
You should use clear naming for runbooks and parameters. Document each runbook job. Use managed identity for authentication. Schedule regular reviews of your configuration. Monitor runbook jobs for errors. This approach supports strong management and process automation.
How do you test and publish the runbook?
You test and publish the runbook by using the Azure Automation editor. Run the script in test mode to check for errors. After testing, publish the runbook to make it available for scheduling or manual execution. This step ensures your configuration is correct.
What is the role of runbook parameters in process automation?
Runbook parameters let you pass values to your runbook at runtime. You use them to make your automation flexible. Parameters support different scenarios in configuration and management. This feature helps you reuse runbooks for many tasks.
How do you stop a virtual machine with a runbook?
You create a runbook in Azure Automation. Add code to the runbook that uses the Stop-AzVM cmdlet. Assign a managed identity for secure access. Test and publish the runbook. Schedule the runbook job to stop a virtual machine automatically.
Tip: Use tables to track runbook jobs and monitor configuration changes for better management.
| Task | Runbook Name | Status |
|---|---|---|
| Start VM | StartVMRunbook | Success |
| Stop VM | StopVMRunbook | Success |
| User Management | UserMgmtRunbook | Running |
🎧 Listen to this episode
Want a practical explanation of PowerShell Automation for Azure and Microsoft 365? This episode breaks down the topic in clear language and shows why it matters for Microsoft 365, Azure, Power Platform, security, AI, and modern work.
Listen to this episode if you want to:
- Understand the key concepts behind PowerShell Automation for Azure and Microsoft 365
- See how it fits into the wider Microsoft technology ecosystem
- Learn where it can create practical value for your organization
You may also enjoy these related M365 FM episodes:
- PowerShell vs Bicep for Azure Infrastructure Automation
- Microsoft Graph and PowerShell for Enterprise Automation
- Modern Microsoft 365 Automation Beyond PowerShell Scripts
- PowerShell Automation with Harm Veenstra [MVP]
- PowerShell vs Microsoft Graph API for Automation
Discover more practical Microsoft conversations on M365 FM.
Official Microsoft MVP profile: Matthew Dowst on Microsoft MVP
Apple Podcasts · Spotify · YouTube · YouTube Music
Host: Mirko Peters