This manual documents a comprehensive collection of PowerShell scripts for managing all aspects of Azure Cloud, Microsoft 365, Entra ID, Intune, and Microsoft Defender. These scripts are designed for Azure administrators, Intune administrators, and security analysts to automate common tasks and generate detailed reports.
Author: Michael Witzsche Date: April 26, 2025 Version: 1.0.1
- PowerShell 5.1 or PowerShell 7.x
- Required PowerShell modules:
- Microsoft.Graph.Authentication
- Microsoft.Graph.Identity.DirectoryManagement
- Microsoft.Graph.Users
- Microsoft.Graph.Groups
- Microsoft.Graph.DeviceManagement
- Microsoft.Graph.DeviceManagement.Administration
- Microsoft.Graph.DeviceManagement.Enrollment
- Microsoft.Graph.Security
- Microsoft.Graph.Compliance
- Microsoft.Graph.Teams
- Microsoft.Graph.Reports
- Microsoft.Graph.Sites
- ExchangeOnlineManagement
- Az
- ImportExcel
- MicrosoftTeams
- Install required PowerShell modules:
# Install Microsoft Graph modules
Install-Module Microsoft.Graph -Force
# Install Azure modules
Install-Module Az -Force
# Install Exchange Online module
Install-Module ExchangeOnlineManagement -Force
# Install Microsoft Teams module
Install-Module MicrosoftTeams -Force
# Install ImportExcel module for report export
Install-Module ImportExcel -Force- Download the scripts to your local machine
- Ensure execution policy allows running the scripts:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUserMost scripts use Microsoft Graph API and require authentication. Scripts are designed to use interactive authentication with a human account running from a desktop to Azure remotely. When running scripts, you'll be prompted to sign in with your Azure AD credentials. Some scripts require connection to specific services like Exchange Online or Microsoft Teams, and will handle those connections internally.
Scripts for managing Azure resources and services.
Description: Creates a new virtual machine in Azure with specified configuration.
Parameters:
ResourceGroupName- Name of the resource group where the VM will be createdVMName- Name of the virtual machineLocation- Azure region for the VMVMSize- Size of the VM (e.g., Standard_D2s_v3)ImageName- OS image to use (e.g., Win2019Datacenter, UbuntuLTS)AdminUsername- Administrator usernameAdminPassword- Administrator passwordVNetName- Virtual network nameSubnetName- Subnet namePublicIPName- Public IP address nameNSGName- Network security group nameTags- Hashtable of tags to apply to the VMLogPath- Path where logs will be stored
Example:
.\New-AzureVM.ps1 -ResourceGroupName "MyResourceGroup" -VMName "MyVM" -Location "eastus" -VMSize "Standard_D2s_v3" -ImageName "Win2019Datacenter" -AdminUsername "azureadmin" -AdminPassword (ConvertTo-SecureString "P@ssw0rd123" -AsPlainText -Force) -VNetName "MyVNet" -SubnetName "default" -PublicIPName "MyPublicIP" -NSGName "MyNSG" -Tags @{Environment="Test"; Department="IT"}Description: Creates a new virtual network in Azure with subnets and network security groups.
Parameters:
ResourceGroupName- Name of the resource groupVNetName- Name of the virtual networkLocation- Azure region for the VNetAddressPrefix- Address space for the VNet (e.g., "10.0.0.0/16")Subnets- Array of subnet configurationsCreateNSG- Whether to create network security groups for each subnetTags- Hashtable of tags to applyLogPath- Path where logs will be stored
Example:
$subnets = @(
@{Name="Frontend"; AddressPrefix="10.0.0.0/24"; ServiceEndpoints=@("Microsoft.Storage")},
@{Name="Backend"; AddressPrefix="10.0.1.0/24"; ServiceEndpoints=@("Microsoft.Sql")}
)
.\New-AzureVirtualNetwork.ps1 -ResourceGroupName "MyResourceGroup" -VNetName "MyVNet" -Location "eastus" -AddressPrefix "10.0.0.0/16" -Subnets $subnets -CreateNSG $true -Tags @{Environment="Production"; Department="IT"}Description: Creates a new Azure SQL Database with specified configuration.
Parameters:
ResourceGroupName- Name of the resource groupServerName- Name of the SQL ServerDatabaseName- Name of the databaseLocation- Azure region for the databaseEdition- SQL Database edition (e.g., Basic, Standard, Premium)ServiceObjective- Performance level (e.g., S0, S1, P1)AdminUsername- SQL Server admin usernameAdminPassword- SQL Server admin passwordAllowAzureIPs- Whether to allow Azure services to access the serverFirewallRules- Array of firewall rules to createTags- Hashtable of tags to applyLogPath- Path where logs will be stored
Example:
$firewallRules = @(
@{Name="Office"; StartIpAddress="203.0.113.0"; EndIpAddress="203.0.113.255"},
@{Name="HomeNetwork"; StartIpAddress="198.51.100.0"; EndIpAddress="198.51.100.255"}
)
.\New-AzureSQLDatabase.ps1 -ResourceGroupName "MyResourceGroup" -ServerName "mysqlserver" -DatabaseName "MyDatabase" -Location "eastus" -Edition "Standard" -ServiceObjective "S1" -AdminUsername "sqladmin" -AdminPassword (ConvertTo-SecureString "P@ssw0rd123" -AsPlainText -Force) -AllowAzureIPs $true -FirewallRules $firewallRules -Tags @{Environment="Production"; Department="IT"}Scripts for managing Entra ID (formerly Azure AD) users, groups, and roles.
Description: Creates a new user in Entra ID with specified attributes and group memberships.
Parameters:
DisplayName- Display name for the userUserPrincipalName- User principal name (email format)MailNickname- Mail nickname for the userPassword- Initial passwordForceChangePasswordNextSignIn- Whether to force password change at next sign-inAccountEnabled- Whether the account should be enabledDepartment- User's departmentJobTitle- User's job titleCompanyName- User's company nameUsageLocation- Two-letter country code for license assignmentGroupIds- Array of group IDs to add the user toLicenseSkuIds- Array of license SKU IDs to assignLogPath- Path where logs will be stored
Example:
.\New-AzureADUser.ps1 -DisplayName "John Doe" -UserPrincipalName "john.doe@contoso.com" -MailNickname "johndoe" -Password (ConvertTo-SecureString "P@ssw0rd123" -AsPlainText -Force) -ForceChangePasswordNextSignIn $true -AccountEnabled $true -Department "IT" -JobTitle "System Administrator" -CompanyName "Contoso" -UsageLocation "US" -GroupIds @("12345678-1234-1234-1234-123456789012", "87654321-4321-4321-4321-210987654321") -LicenseSkuIds @("f8a1db68-be16-40ed-86d5-cb42ce701560")Description: Creates a new security or Microsoft 365 group in Entra ID.
Parameters:
DisplayName- Display name for the groupMailNickname- Mail nickname for the groupDescription- Description of the groupGroupType- Type of group (Security, Microsoft365)MailEnabled- Whether the group is mail-enabledSecurityEnabled- Whether the group is security-enabledVisibility- Visibility of the group (Private, Public, HiddenMembership)Owners- Array of user IDs to set as group ownersMembers- Array of user IDs to add as group membersIsAssignableToRole- Whether the group can be assigned to an admin roleLogPath- Path where logs will be stored
Example:
.\New-AzureADGroup.ps1 -DisplayName "IT Department" -MailNickname "itdepartment" -Description "IT Department Security Group" -GroupType "Security" -MailEnabled $false -SecurityEnabled $true -Visibility "Private" -Owners @("12345678-1234-1234-1234-123456789012") -Members @("12345678-1234-1234-1234-123456789012", "87654321-4321-4321-4321-210987654321") -IsAssignableToRole $falseDescription: Assigns an Entra ID directory role to a user or group.
Parameters:
RoleDefinitionName- Name of the role to assign (e.g., Global Administrator, User Administrator)PrincipalId- ID of the user or group to assign the role toPrincipalType- Type of principal (User, Group)LogPath- Path where logs will be stored
Example:
.\Add-AzureADRoleAssignment.ps1 -RoleDefinitionName "User Administrator" -PrincipalId "12345678-1234-1234-1234-123456789012" -PrincipalType "User"Description: Generates comprehensive reports about users in Microsoft 365 and Azure environments, including account information, license status, group memberships, role assignments, authentication methods, and activity logs.
Parameters:
ReportType- Type of user report to generate (Basic, Detailed, Licenses, Groups, Roles, Auth, Activity, All)Filter- Hashtable of filters to apply to the reportTimeFrame- Time frame for activity data (Last7Days, Last30Days, Last90Days, LastYear)IncludeGuests- Whether to include guest users in the reportIncludeServiceAccounts- Whether to include service accounts in the reportExportPath- Path where the report will be savedExportFormat- Format of the export file (CSV, JSON, Excel, HTML)LogPath- Path where logs will be stored
Example:
.\Get-UserReport.ps1 -ReportType Licenses -Filter @{Department="IT"} -TimeFrame Last30Days -IncludeGuests $false -IncludeServiceAccounts $false -ExportPath "C:\Reports\UserLicenses.xlsx" -ExportFormat ExcelScripts for managing Microsoft Intune devices, applications, and policies.
Description: Creates a new device configuration profile in Microsoft Intune.
Parameters:
ProfileName- Name of the configuration profileDescription- Description of the profilePlatform- Target platform (Windows10, iOS, Android, macOS)ProfileType- Type of configuration profileSettings- Hashtable of settings for the profileAssignments- Array of group IDs to assign the profile toAssignmentType- Type of assignment (Include, Exclude)LogPath- Path where logs will be stored
Example:
$settings = @{
passwordRequired = $true
passwordMinimumLength = 8
passwordRequiredType = "alphanumeric"
passwordMinutesOfInactivityBeforeLock = 15
}
.\New-IntuneConfigurationProfile.ps1 -ProfileName "Windows 10 Security Baseline" -Description "Security baseline for Windows 10 devices" -Platform "Windows10" -ProfileType "deviceConfiguration" -Settings $settings -Assignments @("12345678-1234-1234-1234-123456789012") -AssignmentType "Include"Description: Creates and deploys a new application in Microsoft Intune.
Parameters:
AppName- Name of the applicationDescription- Description of the applicationPublisher- Publisher of the applicationAppType- Type of application (Win32, iOS, Android, WebApp)FilePath- Path to the application installation fileInstallCommand- Command to install the applicationUninstallCommand- Command to uninstall the applicationDetectionRules- Array of detection rulesRequirements- Hashtable of requirements for the applicationAssignments- Array of group IDs to assign the application toAssignmentType- Type of assignment (Required, Available, Uninstall)LogPath- Path where logs will be stored
Example:
$detectionRules = @(
@{
Type = "File"
Path = "C:\Program Files\MyApp"
File = "myapp.exe"
Existence = $true
}
)
$requirements = @{
MinimumOS = "10.0.18363"
Architecture = "x64"
}
.\New-IntuneApplication.ps1 -AppName "My Application" -Description "Business application" -Publisher "Contoso" -AppType "Win32" -FilePath "C:\Packages\MyApp.intunewin" -InstallCommand "setup.exe /quiet" -UninstallCommand "setup.exe /uninstall /quiet" -DetectionRules $detectionRules -Requirements $requirements -Assignments @("12345678-1234-1234-1234-123456789012") -AssignmentType "Required"Description: Creates a new device compliance policy in Microsoft Intune.
Parameters:
PolicyName- Name of the compliance policyDescription- Description of the policyPlatform- Target platform (Windows10, iOS, Android, macOS)Settings- Hashtable of compliance settingsAssignments- Array of group IDs to assign the policy toAssignmentType- Type of assignment (Include, Exclude)LogPath- Path where logs will be stored
Example:
$settings = @{
passwordRequired = $true
passwordMinimumLength = 8
secureBootEnabled = $true
bitLockerEnabled = $true
antivirusRequired = $true
antiSpywareRequired = $true
defenderEnabled = $true
firewallEnabled = $true
}
.\New-IntuneCompliancePolicy.ps1 -PolicyName "Windows 10 Compliance Policy" -Description "Basic compliance policy for Windows 10 devices" -Platform "Windows10" -Settings $settings -Assignments @("12345678-1234-1234-1234-123456789012") -AssignmentType "Include"Description: Performs various management actions on Intune-managed devices.
Parameters:
Action- Action to perform (Restart, Wipe, Reset, Rename, Sync, Retire, Delete, LocateDevice)DeviceId- ID of the target deviceDeviceName- Name of the target device (alternative to DeviceId)NewDeviceName- New name for the device (for Rename action)BatchFile- Path to CSV file for batch operationsLogPath- Path where logs will be stored
Example:
.\Manage-IntuneDevice.ps1 -Action "Restart" -DeviceId "12345678-1234-1234-1234-123456789012"Description: Generates comprehensive reports about devices in Microsoft Intune and Azure AD, including device information, compliance status, configuration profiles, installed applications, and security status.
Parameters:
ReportType- Type of device report to generate (Basic, Detailed, Compliance, Profiles, Apps, Security, All)Filter- Hashtable of filters to apply to the reportTimeFrame- Time frame for activity data (Last7Days, Last30Days, Last90Days, LastYear)IncludePersonal- Whether to include personal devices in the reportIncludeRetired- Whether to include retired devices in the reportExportPath- Path where the report will be savedExportFormat- Format of the export file (CSV, JSON, Excel, HTML)LogPath- Path where logs will be stored
Example:
.\Get-DeviceReport.ps1 -ReportType Compliance -Filter @{OS="Windows"} -TimeFrame Last30Days -IncludePersonal $false -IncludeRetired $false -ExportPath "C:\Reports\WindowsCompliance.xlsx" -ExportFormat ExcelScripts for managing Microsoft 365 services including Exchange Online, SharePoint, Teams, and licenses.
Description: Creates a new user in Microsoft 365 with specified attributes and license assignments.
Parameters:
DisplayName- Display name for the userUserPrincipalName- User principal name (email format)Password- Initial passwordForceChangePasswordNextSignIn- Whether to force password change at next sign-inAccountEnabled- Whether the account should be enabledUsageLocation- Two-letter country code for license assignmentLicenseSkus- Array of license SKUs to assignCreateMailbox- Whether to create an Exchange Online mailboxMailboxType- Type of mailbox to create (User, Shared, Resource)LogPath- Path where logs will be stored
Example:
.\New-M365User.ps1 -DisplayName "John Doe" -UserPrincipalName "john.doe@contoso.com" -Password (ConvertTo-SecureString "P@ssw0rd123" -AsPlainText -Force) -ForceChangePasswordNextSignIn $true -AccountEnabled $true -UsageLocation "US" -LicenseSkus @("ENTERPRISEPACK") -CreateMailbox $true -MailboxType "User"Description: Creates a new Microsoft 365 group with specified attributes and members.
Parameters:
DisplayName- Display name for the groupMailNickname- Mail nickname for the groupDescription- Description of the groupVisibility- Visibility of the group (Private, Public)Owners- Array of user principal names to set as group ownersMembers- Array of user principal names to add as group membersCreateTeam- Whether to create a Teams team for the groupLogPath- Path where logs will be stored
Example:
.\New-M365Group.ps1 -DisplayName "Marketing Team" -MailNickname "marketing" -Description "Marketing department team" -Visibility "Private" -Owners @("john.doe@contoso.com") -Members @("jane.smith@contoso.com", "bob.johnson@contoso.com") -CreateTeam $trueDescription: Creates a new SharePoint Online site with specified configuration.
Parameters:
SiteType- Type of site to create (TeamSite, CommunicationSite)Title- Title of the siteUrl- URL for the siteDescription- Description of the siteOwners- Array of user principal names to set as site ownersMembers- Array of user principal names to add as site membersVisitors- Array of user principal names to add as site visitorsIsPublic- Whether the site is publicLocale- Locale ID for the siteTimeZone- Time zone ID for the siteLogPath- Path where logs will be stored
Example:
.\New-SharePointSite.ps1 -SiteType "TeamSite" -Title "Project X" -Url "https://contoso.sharepoint.com/sites/ProjectX" -Description "Project X collaboration site" -Owners @("john.doe@contoso.com") -Members @("jane.smith@contoso.com", "bob.johnson@contoso.com") -Visitors @() -IsPublic $false -Locale 1033 -TimeZone 10Description: Creates a new Exchange Online mailbox of specified type.
Parameters:
MailboxType- Type of mailbox to create (User, Shared, Room, Equipment)DisplayName- Display name for the mailboxPrimarySmtpAddress- Primary SMTP address for the mailboxAlias- Email alias for the mailboxUserPrincipalName- User principal name (for user mailboxes)Password- Initial password (for user mailboxes)RoomCapacity- Capacity of the room (for room mailboxes)ResourceCapacity- Capacity of the resource (for equipment mailboxes)AutoAccept- Whether to automatically accept meeting requests (for room/equipment mailboxes)Delegates- Array of users to set as delegates (for shared mailboxes)LogPath- Path where logs will be stored
Example:
.\New-ExchangeMailbox.ps1 -MailboxType "Shared" -DisplayName "Support Mailbox" -PrimarySmtpAddress "support@contoso.com" -Alias "support" -Delegates @("john.doe@contoso.com", "jane.smith@contoso.com")Description: Manages Microsoft 365 license assignments for users and groups.
Parameters:
Action- Action to perform (Assign, Remove, List, Report)UserPrincipalName- User principal name to manage licenses forGroupId- Group ID to manage licenses forLicenseSkus- Array of license SKUs to assign or removeDisabledPlans- Array of service plans to disableUsageLocation- Two-letter country code for license assignmentBatchFile- Path to CSV file for batch operationsExportPath- Path to export license reportLogPath- Path where logs will be stored
Example:
.\Manage-M365Licenses.ps1 -Action "Assign" -UserPrincipalName "john.doe@contoso.com" -LicenseSkus @("ENTERPRISEPACK") -DisabledPlans @("SWAY") -UsageLocation "US"Description: Manages Azure subscriptions including creation, assignment, and reporting.
Parameters:
Action- Action to perform (Create, Assign, Remove, List, Report)SubscriptionName- Name of the subscriptionSubscriptionId- ID of the subscriptionBillingAccount- Billing account IDBillingProfile- Billing profile IDInvoiceSection- Invoice section IDOfferType- Offer type for the subscriptionPrincipalId- ID of the user or group to assign the subscription toRoleDefinitionName- Role to assign (Owner, Contributor, Reader)ExportPath- Path to export subscription reportLogPath- Path where logs will be stored
Example:
.\Manage-AzureSubscription.ps1 -Action "Assign" -SubscriptionId "12345678-1234-1234-1234-123456789012" -PrincipalId "87654321-4321-4321-4321-210987654321" -RoleDefinitionName "Contributor"Scripts for managing Microsoft Teams teams, channels, members, and settings.
Description: Creates a new Microsoft Teams team with specified channels and settings.
Parameters:
TeamName- Name of the teamDescription- Description of the teamVisibility- Visibility of the team (Private, Public)Owners- Array of user principal names to set as team ownersMembers- Array of user principal names to add as team membersChannels- Array of channels to createAllowGuestAccess- Whether to allow guest accessAllowCreateUpdateChannels- Whether to allow members to create and update channelsAllowCreatePrivateChannels- Whether to allow members to create private channelsAllowDeleteChannels- Whether to allow members to delete channelsExistingGroupId- ID of an existing Microsoft 365 group to create the team fromLogPath- Path where logs will be stored
Example:
$channels = @(
@{Name="General"; Description="General channel"},
@{Name="Announcements"; Description="Team announcements"},
@{Name="Projects"; Description="Project discussions"}
)
.\New-TeamsTeam.ps1 -TeamName "Marketing Team" -Description "Marketing department team" -Visibility "Private" -Owners @("john.doe@contoso.com") -Members @("jane.smith@contoso.com", "bob.johnson@contoso.com") -Channels $channels -AllowGuestAccess $false -AllowCreateUpdateChannels $true -AllowCreatePrivateChannels $true -AllowDeleteChannels $falseDescription: Generates comprehensive reports about Microsoft Teams teams and their usage.
Parameters:
ReportType- Type of Teams report to generate (Basic, Membership, Channels, Activity, Settings, All)Filter- Hashtable of filters to apply to the report (e.g. @{Visibility="Private"; Status="Active"})TimeFrame- Time frame for activity data (Last7Days, Last30Days, Last90Days, LastYear)IncludeArchived- Whether to include archived teams in the reportExportPath- Path where the report will be savedExportFormat- Format of the export file (CSV, JSON, Excel, HTML)LogPath- Path where logs will be stored
Example:
.\Get-TeamsReport.ps1 -ReportType Membership -ExportPath "C:\Reports\TeamsMembership.csv" -ExportFormat CSVDescription: Manages Microsoft Teams team membership (owners and members).
Parameters:
Action- Action to perform (AddOwner, RemoveOwner, AddMember, RemoveMember)TeamId- ID of the target Microsoft Teams teamUserPrincipalNames- Array of user principal names (UPNs) to add or removeLogPath- Path where logs will be stored
Example:
.\Manage-TeamMembership.ps1 -Action AddMember -TeamId "12345678-1234-1234-1234-123456789012" -UserPrincipalNames @("user1@contoso.com", "user2@contoso.com")Description: Manages Microsoft Teams channels (create, delete, update).
Parameters:
Action- Action to perform (Create, Delete, Update)TeamId- ID of the target Microsoft Teams teamChannelName- Display name of the channel to manageNewChannelName- New display name for the channel (for Update action)Description- Description for the channelMembershipType- Membership type (Standard or Private)IsFavoriteByDefault- Whether the channel should be favorited by default (for Create action)LogPath- Path where logs will be stored
Example:
.\Manage-TeamChannel.ps1 -Action Create -TeamId "12345678-1234-1234-1234-123456789012" -ChannelName "Project Alpha" -Description "Channel for Project Alpha discussions"Description: Configures settings for a Microsoft Teams team.
Parameters:
TeamId- ID of the target Microsoft Teams teamAllowCreateUpdateChannels- Allow members to create and update channels ($true/$false)AllowDeleteChannels- Allow members to delete channels ($true/$false)AllowAddRemoveApps- Allow members to add and remove apps ($true/$false)AllowGuestAccess- Allow guest access ($true/$false)AllowGuestCreateUpdateChannels- Allow guests to create/update channels ($true/$false)AllowGiphy- Allow Giphy ($true/$false)GiphyContentRating- Giphy content rating (Strict, Moderate)AllowStickersAndMemes- Allow stickers and memes ($true/$false)LogPath- Path where logs will be stored
Example:
.\Set-TeamSettings.ps1 -TeamId "12345678-1234-1234-1234-123456789012" -AllowCreateUpdateChannels $false -AllowGuestAccess $falseScripts for managing security settings, Microsoft Defender, and security reporting.
Description: Configures Azure Security Center settings and policies.
Parameters:
SubscriptionId- ID of the subscriptionPricingTier- Pricing tier for Security Center (Free, Standard)AutoProvisioningSettings- Auto-provisioning settings for the Security Center agentWorkspaceId- Log Analytics workspace ID for data collectionSecurityContacts- Array of security contactsEnableDefender- Whether to enable Microsoft Defender for CloudDefenderPlans- Array of Defender plans to enableLogPath- Path where logs will be stored
Example:
$securityContacts = @(
@{Email="security@contoso.com"; Phone="+1-555-123-4567"; AlertNotifications=$true; AlertsToAdmins=$true}
)
$defenderPlans = @("VirtualMachines", "SqlServers", "AppServices", "StorageAccounts", "KeyVaults", "Containers")
.\Set-AzureSecurityCenter.ps1 -SubscriptionId "12345678-1234-1234-1234-123456789012" -PricingTier "Standard" -AutoProvisioningSettings "On" -WorkspaceId "87654321-4321-4321-4321-210987654321" -SecurityContacts $securityContacts -EnableDefender $true -DefenderPlans $defenderPlansDescription: Configures Microsoft 365 security settings including conditional access policies and security defaults.
Parameters:
Action- Action to perform (EnableSecurityDefaults, DisableSecurityDefaults, CreateConditionalAccessPolicy)PolicyName- Name of the conditional access policyPolicyState- State of the policy (Enabled, Disabled, EnabledForReportingOnly)IncludeUsers- Array of users to include in the policyExcludeUsers- Array of users to exclude from the policyIncludeGroups- Array of groups to include in the policyExcludeGroups- Array of groups to exclude from the policyIncludeApplications- Array of applications to include in the policyExcludeApplications- Array of applications to exclude from the policyGrantControls- Array of grant controls for the policySessionControls- Array of session controls for the policyLogPath- Path where logs will be stored
Example:
$grantControls = @{
Operator = "OR"
BuiltInControls = @("mfa", "compliantDevice")
}
.\Set-M365Security.ps1 -Action "CreateConditionalAccessPolicy" -PolicyName "Require MFA for All Users" -PolicyState "Enabled" -IncludeUsers @("All") -ExcludeUsers @("admin@contoso.com") -IncludeApplications @("All") -GrantControls $grantControlsDescription: Analyzes Microsoft Defender alerts to identify potential false positives.
Parameters:
TimeFrame- Time frame for alert analysis (Last7Days, Last30Days, Last90Days, LastYear)MinimumAlertCount- Minimum number of similar alerts to consider for false positive analysisExcludeAlertTypes- Array of alert types to exclude from analysisExportPath- Path to export false positive reportExportFormat- Format of the export file (CSV, JSON, Excel, HTML)LogPath- Path where logs will be stored
Example:
.\Analyze-DefenderAlertFalsePositives.ps1 -TimeFrame "Last30Days" -MinimumAlertCount 5 -ExportPath "C:\Reports\DefenderFalsePositives.xlsx" -ExportFormat "Excel"Description: Manages Microsoft Defender incidents including assignment, classification, and comments.
Parameters:
Action- Action to perform (Assign, Classify, Comment, Close, List)IncidentId- ID of the incidentAssignedTo- User to assign the incident toClassification- Classification of the incident (TruePositive, FalsePositive, Informational)ClassificationReason- Reason for the classificationComment- Comment to add to the incidentStatus- Status to set for the incident (New, Active, Resolved)ExportPath- Path to export incident reportLogPath- Path where logs will be stored
Example:
.\Manage-DefenderIncident.ps1 -Action "Classify" -IncidentId "12345" -Classification "FalsePositive" -ClassificationReason "Legitimate administrative activity" -Comment "Verified with system administrator"Description: Configures Microsoft Defender XDR settings including advanced features and integrations.
Parameters:
Action- Action to perform (ConfigureEDR, ConfigureIdentity, ConfigureOffice365, ConfigureEndpoints, ConfigureIntegrations)SubscriptionId- ID of the subscriptionWorkspaceId- Log Analytics workspace IDEnableAdvancedFeatures- Whether to enable advanced featuresEnableAuditLogs- Whether to enable audit logsEnableAutomaticSampleSubmission- Whether to enable automatic sample submissionEnableCloudDeliveredProtection- Whether to enable cloud-delivered protectionIntegrationType- Type of integration to configure (SIEM, SOAR, API)IntegrationSettings- Hashtable of integration settingsLogPath- Path where logs will be stored
Example:
$integrationSettings = @{
WorkspaceId = "12345678-1234-1234-1234-123456789012"
PrimaryKey = "abcdefghijklmnopqrstuvwxyz123456789="
EventTypes = @("SecurityAlert", "SecurityIncident", "AuditLogs")
}
.\Configure-DefenderXDR.ps1 -Action "ConfigureIntegrations" -IntegrationType "SIEM" -IntegrationSettings $integrationSettingsDescription: Generates comprehensive security reports from Microsoft Defender XDR.
Parameters:
ReportType- Type of report to generate (Alerts, Incidents, Vulnerabilities, SecureScore, Compliance, ThreatAnalytics, All)TimeFrame- Time frame for the report (Last7Days, Last30Days, Last90Days, LastYear)Filter- Hashtable of filters to apply to the reportIncludeRemediation- Whether to include remediation recommendationsExportPath- Path to export the reportExportFormat- Format of the export file (CSV, JSON, Excel, HTML)LogPath- Path where logs will be stored
Example:
.\Generate-DefenderSecurityReport.ps1 -ReportType "Incidents" -TimeFrame "Last30Days" -Filter @{Severity="High"} -IncludeRemediation $true -ExportPath "C:\Reports\HighSeverityIncidents.xlsx" -ExportFormat "Excel"Description: Generates comprehensive security reports for Microsoft Defender and Azure Security Center, including security alerts, incidents, vulnerabilities, secure score, and compliance status.
Parameters:
ReportType- Type of security report to generate (Alerts, Incidents, Vulnerabilities, SecureScore, Compliance, All)Filter- Hashtable of filters to apply to the reportTimeFrame- Time frame for security data (Last7Days, Last30Days, Last90Days, LastYear)IncludeInformational- Whether to include informational alerts in the reportIncludeResolved- Whether to include resolved items in the reportExportPath- Path where the report will be savedExportFormat- Format of the export file (CSV, JSON, Excel, HTML)LogPath- Path where logs will be stored
Example:
.\Get-SecurityReport.ps1 -ReportType Alerts -TimeFrame Last7Days -Filter @{Severity="High"} -IncludeInformational $false -IncludeResolved $false -ExportPath "C:\Reports\SecurityAlerts.xlsx" -ExportFormat ExcelDescription: Analyzes and reports on Attack Surface Reduction (ASR) rules configuration and events, helping security administrators identify potential false positives and optimize ASR rule deployment.
Parameters:
ReportType- Type of ASR report to generate (Configuration, Events, FalsePositives, Recommendations, All)TimeFrame- Time frame for ASR events data (Last7Days, Last30Days, Last90Days, LastYear)Filter- Hashtable of filters to apply to the reportIncludeAuditEvents- Whether to include audit mode events in the reportGroupByDevice- Whether to group results by device instead of by ruleExportPath- Path where the report will be savedExportFormat- Format of the export file (CSV, JSON, Excel, HTML)LogPath- Path where logs will be stored
Example:
.\Analyze-ASRRules.ps1 -ReportType FalsePositives -TimeFrame Last30Days -ExportPath "C:\Reports\ASRFalsePositives.xlsx" -ExportFormat ExcelScripts for managing data protection with Microsoft Purview and Windows Information Protection.
Description: Manages Windows Information Protection (WIP) policies for devices.
Parameters:
Action- Action to perform (Create, Update, Remove, List)PolicyName- Name of the WIP policyDescription- Description of the policyEnforcementLevel- Enforcement level (Off, Silent, Override, Block)EnterpriseProtectedDomains- Array of enterprise protected domainsEnterpriseIPRanges- Array of enterprise IP rangesEnterpriseProxyServers- Array of enterprise proxy serversEnterpriseInternalProxyServers- Array of enterprise internal proxy serversDataRecoveryCertificate- Data recovery certificateProtectedApps- Array of protected appsExemptApps- Array of exempt appsAssignments- Array of group IDs to assign the policy toLogPath- Path where logs will be stored
Example:
$protectedDomains = @("contoso.com", "contoso.net")
$protectedApps = @(
@{Name="Microsoft Edge"; Path="C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"},
@{Name="Microsoft Office"; Path="C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE"}
)
.\Manage-WindowsInformationProtection.ps1 -Action "Create" -PolicyName "Contoso WIP Policy" -Description "Windows Information Protection policy for Contoso" -EnforcementLevel "Block" -EnterpriseProtectedDomains $protectedDomains -ProtectedApps $protectedApps -Assignments @("12345678-1234-1234-1234-123456789012")Description: Manages Microsoft Purview compliance settings including data classification and retention policies.
Parameters:
Action- Action to perform (CreateSensitivityLabel, CreateRetentionPolicy, CreateDLPPolicy, List)Name- Name of the policy or labelDescription- Description of the policy or labelContentType- Content types the policy applies to (Email, Document, Site)SensitivityLabelSettings- Hashtable of sensitivity label settingsRetentionPolicySettings- Hashtable of retention policy settingsDLPPolicySettings- Hashtable of DLP policy settingsLocations- Array of locations to apply the policy toExcludedLocations- Array of locations to exclude from the policyPriority- Priority of the policyLogPath- Path where logs will be stored
Example:
$sensitivitySettings = @{
Tooltip = "Contains confidential information"
Color = "#FF0000"
Encryption = $true
EncryptionProtectionType = "Template"
EncryptionTemplateId = "12345678-1234-1234-1234-123456789012"
ContentMarkingEnabled = $true
HeaderText = "Confidential"
FooterText = "Contoso Confidential"
WatermarkText = "Confidential"
}
.\Manage-MicrosoftPurview.ps1 -Action "CreateSensitivityLabel" -Name "Confidential" -Description "Label for confidential information" -ContentType @("Email", "Document") -SensitivityLabelSettings $sensitivitySettingsDescription: Manages Microsoft Purview Information Protection settings including sensitivity labels, policies, and auto-labeling.
Parameters:
Action- Action to perform (CreateLabel, CreatePolicy, CreateAutoLabelingPolicy, List)Name- Name of the label or policyDescription- Description of the label or policyParentLabelId- ID of the parent label (for sub-labels)Tooltip- Tooltip for the labelColor- Color for the labelSensitivity- Sensitivity level (Low, Medium, High, Critical)EncryptionEnabled- Whether encryption is enabledEncryptionSettings- Hashtable of encryption settingsMarkingSettings- Hashtable of content marking settingsProtectionSettings- Hashtable of protection settingsAutoLabelingSettings- Hashtable of auto-labeling settingsScope- Scope of the policy (All, Exchange, SharePoint, OneDrive)Priority- Priority of the policyLogPath- Path where logs will be stored
Example:
$markingSettings = @{
HeaderEnabled = $true
HeaderText = "Confidential"
HeaderFontSize = 12
HeaderColor = "#FF0000"
HeaderAlignment = "Center"
FooterEnabled = $true
FooterText = "Contoso Confidential"
FooterFontSize = 12
FooterColor = "#FF0000"
FooterAlignment = "Center"
WatermarkEnabled = $true
WatermarkText = "Confidential"
WatermarkFontSize = 40
WatermarkColor = "#FF0000"
}
.\Manage-PurviewInformationProtection.ps1 -Action "CreateLabel" -Name "Confidential" -Description "Label for confidential information" -Tooltip "Contains confidential information" -Color "#FF0000" -Sensitivity "High" -MarkingSettings $markingSettingsAll scripts include comprehensive error handling and logging capabilities. By default, logs are stored in the Windows log directory, but you can specify a custom log path using the LogPath parameter.
Logs include:
- Timestamp
- Log level (Information, Warning, Error)
- Detailed message
Example log entry:
[2025-04-26 10:15:30] [Information] Successfully connected to Microsoft Graph as admin@contoso.com
-
Authentication: Always use secure authentication methods. Scripts are designed to use interactive authentication with a human account.
-
Error Handling: All scripts include comprehensive error handling. Check logs for detailed error information.
-
Testing: Always test scripts in a non-production environment before using them in production.
-
Permissions: Ensure the account running the scripts has the necessary permissions for the operations being performed.
-
Secure Storage: Store scripts in a secure location with appropriate access controls.
-
Parameter Validation: All scripts include parameter validation to prevent errors and security issues.
-
Logging: Review logs regularly to monitor script execution and troubleshoot issues.
For issues or questions about these scripts, please contact the author:
Author: Michael Witzsche Date: April 26, 2025 Version: 1.0.1