Get-AzPolicyAssignment

In this Azure PowerShell article, we will discuss the syntax and usage of the Get-AzPolicyAssignment PowerShell cmdlet and along with that, we will also discuss the use of the Get-AzPolicyAssignment PowerShell command with an example.

Table of Contents

Get-AzPolicyAssignment – Video Tutorial

Get-AzPolicyAssignment is a very good Azure PowerShell command to retrieve the policy assignments.

Below is the syntax of the Get-AzPolicyAssignment PowerShell command.

Now, let’s discuss a few examples of how to use the Get-AzPolicyAssignment PowerShell command with a few examples.

Below PowerShell command can help you to retrieve the lists of policy assignments.

After running the above command, I got the below output.

You can see the same output here as below

Get-AzPolicyAssignment

Check out a video tutorial on this command.

In this Azure article, we discussed, the syntax and usage of the Get-AzPolicyAssignment PowerShell cmdlet and along with certain examples of how to use this command.

Microsoft Azure

I am Rajkishore, and I am a Microsoft Certified IT Consultant. I have over 14 years of experience in Microsoft Azure and AWS, with good experience in Azure Functions, Storage, Virtual Machines, Logic Apps, PowerShell Commands, CLI Commands, Machine Learning, AI, Azure Cognitive Services, DevOps, etc. Not only that, I do have good real-time experience in designing and developing cloud-native data integrations on Azure or AWS, etc. I hope you will learn from these practical Azure tutorials. Read more .

4sysops

  • IT Administration Forum
  • PowerShell Forum
  • Community Forum
  • PowerShell Group
  • Earning as 4sysops member
  • Member Ranks
  • Member Leaderboard – This Month
  • Member Leaderboard – This Year
  • Member Leaderboard – All-time
  • Author Leaderboard – 30 Days
  • Author Leaderboard – 365 Days
  • Cloud Computing
  • Write for 4sysops

Manage Azure Policy using PowerShell

4sysops - The online community for SysAdmins and DevOps

Avatar

Policy definition

Policy initiative, policy rule, policy effects, policy assignment, policy scope, policy compliance, policy remediation, assign a built-in policy to a resource group, create a custom policy and assign it to a subscription, report policy compliance status.

  • Recent Posts

Baki Onur Okutucu

  • Use PowerShell to deploy and access GPT-4o in Azure OpenAI Service - Thu, Jun 6 2024
  • How to enable Azure App Service Automatic Scaling - Fri, Apr 19 2024
  • An Azure Storage Actions example - Fri, Mar 29 2024

With many built-in policies, you can easily start implementing governance and manage compliance throughout your organization. For advanced scenarios, you can also create your own custom policy definitions and flexibly assign them to the desired scopes based on your needs.

Here are some useful scenarios that can be implemented with Azure Policy:

  • Enforcing resource naming conventions based on specified patterns for new resources
  • Allowing only specific regions for certain resource types
  • Denying the creation of public IP addresses across the organization
  • Denying public access to resources such as storage accounts
  • Enabling features, such as Azure Monitor on Azure resources
  • Forcing supported resources to use private links.

First, let's zoom in on Azure Policy objects to understand how they work before diving into PowerShell commands to manage Azure Policies.

Azure Policy objects

Each Azure policy has a definition in JSON format comprising rules, parameters, conditions, and effects. With these elements defined in the policy definition, you can flexibly control resources based on the target scenario.

A policy rule is a section in a policy definition where you specify the policy's conditions using "If" and "Then" blocks.

Each policy definition must have an "effect" as part of its policy rule, which allows the policy to determine what action will be taken when there is a match between the policy rule and the target resource object. The supported effects that can be used in policy definitions are as follows:

  • AuditIfNotExists
  • DeployIfNotExists

For example, if you specify Audit as the effect in the policy definition, then Azure Policy will only audit the resources. Therefore, it will never block any resource creation or try to remediate noncompliant resources. If the effect is set to DeployIfNotExists , the Azure Policy will check the target and take the necessary actions to deploy missing resources based on the defined action plan in the policy definition.

Policy assignments are used to declare where the policy definitions are applied. You can create a policy assignment by linking an existing policy definition and specifying the target scope. In this way, the same policy definition object can be reused with another policy assignment.

This determines which resources to apply the policy to, based on the specified Azure Resource Manager resource path. A scope can be a single resource, a resource group, a subscription, or a management group. Exclusions and exemptions can also be configured to control the target scope in a more granular way.

When policies are applied to specific scopes, the resources in the target scopes are evaluated at specific times. This evaluation occurs whenever a resource or policy object is created, updated, or deleted. There is also a regular compliance check that evaluates the resources every 24 hours, even if nothing has changed.

Azure Policy also supports remediation when a resource is evaluated as noncompliant by an Azure policy. With remediation tasks, Azure policies can create deployments or modify existing resources to make them compliant.

Now we will perform common Azure Policy tasks using PowerShell.

First, let's list all available built-in policy definitions on Azure with the following command:

Listing built in policy definitions

Listing built in policy definitions

As listed above, hundreds of built-in policy definitions are available to use.

Now, we'll assign one of the built-in policy definitions, named "[Preview]: Storage account public access should be disallowed" and assign it to a resource group called AzurePolicyTest . With this assignment, we will be blocking public access on storage accounts within that resource group.

Creating a policy assignment using a built in policy definition

Creating a policy assignment using a built in policy definition

So when we try to create a storage account with public access enabled, we get the following error message, saying that the resource was disallowed by the Policy DenyStorageAccountPublicAccess we just created.

Azure Policy prevents disallowed resources

Azure Policy prevents disallowed resources

Now, we will create our own custom policy definition and assign it to an entire subscription.

Here is an example of a JSON definition that enforces a naming convention for resource groups:

Creating and assigning a custom policy definition to a subscription scope

Creating and assigning a custom policy definition to a subscription scope

When we try to create a resource group in the Western Europe region with a name that is not allowed by the policy, the policy fails with the message that we defined earlier.

Resource group creation failed due to a disallowed name for the resource group

Resource group creation failed due to a disallowed name for the resource group

If we need to exclude scopes, such as resource groups, subscriptions, or individual resources, we can simply define those scopes using the -NotScope parameter with the New-AzPolicyAssignment cmdlet.

So, if we want to assign a policy definition to an entire subscription except for a specific resource group, then we should use the following command:

The policy compliance status for a specific policy assignment can be checked easily using the following command:

Listing noncompliant resources for an individual policy assignment

Listing noncompliant resources for an individual policy assignment

The same data can also be found in the Azure Portal.

Policy compliance reports can also be checked in the Azure Portal

Policy compliance reports can also be checked in the Azure Portal

Use the following command to generate a summary:

All noncompliant resources and policies can be listed with a single command

All noncompliant resources and policies can be listed with a single command

Subscribe to 4sysops newsletter!

Azure policies have many useful capabilities for dynamically controlling Azure resources while implementing governance across the organization. The availability of numerous tools and platforms to control automatic deployments for new and existing resources enables DevOps teams to manage their environments reliably. With Blueprint support, it is even easier for large enterprises to implement predefined templates, such as ISO 270001, CAF Foundation, and HIPAA, to support regulatory requirements.

avatar

IT Administration News

  • Windows 10 Start Menu will soon display ads for Microsoft 365 – gHacks Tech News
  • Microsoft: Exchange Online mistakenly tags emails as malware
  • Rejoice! Microsoft suggests it may never truly kill Windows Control Panel – Neowin
  • Microsoft AI employees reportedly paid more than peers
  • Exchange Online Message Recall Updates – Microsoft Community Hub

Read All IT Administration News

Join the 4sysops PowerShell group!

Your question was not answered? Ask in the PowerShell forum!

The report displays the email count for each HVE account

High Volume Email in Microsoft 365: Overcoming sending limits

Avatar

Send email notifications about expiring Active Directory passwords with a PowerShell script

Avatar

What is Microsoft 365 Backup?

Avatar

Unlock BitLocker drive from Windows PE with a PowerSell script

Azure AD PowerShell seamlessly integrates with Entra PowerShell within a single PowerShell session

Microsoft Entra PowerShell module, successor to the Azure AD PowerShell module

Daily retrieval of critical vulnerability alerts

Receive critical Microsoft security alerts by email

Standard development tools are pre-installed in the CloudShell environment

Install AWS CloudShell in a VPC

Avatar

Search and delete Copilot data in Microsoft 365

Mapping array index to XML elements

Audit Group Policy changes in the event log using XML queries and PowerShell

Resetting a computer from Windows RE to a restore point

Create, configure, and delete system restore points with PowerShell, vssadmin.exe, and System Properties

Signing in to AWS with Touch ID

Enable FIDO passkey authentication for IAM users in AWS

Applying OpenTofu resources to AWS

Setting up EC2 instance access to an S3 bucket using IAM and OpenTofu

Avatar

Use PowerShell to deploy and access GPT-4o in Azure OpenAI Service

Results of an audit search using the manual HTTP method and exported to a CSV file

Microsoft Purview Audit Search Graph API: Retrieve audit logs from Microsoft 365 with PowerShell

On the OSDCloudGUI, users can select drivers for numerous PC models from various manufacturers.

Deploy Windows 11 with the free PowerShell framework OSDCloud

Flow of an external authentication with Entra ID. Courtesy: Microsoft

Configuring external authentication methods in Microsoft 365 with Microsoft Entra ID

Microsoft Graph and its interconnected components

Integrate Microsoft Graph activity logs for Microsoft 365 with Azure Monitor

Representation of a multitenant organization

The new Microsoft 365 multitenant organization feature

Running an OpenTofu init

Create an S3 bucket in AWS with OpenTofu

Exchange Online Interacting with Azure Communication Services Email

Disable Basic Authentication for SMTP AUTH in Exchange Online

Avatar

Hi. Thanks for the article. Regarding Tagging, Azure Policy seems to focus on only Adding/appending/inheriting tags. What I want to know, is how can one create a policy that will apply an action only if a specific Tag is found on a resource in the subscription?

Leave a reply Click here to cancel the reply

Please enclose code in pre tags: <pre></pre>

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.

Receive new post notifications

Twitter

Subscribe to Newsletter

Follow 4sysops.

Please ask IT administration questions in the forums . Any other messages are welcome.

Log in with your credentials

or      Create an account

Forgot your details?

Create account.

How to Get All Azure Policy Assignments of a Specific Category?

  • 2-minute read

I’ve been in quite a pickle recently: I needed to find out how many and what Azure Policy definitions from Guest Configuration category are currently assigned to my subscription, so that I could understand if any of those policies are applicable to Azure Arc-enabled servers that are residing in the same subscription. Why?

Well, because Guest Configuration is a billed functionality, when it comes to Azure Arc. In this case it’s good to get an overview if any policies related to the billed functionality are enabled in order to further evaluate if you want to use this functionality or not (and therefore disable it to avoid undesired billing). You may also have different use cases for why you would want to retrieve the same information from Azure Policy🧐

After some time investigating I discovered that it’s quite a challenging to retrieve this kind of information in Azure portal: you can see the category of every single Azure Policy definition in the list of all definitions, but you can’t use policy category as a filter on assignments or compliance page. There’s no single-line solution in Azure CLI either.

That’s when I got lazy once again and leaned back to my dear friend PowerShell to achieve this😅 Following PowerShell script retrieves all policy definition assignments coming both from regular policy assignments and policy initiative assignments. If any of the assigned policies belong to the requested category, like Guest Configuration in my case, information about those policies will be provided as output upon script execution.

You can find the PowerShell script in my GitHub repo: Get-Policy-Assignments-In-Category.ps1

The output will look something like the screenshot below:

Screenshot of the PowerShell script output

Already tested it out? Let me know how it went!🤗

That’s it from me this time, thanks for checking in!💖

If this article was helpful, I’d love to hear about it! You can reach out to me on LinkedIn, X, GitHub or by using the contact form on this page.😺

Stay secure, stay safe.

Till we connect again!😻

get policy assignment powershell

TimmyIT.com

TimmyIT.com

Get all assigned Intune policies and apps per Azure AD group

IMPORTANT NOTICE. A new updated article on this topic has been published here: https://timmyit.com/2023/10/09/get-all-assigned-intune-policies-and-apps-from-a-microsoft-entra-group/ The new article covers using the new Microsoft.Graph Powershell SDK instead of the old Intune Powershell SDK that has not been updated since 2019. I recommend you take a look at the newer article.

Get all assigned Intune policies and apps from a Microsoft Entra group

During MMS JAZZ Edition in New Orleans a couple of weeks ago me and the amazing Sandy Zeng did a presentation on using the Intune Powershell SDK and in this demo packed session we showed off a script that were able to find assigned policies and apps from AAD groups.

https://mmsjazz.sched.com/event/Rmdh/intune-graph-api-ftw

More info about MMS:

https://mmsmoa.com/

Little bit of a back story to this script. One of the most frustating things we’ve came a cross when working with Intune and AAD is the lack of capability to go to an AAD group and see what kind of Intune assignments has been targeted to that group. What you have to do instead is to go to each policy or app and see which group it’s assigned to, this can be a nightmare if you have a lot of different policies and apps assigned to multiple groups.

get policy assignment powershell

In the sample script below we have one section for getting information for all the Applications thats been assigned and then we have one section for Device Compliance, Device Configuration, Device Configuration Powershell scripts and Administrative templates.

The one thing that might be confusing when looking throug the script is the fact that not all policies even tho they are in the same blade and pane in the Intune portal they haven’t one common propertyname.

So for example, Device Configuration policies and Administrative templates are different and when we use the Intune Powershell SDK and the Get-IntuneDeviceConfigurationPolicy we won’t get any Administrative templates or powershell scripts. I haven’t been able to find any specific cmdlet for those in the 1907 SDK version so thats why we need to do a Invoke-MSGraphRequest to be able to get those policies.

Note. You need to have the Intune Powershell module installed to use the script. https://www.powershellgallery.com/packages/Microsoft.Graph.Intune/6.1907.1.0

Sample script

The result of running script will be output to the screen using Write-host and give you information on which group did it look at and what kind of policy or app did it find and out put the name of it.

get policy assignment powershell

Running the sample script on all AAD groups

If you instead want to run the script against all of your Azure AD groups you can simply do this by just changing the $Group variable and then add a foreach loop. If you have a lot of AAD groups it can take a while for the script to run.

get policy assignment powershell

Thats it for this time, leave any comments below and don’t forget to follow me on twitter @Timmyitdotcom You can also find me blogging over at http://blog.ctglobalservices.com/

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)

61 comments

Exactly what I needed after inheriting an existing Intune deployment that 3 other IT providers have been administering over the past 3 years… Thanks!

When I run Get-IntuneMobileApp I dont’t get “assignments”property. Any ideas why? Thanks!

change line 17. its backwards. need to -expand property before selecting it

$AllAssignedApps = Get-IntuneMobileApp -Expand assignments | Select id, displayName, lastModifiedDateTime, assignments | Where-Object {$_.assignments -match $Group.id}

Please correct me if I’m wrong, but to my understanding “Get-AADGroup” is not a real command. What you should be using is Get-AzureADGroup ?

Get-AADGroup is one of the cmdlets in the Intune Graph SDK.

Great resource and learning aid to GraphAPI for Intune.

There is however an error in the # Device Configuration Powershell Scripts section in both scripts.

$AllDeviceConfigScripts = $DMS.value | Where-Object {$_.assignments -match $Group.id}

$AllDeviceConfigScripts = $DMS.value | Where-Object {$_.groupAssignments -match $Group.id}

You say “If you have a lot of AAD groups it can take a while for the script to run.” You can speed this up significantly by running:

$AllAssignedApps = Get-IntuneMobileApp -Select id, displayName, lastModifiedDateTime, assignments -Expand assignments $AllDeviceCompliance = Get-IntuneDeviceCompliancePolicy -Select id, displayName, lastModifiedDateTime, assignments -Expand assignments $AllDeviceConfig = Get-IntuneDeviceConfigurationPolicy -Select id, displayName, lastModifiedDateTime, assignments -Expand assignments

..outside of the main loop, and:

$AssignedApps = $AllAssignedApps | Where-Object {$_.assignments -match $Group.id} $DeviceCompliance = $AllDeviceCompliance | Where-Object {$_.assignments -match $Group.id} $DeviceConfig = $AllDeviceConfig | Where-Object {$_.assignments -match $Group.id}

..inside it.

that’s a great idea, thanks for the input

Echoing the previous comment made for gathering assigned PowerShell scripts.

you can verify by looking at $DMS.Value … there’s no “assignments” property.

thanks, I’ll update the script as soon as i get time.

I’ve modified the script to make it run faster and slightly more readable: https://pastebin.com/ZVr2VCwP

Sorry, pasted wrong link. Here’s the correct one – https://pastebin.com/gq3YEcFT

Great scripts! works well

great script , but it doesn’t list the ” settings catalog ” profiles type deployed

+1 Can you please update the script to search settings catalog as well?

  • Pingback: MANAGING INTUNE WITH POWERSHELL - TALES FROM THE DESKTOP

Here is what I added to the script get the settings catalogs:

# Settings Catalogs $Resource = “deviceManagement/configurationPolicies” $graphApiVersion = “Beta” $uri = “https://graph.microsoft.com/$graphApiVersion/$($Resource)?`$expand=Assignments” $SC = Invoke-MSGraphRequest -HttpMethod GET -Url $uri $AllSC = $SC.value | Where-Object {$_.assignments -match $Group.id} Write-host “Number of Device Settings Catalogs found: $($AllSC.Name.Count)” -ForegroundColor cyan

Foreach ($Config in $AllSC) {

Write-host $Config.Name -ForegroundColor Yellow

thank you, I will test this.

Seems to work great, awesome!

Exactly what I needed! Works great thanks for putting this up!

Thank you! This is great as is and an awesome jumping off point to customize and learn!

I would like to try this script. Does anyone have a version that combines the improvements from chaozkreator and the section for Settings Catalogue at GitHub or another location? Unfortunately I cannot access the script at the location chaozkreator provided.

Thank you all for your help!

# Fixed scripts # Added group members # Added Settings Catalogs

# Connect and change schema Connect-MSGraph -ForceInteractive Update-MSGraphEnvironment -SchemaVersion beta Connect-MSGraph

# All Intune groups in AAD $Groups = Get-AADGroup | Get-MSGraphAllPages | Where {($_.displayName -like “NL-*” -or $_.displayName -like “*Intune*”)}

#### Config Foreach ($Group in $Groups) { Write-host “AAD Group Name: $($Group.displayName)” -ForegroundColor Green

# Members $AllAssignedUsers = (Get-AADGroupMember -groupId $Group.id) | Select-Object -Property displayName Write-host ” Number of Users found: $($AllAssignedUsers.DisplayName.Count)” -ForegroundColor cyan Foreach ($User in $AllAssignedUsers) {

Write-host ” “, $User.DisplayName -ForegroundColor Gray

# Apps $AllAssignedApps = Get-IntuneMobileApp -Filter “isAssigned eq true” -Select id, displayName, lastModifiedDateTime, assignments -Expand assignments | Where-Object {$_.assignments -match $Group.id} Write-host ” Number of Apps found: $($AllAssignedApps.DisplayName.Count)” -ForegroundColor cyan Foreach ($Config in $AllAssignedApps) {

Write-host ” “, $Config.displayName -ForegroundColor Yellow

# Device Compliance $AllDeviceCompliance = Get-IntuneDeviceCompliancePolicy -Select id, displayName, lastModifiedDateTime, assignments -Expand assignments | Where-Object {$_.assignments -match $Group.id} Write-host ” Number of Device Compliance policies found: $($AllDeviceCompliance.DisplayName.Count)” -ForegroundColor cyan Foreach ($Config in $AllDeviceCompliance) {

# Device Configuration $AllDeviceConfig = Get-IntuneDeviceConfigurationPolicy -Select id, displayName, lastModifiedDateTime, assignments -Expand assignments | Where-Object {$_.assignments -match $Group.id} Write-host ” Number of Device Configurations found: $($AllDeviceConfig.DisplayName.Count)” -ForegroundColor cyan Foreach ($Config in $AllDeviceConfig) {

# Device Configuration Powershell Scripts $Resource = “deviceManagement/deviceManagementScripts” $graphApiVersion = “Beta” $uri = “https://graph.microsoft.com/$graphApiVersion/$($Resource)?`$expand=groupAssignments” $DMS = Invoke-MSGraphRequest -HttpMethod GET -Url $uri $AllDeviceConfigScripts = $DMS.value | Where-Object {$_.groupAssignments -match $Group.id} Write-host ” Number of Device Configurations Powershell Scripts found: $($AllDeviceConfigScripts.DisplayName.Count)” -ForegroundColor cyan

Foreach ($Config in $AllDeviceConfigScripts) {

# Settings Catalogs $Resource = “deviceManagement/configurationPolicies” $graphApiVersion = “Beta” $uri = “https://graph.microsoft.com/$graphApiVersion/$($Resource)?`$expand=Assignments” $SC = Invoke-MSGraphRequest -HttpMethod GET -Url $uri $AllSC = $SC.value | Where-Object {$_.assignments -match $Group.id} Write-host “ Number of Device Settings Catalogs found: $($AllSC.Name.Count)” -ForegroundColor cyan

Write-host ” “, $Config.Name -ForegroundColor Yellow

# Administrative templates $Resource = “deviceManagement/groupPolicyConfigurations” $graphApiVersion = “Beta” $uri = “https://graph.microsoft.com/$graphApiVersion/$($Resource)?`$expand=Assignments” $ADMT = Invoke-MSGraphRequest -HttpMethod GET -Url $uri $AllADMT = $ADMT.value | Where-Object {$_.assignments -match $Group.id} Write-host ” Number of Device Administrative Templates found: $($AllADMT.DisplayName.Count)” -ForegroundColor cyan Foreach ($Config in $AllADMT) {

oh my god, thank you so much !

Hi, great tool! Thanks

Sharing my modification

##################### select groups by containing text

###################### new section listing members of the group

# members $AllAssignedUsers = (Get-AADGroupMember -groupId $Group.id) | Select-Object -Property displayName Write-host ” Number of Users found: $($AllAssignedUsers.DisplayName.Count)” -ForegroundColor cyan Foreach ($User in $AllAssignedUsers) { Write-host ” “, $User.DisplayName -ForegroundColor Gray }

############################################################################

You guys are the best. Had a call with MS re this yesterday and they had nothing!! Thank the Lord for community

Trying to use this (looks helpful) but I am unsure how to make it work. I placed the code into a .ps1 file and tried to execute it but even after allowing the script to run it still fails and does not even attempt to prompt me to connect to the online services. I am use MFA.

Got it, I forgot to load the graph addin

For some reason I don’t see the powershell scripts. Result show 0 but I have some assigned to the group?

Love it….. is there a way to do the following I tried to decipher the PS code but was unsuccessful. 1. Get any security policies: Antivirus, Firewall, Encryption ect. 2. Instead of scanning a security Group scan a device by name?

hey guys. how about displaying the Proactive Remediation scripts? do you have any idea how to do it?

This is what I am using and seems to work well. Rest of the script and output is the same as other areas.

# Proactive Remediation $Resource = “deviceManagement/deviceHealthScripts” $graphApiVersion = “Beta” $uri = “https://graph.microsoft.com/$graphApiVersion/$($Resource)?`$expand=Assignments” $Proactive = Invoke-MSGraphRequest -HttpMethod GET -Url $uri $AllProactive = $Proactive.value | Where-Object {$_.assignments -match $Group.id}

Thanks for sharing !

great info. it works perfectly. thanks.

Does anyone know of a way to save the output of this into a csv?

Your original script is fantastic. Thank you!! Our environment has thousands of AAD groups so it’s a lot to weed through. I’ve used some of the tweaks that others have made to improve the script in the following ways: 1. Faster as it only does a single API query run for all groups and uses a for-each to process the data from the array. 2. Added Settings Catalogs to the script 3. My own addition of a conditional for outputting data from each group, as I’m not interesting in knowing if a group has 0 assigned policies and apps. Literally thousands! 🙂

https://pastebin.com/Taz6KFtk

^ This way I only get AAD groups which have Intune policies, apps etc

Great script! Thank you so much for sharing! Is there a way to add if the app is deployed as “required” or “available”?

Microsoft must have changed something recently, because listing of apps through “$AllAssignedApps = Get-IntuneMobileApp -Expand assignments | Select id, displayName, lastModifiedDateTime, assignments” does not work anymore. It was working maybe 2 weeks ago. Now, it seems that the property “assignments” is no longer present in the application attributes, that are retrieved from Graph API and it returns 0 apps for all groups. How do you tackle that?

Im having the same issue too, would be great to have this resolved. Thanks

Nice Script. Would you check this script too: https://github.com/sibranda/GetIntuneAssignments

I found that one too. This C# app need registration in azure app’s on your tenant, if you can’t “read” this language very well you don’t know what it does. So security wise don’t just trust it. Make sure with someone that knows C# pretty good the app is safe and doesn’t open any backdoors or something.

Number of Device Configurations Powershell Scripts found: 0

But group in question definitely has PS scripts assigned…

There was a typo in the script, it has been fixed now.

Guys this is incredible! Thanks!

Guys, I found this crazy script too https://www.powershellgallery.com/packages/Get-IntuneGroupAssignments/1.0/Content/Get-IntuneGroupAssignments.ps1

FYI theres a typo in the scripts part:

$AllDeviceConfigScripts = $DMS.value | Where-Object {$_.groupassignments -match $Group.id}

Could have been something Microsoft have changed though as I know it was written a few years ago

Hi I have over 1000 Apps so the script doesnt list any apps assigned to groups. I believe its due to the script not including paging and i think some data for additional pages go into odata.nextlink and so the script needs modification to take into account large numbers. Would be amazing if you could modify this script. Thanks

Hello, I use this script a lot, but I just found an inconsistency, what makes me wonder if I have missed any assignments in the past.

I have a user group where I have applied two configuration policies to. – set desktopbackground and lockscreen image – set edge to open a new specified tab Both of them are applied and work, When I run the script it only shows me the “set desktop background and lockscreen image” has been applied. The policy about edge is not mentioned.

Any ideas? Thanks

Its most likely that those 2 policies are using different Graph API resources. Some settings and policies uses different resources in the backend tho from the UI they are configured in the same place. I would need to get some more info on the settings and how you configured them to be able to test it myself. What OS are they for ? And are they from the Settings catalog or Templates ?

Hi all, has anyone re-written the original script for Powershell 7.0+ yet? Love the idea of this, but need it updated for PS 7.

Super! Appreciated.

This is an awesome script! Any chance there’s a way to add endpoint security policies as well?

Thank you for this script. I tried to put all outputs into an excel with export-excel but failed. Does someone know how to modify the script to get the output as an excel?

Any specific reason why you want to use export-excel ? What if you try, export-csv and open the file with excel. Or out-file and save it as any other format ?

I have to send this as a report to another departement and they need it as a formatted excel file.the reason is that they have other scripts for automation processes that grab information from certain colums.

Can we export the output of powershell script in excel file?

Hey All, I’m able to connect to the tenant but then I get a “Get-MSGraphNextPage: Not authenticated. Please use the “Connect-MSGraph” command to authenticate”. arguement. Any thoughts?

Great script! Couldn’t work out why some proactive remediation scripts weren’t showing, then realised they’re assigned to ‘All Users’ or ‘All Devices’. So, in the assignments I’m seeing two groups with IDs starting ‘acacacac…’ and ‘adadadad…’ but they don’t show in the group list! Am i on the right track?

  • Pingback: Get all assigned Intune policies and apps from a Microsoft Entra group

Leave a Reply Cancel reply

Discover more from timmyit.com.

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

Type your email…

Continue reading

Subscribe for Practical 365 updates

Please turn off your ad blocker and refresh the page to subscribe.

You may withdraw your consent at any time. Please visit our Privacy Statement for additional information

Blog / PowerShell / Teams

Use powershell to create a report about the teams policies assigned to user accounts.

Avatar photo

I’m often asked why the Microsoft 365 admin consoles omit the print option. For instance, go to the Active users section of the Microsoft 365 admin center and look for a way to print a list of users. There isn’t one. What usually exists is an option to export data (users in this case) to a CSV file.

I think several reasons exist why Microsoft takes this approach with admin consoles. First, the consoles page information for display. As you move to the bottom of the list, more data appears until the complete set is present (I’ve never tried this with a tenant with 50,000 users, but that’s the theory). This implementation is consistent with the way the Graph APIs fetch data. In larger tenants, paging works better than if you were forced to wait for all data to be available. Second, the engineering effort to implement and support print options across all the admin consoles might be a cost Microsoft wants to avoid. Third, the export option allows tenants to download the information and format it according to their own requirements (all organizations have their own formats). Last, programmatic access to the data is often available through PowerShell or Graph API. Overall, it’s hard to complain too much about the lack of printing support in Microsoft 365 admin consoles.

Teams Policies

Which brings me neatly to Teams and a request to generate a report of the policies assigned to user accounts. As you know, Teams is extraordinary fond of policies. A recent check revealed 40 separate Teams policies which can be assigned to an account (sixteen policies are available for editing through the Teams admin center). Unless they’re involved with the Teams Phone system (which consumes many policies), the average Teams administrator might interact with the following set:

  • Meeting Policy: Controls capabilities available in Teams meetings.
  • Messaging Policy: Controls capabilities in Teams chat and channel messages.
  • App Setup Policy: Controls the apps pinned to the app navigation bar and the apps users can install.
  • App Permission Policy: Controls the set of apps available to Teams users .
  • Enhanced Encryption Policy: Controls the availability of Teams end to end encryption in 1:1 calls.
  • Update Management Policy: Controls if users can access preview features .
  • Channels Policy: Controls if users can create new private and shared channels.
  • Feedback Policy: Controls if users are prompted to send feedback surveys to Microsoft.
  • Live Events Policy: Controls how the user can create live events.

With this set of policies in mind, we can write some PowerShell to generate a report of Teams policy assignments.

get policy assignment powershell

Coding the Report

The report script is very straightforward.

  • Connect to the Microsoft Teams PowerShell module to fetch information about the policies assigned to users.
  • Connect to the Exchange Online manage m ent PowerShell module . This is an optional connection that I use to fetch the tenant name for the report using the Get-OrganizationConfig cmdlet. You could also use the Get-AzureADTenantDetail cmdlet from the Azure AD module.
  • For each user, extract the policy assignments and update a PowerShell list object. It’s easy to add or substract policy assignments to customize the output. If the default policy is used, we output “Tenant Default” (you can chose a different name if you like), otherwise the script inserts the name of the assigned policy.
  • When all users are processed, use the list data and some HTML code to create a HTML file.
  • Create a CSV file using the report data to make it easy to analyze the assignments.
  • Finish up by reporting success and the names of the created files.

Figure 1 shows an example of the report. As you can see, the report lists the assignment for each of the nine targeted polices for each user.

Reporting the Teams policy assignments for users

You can download the script from GitHub . Feel free to amend the code to suit the requirements of your tenant. The basics will remain the same, but you might want to add some extra policies or spruce up the formatting of the report.

The Power of the Shell

The script didn’t take long to write (admittingly, I had the HTML bits to hand). It’s yet another proof of how useful PowerShell is to Microsoft 365 tenant administrators in terms of filling the gaps left by Microsoft. Or, put another way, going where Microsoft choses not to go. Enjoy!

About the Author

Avatar photo

Tony Redmond

' src=

Thanks for the post and the script Tony. The script forms the perfect starting point for what I need next week.

' src=

I would like to only extract list of users who has been assigned to the “Global’ app permission policy Get-CsOnlineUser -Filter {TeamsAppPermissionPolicy -eq ”} | Export-CSV

Not sure how to mentioned to extract “Global”, I have tried with $null, blank and global.. no success

Any help plz

The Real Person!

Try: Get-CsOnlineuser | where-Object {$Null -eq $_.TeamsAppPermissionPolicy} | Format-Table DisplayName

' src=

Thanks Tony for the prompt response, I only have 3 user fields in the csv that I’m using SIP, UPN and Email, so I still need to get their policy values with get-csonline user. If I run as is I cant retrieve the users policies

[array]$Users = import-csv ./masterlist_summary1.csv $Report = [System.Collections.Generic.List[Object]]::new() # Process each user to fetch their policy assignments ForEach ($user in $Users) { $TenantDefaultString = “Tenant Default” $TenantDialPlan = $TenantDefaultString

Of course you’ll need to retrieve the policy information for each user with Get-CsOnlineUser. I meant that you wouldn’t use the cmdlet to fetch the set of users for processing.

Because your CSV file only contains three properties with different names to those returned by Get-CsOnlineUser, the command to fetch details for each user will be something like Get-CsOnlineUser -Identity $User.UPN instead of what’s in the script now.

Thanks for the reply. Unfortunately I’m not very good at powershell but I can understand how your script is creating the array from up to 5000 users in the tenant. What I’m confused by is your script has 1 array that is used to get-csonlineuser, retrieves the results for up to 5000 users and then can optionally filter on the array. If I change that $users array to be “[array]$Users = Import-CSV ./Users.csv” then it removes the get-csonlineuser. My question is how do I create an array with my csv AND run get-csonlineuser at the same line of code? I’m not sure how that looks. Really appreciate your help.

There are two lines in the script that fetch users and prepare them for processing:

[array]$Users = Get-CsOnlineUser -ResultSize 5000 # Filter the set to get Teams users – this will filter out all but cloud-only Teams users. If you don’t want to use the filter, comment it out. $Users = $Users | Where-Object {$_.InterpretedUserType -eq “PureOnlineTeamsOnlyUser” -or $_.InterpretedUserType -eq “PureOnlineTeamsOnlyUserFailedPublishingToAAD”} | Sort-Object DisplayName If (!($Users)) {Write-Host “No users found – exiting”; break }

Replace these lines with: [array]$Users = Import-CSV filename…

You don’t need to run Get-CsOnlineUser if you’re providing user details another way.

Sorry meant to say how can I run the script against users in A CSV. We are migrating users in batches so I only want to report on that rather than running the script against the whole organisation and doing matches in Excel against the migration group.

The script uses these lines of code to find the set of users to process:

[array]$Users = Get-CsOnlineUser -ResultSize 5000 # Filter the set to get Teams users – this will filter out all but cloud-only Teams users. If you don’t want to use the filter, comment it out. $Users = $Users | Where-Object {$_.InterpretedUserType -eq “PureOnlineTeamsOnlyUser” -or $_.InterpretedUserType -eq “PureOnlineTeamsOnlyUserFailedPublishingToAAD”} | Sort-Object DisplayName

Instead, to build the set of users to process from a CSV, you’d use a command like:

[array]$Users = Import-CSV Users.csv

Great script. Can I ask how can I run the script only against users in the CSV (a group of users not the whole organisation)

Leave a Reply Cancel reply

Latest articles.

Improving your AD Security with Derek Melber: The Practical 365 Podcast S04 E25

Improving your AD Security with Derek Melber: The Practical 365 Podcast S04 E25

On the show this week, Steve Goodman and Rich Dean are joined by speaker guest, TEC speaker & 20-time Microsoft MVP, Derek Melber to discuss Securing your AD, removing NTLM passwords from use in your organization, and the aftermath of Crowdstrike.

Practical Teams:  Using Templates and Sensitivity Labels with Teams Meetings

Practical Teams:  Using Templates and Sensitivity Labels with Teams Meetings

In this episode of Practical Teams, we dive into meeting templates and sensitivity labels, exploring how labels and templates can be used to adhere to requirements, policies, and if necessary, enforce some applicable settings in meetings.

How to Handle an Unwanted Sensitivity Label

How to Handle an Unwanted Sensitivity Label

Sometimes sensitivity labels defined for use within a Microsoft 365 tenant turn out to be unnecessary. The question then is what to do with these unwanted sensitivity labels. The answer is to pause for thought, gather information, and then make an informed decision, all of which we discuss here.

  • SharePoint Online

Microsoft 365 Scripts

Microsoft 365 scripts repository.

m365scripts.com

Group Policy Assignments Using Microsoft Teams PowerShell

Group Policy Assignments Using Microsoft Teams PowerShell

Unmanaged devices, external file-sharing, and email integration impose a big question mark on the security posture of Microsoft Teams. In order to secure and manage Microsoft Teams, policies are used under various sections like messaging, meetings, calling, conferencing, and many more. Usually, these Teams policies for users, groups, and batches are managed in the Microsoft Teams admin center or using the Teams PowerShell Module (TPM). But now Microsoft extends the managing capability of additional Office 365 group policies using the Teams PowerShell Module as per MC557818 .

According to this latest update, group policy assignments for Microsoft 365 groups, distribution lists, mail-enabled security groups, and security groups support additional policies in the Teams PowerShell Module. Apart from action control, policy assignments also set way for security controls like restricting anonymous access in meetings.

Let us see how to assign group policies using Microsoft Teams PowerShell Module and their functionalities under this blog.

What are Group Policy Assignments?

As the name suggests, assigning a policy to a particular group of users is known as a group policy assignment. The groups can be managed in Microsoft 365 admin center whereas group policies can be managed under the single roof of the Teams PowerShell Module.

Policy assignments are applied only to the direct members of a group and not to the nested group. That too, they are applied according to the precedence rules. And at the time of addition or deletion of users from a group, the policy assignments are updated which is also applicable when a policy is unassigned. Before jumping into group policy assignments, let us look through the precedence rules and ranking of policies.

What are Microsoft Teams Policy Precedence Rules?

Policy precedence determines the user’s effective policy when a user is assigned two or more of the same policy types. The precedence rules of policies are listed below for deeper insights into how an assigned policy will be deployed according to these rules.

  • If a user is directly assigned a policy, the same type of policy can’t be inherited from the group. Therefore, the directly assigned policy takes precedence over the same policy type defined by the group.
  • Also, if a user doesn’t contain a directly assigned policy, the user inherits the highest-ranking policy from the same type of policies applied by two or more groups.
  • Finally, if the user is not assigned a policy directly or by group, then the global (organization-wide) policy takes precedence .

The user policy is updated under the following circumstances.

  • Especially when a user is added or removed from the policy assigned group.
  • And when a group policy is unassigned.
  • At last, if a directly assigned policy is removed from a user.

What is Group Policy Assignment Rank in Teams?

As an admin, you are asked to define the rank of policy while assigning the policy. Primarily this ranking weighs the priority of the same type of policies assigned from two or more groups for a common user. Finally, the highest-ranking group policy is assigned as the effective policy to the end user after weighing the priority. Because a policy type can be assigned to a maximum number of 64 groups in Office 365.

NOTE: If the rank value is undefined, then the lowest ranking is given to the policy assignment.

How to Assign Policy to a Group in Teams Admin Center?

Follow the below steps to configure group policies in the Teams admin center where it majorly supports Teams calling policy, Teams call park policy, Teams policy, Teams live events policy, Teams meeting policy, and Teams messaging policy.

  • Navigate using the path below.

Microsoft Teams admin center 🡢 Messaging Policies (Select the desired policy type page) 🡢 Group policy assignment 🡢 Add group 🡢 Assign policy to group

Group Policy Assignments in the Teams admin center

2. Then, select a group to which you want to assign a policy. 3. Set the ranking value for the group policy assignment through the select rank option. 4. After that, select a policy from the available policy types in the drop-down list and click Apply .

Unfortunately, all policy types can’t be managed under the Microsoft Teams admin center since it supports only certain policy types. Without a second thought, PowerShell is the go-to solution! Yes, managing policies using PowerShell is easy and efficient as it is the primary automation tool that ensures the deployment of objects in multiple tenants. Also, it is a place where error handling and logging are more flexible compared to the native admin center. Thus, let us deeply look through the next section of the blog to manage group policy assignments using Microsoft Teams PowerShell.

Manage Group Policy Assignments Using Teams PowerShell Module

As per the new update, Teams PowerShell Module now helps to manage group policies of Microsoft 365 groups, mail-enabled security groups, distribution lists, and security groups including Teams-related policies. Thus, create & manage groups in Microsoft 365 admin center and manage their policies in Teams PowerShell. Before getting started with PowerShell cmdlets, make sure to connect to the Teams PowerShell Module .

Assign Policy to Group Using Teams PowerShell Module

Get group policy assignments using ms teams powershell, remove policy assignment from a group using tpm, modify group policy assignment using teams powershell module.

By defining group policies, you can control user-specific actions like allowing them to schedule meetings, edit sent messages, etc. You can assign the available policies or create and assign custom policies depending on your requirements. Execute the following cmdlet after replacing the unique group identifier, policy type, policy name, and expected rank to assign a new policy for a group.

This “New-CsGroupPolicyAssignment” cmdlet is basically used to create new policy assignments for security groups and distribution lists. In which the group ID, policy type, policy name, and rank must be mentioned as mandatory parameters. Here with the rank value as one, the ‘AllOn’ policy under TeamsMeetingPolicy type is created for the given group.

The rank of the policy must be defined to determine the precedence. The recommended group membership size is 50,000 users per group while assigning a group policy. Also, it takes 24 hours or more to propagate the policy to all members of the larger groups.

Knowing all the available policy assignments allows you to understand the working conditions and their precedence levels better. Using this you can remove unnecessary policies, alter the desired ranking for policies and efficiently manage teams & groups around your Office environment.

The “Get-CsGroupPolicyAssignment” cmdlet primarily returns all the group policy assignments with some optional parameters to filter the results.

  • Primarily, list all the policy-assigned groups by running the following command.

Group Policy Assignments Using Microsoft Teams PowerShell

2. However, you can also retrieve all the policies assigned to a particular group using the below cmdlet.

Here the cmdlet is mentioned with group ID so that retrieving only the policy assignments of that particular group.

3.Also, you can list the groups based on their policy type by executing the below command.

In this case, the policy type is mentioned as TeamsMeetingPolicy. Hence this cmdlet returns only the groups assigned with this policy.

Get Group Policy Assignments Using Microsoft Teams PowerShell Module

Remove the unnecessary policies found in your organization that are interrupting the ranking and slowing down the work progress. Most importantly, the removal of policies will update the ranking value of the same type policies where the policies in the list will be ranked consecutively after the removal.

Run the following cmdlet to remove a specific group policy assignment in Microsoft 365 environment.

The ” Remove-CsGroupPolicyAssignment” cmdlet removes the given policy type in mentioned group ID.

Remove Group Policy Assignment Using Teams PowerShell Module

Directly altering the policy assignment ranking value is not possible in the Teams admin center. The policy assignments should be removed and newly assigned again with a new rank value to change the ranking. To take away this hassle, PowerShell lends you a hand with a simple and reusable cmdlet which is described below.

The “Set-CsGroupPolicyAssignment” cmdlet can be used to make the following alterations in group policy assignments based on the given attributes.

  • Change policy assignment ranking.
  • Change the policy under the existing policy type.
  • Change policy assignment ranking value and policy of a given policy type.

In this example, the policy is changed to ‘SupportCallPark’ policy, and the rank value is assigned to 3.

NOTE: The “Set-CsGroupPolicyAssignment” cmdlet is currently not released for use. So, for now, you need to remove policies and add new policies to change the policy or ranking. But you can easily alter the policy settings once after the availability of this cmdlet.

New Group Policy Assignment Support in Teams PowerShell Module

Microsoft rolls out group policy assignment support for additional policies in Teams PowerShell Module as a new update. So that admins can manage their groups in the M365 admin center and group policies in Teams PowerShell with a breeze. This feature will allow you to configure custom policies to groups for all Microsoft commercial licenses. With this update, dependency on global or direct policy assignments through manual methods is eliminated. In addition to the core policies such as meeting policies, calling policies, and messaging policies, the following policies are now expected to be available in Teams PowerShell by late May 2023 .

  • Application Access Policy
  • Call Hold Policy
  • Carrier Emergency Call Routing Policy
  • Cortana Policy
  • Dial Out Policy
  • Education Assignments App Policy
  • Emergency Calling Policy
  • Enhanced Encryption Policy
  • Events Policy
  • External Access Policy
  • Feedback Policy
  • Files Policy
  • IPPhone Policy
  • Media Logging Policy
  • Meeting Branding Policy
  • Meeting Template Permission Policy
  • Mobility Policy
  • Notification And Feeds Policy
  • Room Video Tele Conferencing Policy
  • Synthetic Automated Call Policy
  • Teams Branch Survivability Policy
  • Template Permission Policy
  • Video Interop Service Policy
  • Voice Routing Policy
  • Voicemail Policy

In conclusion, ultimately manage all group policies including Teams using PowerShell cmdlets. Take charge of the user-specific actions and security controls through this group policy assignment. Not only policies, you can also manage your Teams using PowerShell for effective administration. Rather than performing numerous repetitive tasks in the Teams admin center, automate them with just a few cmdlets in PowerShell.

I hope that this blog provides you with deeper insights into group policy assignments using Teams PowerShell. For any clarifications feel free to reach us through comments.

Related Posts:

Manage Microsoft Teams Users - PowerShell

Regain Control of Azure Resources with Azure Policy

Published: 3 August 2019 - 6 min. read

  • Microsoft Azure

Adam Bertram Image

Adam Bertram

Read more tutorials by Adam Bertram!

Table of Contents

A common theme in cloud environments today is the ability to define templates, policies, and procedures. These templates then dictate what can be done and verify that what does exist is correct. A service from Microsoft called Azure Policy is a great way to make that happen.

In this article, you will learn how Azure Policy works and then see how to create various policies and remediate actions.

Creating an Azure Policy

There are many ways to create policies such as via the Azure Portal Portal, PowerShell, Azure CLI and ARM templates.

Azure Portal

If you prefer the GUI route or are exploring your options, starting here is a good introduction into policies. The interface is simple and allows you to see what your options are at a glance.

  • Within the Azure Portal , s earch for Policy .
  • Click on Assignments under the Authoring section
  • Click on Assign policy
  • Click on the ellipsis under Scope to select the subscription to apply to and optionally the resource group
  • Click on the ellipsis under Policy definition to select the policy to define
  • Either use the default generated name under Assignment n ame or enter one to uniquely identify your policy
  • Fill out any parameters as necessary based on the policy chosen
  • Finally create a managed identity a nd define its location if necessary

Creating a Policy

Thankfully PowerShell makes it quick and easy to assign an Azure policy definition to a policy assignment. There are two prerequisites, which is needing the latest version of Azure PowerShell installed and registering the Azure Policy Insights resource provider.

If PowerShell isn’t available or not preferred, then using the Azure CLI also allows you to accomplish much of the same. This can also be helpful in cross-platform scenarios if you are unable to use PowerShell on all operating systems.

Azure Policy Templates

Azure Resource Manager templates are yet another way to create and assign policies to resources. Below is a starter template that you can use to choose a policy to assign to a resource group as an example.

How Azure Policy Assignment Works

After choosing or creating the policy definitions that you want to apply, assign those definitions to affect a specific scope. The scope merely defines what the policy assignment is going to apply to, such as a management or resource group. Something to note is that policy assignment are inherited by all child resources, but you do have the ability to exclude a sub-scope if required.

Example Azure Policies

There are a lot of policy definitions out there and it can be hard to decide what is best to apply. So what are some of the options, when might you use them and why?

  • Require Tag and its Value – This can be used for any number of ways, but one possibility is for say cost codes, or for identifying a number of different resources spread across multiple resource groups.
  • Allowed Resource Types – What if you only want to allow specific resources? This can enforce that, with say just the ability to create a storage resource.
  • Audit Windows VMs with a Pending Reboot – Perhaps you want to know what Windows VMs require a pending reboot, to make sure those don’t get left behind? Use this policy to find and possibly remediate those on a schedule.
  • Audit Diagnostic Setting – If diagnostic settings are not enabled then this policy will find those that are non-compliant.
  • Management Ports Should be Closed on your Virtual Machines – Verify that the management ports on your VMs are closed, a great policy for the security-minded.
  • Deprecated Accounts Should be Removed from your Subscription – For all accounts that have been blocked from sign-in within a directory, find those to potentially remediate as necessary. Although there are many here, and even more being created every day, you also have a very powerful ability to create your own custom policy definitions. Using a simple query definition schema you can create powerful if-then constructions to define what you want to apply policies to.

How to Make Azure Policies more Reusable

One of the most useful tools are defining parameters for use in your policies. If you had to define a unique policy for each and every variation in a policy, you may end up with hundreds. A great solution to this is to parameterize a policy. With this you can customize the policy at the time of assignment and make one policy definition apply to many different use cases.

Initiatives

The next logical step is to collect multiple definitions together in a set. This allows you to assign all those different definitions to a scope without having to individually assign each one over and over.

Initiative Parameters

Finally, you can add parameters to initiatives that can be inherited down to the individual policies. This means that you don’t have to individually assign parameters for each policy contained within an initiative. This can save a ton of time as you can define only a few initiatives that apply many different policies in several different ways depending on the parameters chosen.

Remediation Tasks

So what do you do when you have a policy that evaluates but finds resources out of compliance? At that point, you can launch a remediation task to fix whatever the issue might be. This can be quite powerful but also quite dangerous if setup incorrectly. Once again there are several ways to define these tasks either through the Azure Portal, PowerShell or through the Azure CLI.

As before you can use the Azure Portal to explore the creation of a remediation task. If you find that there are no policies listed, make sure you have both deployIfNotExists policies and also those that have evaluated to non-compliant otherwise they will not show.

  • Within the Azure Portal, search for Policy
  • Click on Remediation on the left-hand side
  • Click on a policy that is of the type of deployIfNotExists an d has non-compliant resources
  • Filter the resources to be re-mediated on the New remediation task page to limit what the task applies to
  • Click on Remediate to start the task itself

It is quite simple to create a remediation task via PowerShell. The main thing to remember is that you must be using a deployIfNotExists policy.

In lieu of using PowerShell you can also use the Azure CLI to start a remediation task as well. The same goes for this as the PowerShell task.

The power in using Azure Policies is that for any Azure subscription you can define any number of flexible policies to help you manage your environment. Furthermore, with time, effort and thought put into how you structure your policies, initiatives and parameters you can create a well-defined and easy to remediate setup.

Considering that Azure Policies are free for any Azure Subscription, it makes a lot of sense to take the time to implement what you need. Considering the flexibility in how to create and deploy these definitions and policies, it can apply to nearly anything and help you keep a handle on your environment!

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

More from ATA Learning & Partners

Recommended Resources!

Recommended Resources!

Recommended Resources for Training, Information Security, Automation, and more!

Get Paid to Write!

Get Paid to Write!

ATA Learning is always seeking instructors of all experience levels. Regardless if you’re a junior admin or system architect, you have something to share. Why not write on a platform with an existing audience and share your knowledge with the world?

ATA Learning Guidebooks

ATA Learning Guidebooks

ATA Learning is known for its high-quality written tutorials in the form of blog posts. Support ATA Learning with ATA Guidebook PDF eBooks available offline and with no ads!

Looks like you're offline!

John Folberth

Resources and posts for those figuring out DevOps in Azure

  • Professional

Testing Azure Policy via PowerShell

powershell_azure_policy

Azure Policy is a powerful tool that can be used as effective guardrails to safeguard an environment. In addition it can be leverage to auto remediate anything required a developer may forget about. For some examples on Azure Policy check out my posts “ Creating and Deploying Azure Policy via Terraform ” or “Dynamically Adding Terraform Policy Assignments…Reusing Infrastructure as code “. Specifically, this post is related to “ Terraform, Azure Policy, and Datas OH MY! “

Problem Statement

In a nutshell this policy ensures Azure Resource Groups require a delete-by tag and this delete-by tag must be within a certain date range. The follow up to this is a PowerShell script hooked up to an Azure Automation account which will delete resource groups who have past expiration. The dilemma is how can we seed test data to validate the script when Azure Policy will deny it? We could just delete the policy assignment do our testing and re assign it; however, that is a manual process and leaves open the room for error that the policy is never assigned. So that leaves us with the problem statement: How to seed test data that violates a policy?

Requirements

To run this the following Az Modules will need to be installed:

  • Az.Resources

Breaking down this problem we can outline the steps we should take:

Remove the Policy Assignment

  • Create the Resources that would violate the policy
  • Re add the Policy Assignment

To do this successfully we should read in the existing policy assignment and store that information in our script so we reapply the policy with the same information that was originally available.

Store Policy Assignment Information

To store the policy assignment information, we will use the Get-AzPolicyAssignment PowerShell module:

The $PolicyParameterObject is a hashtable of parameters the Policy Assignment expects.

Can see we look up the Policy Assignment by name and store that as well as the Policy Definition ID as this will be used later.

Removing the Policy Assignment is quite easily actually. We just use the Remove-AzPolicyAssignment command.

Create the Resources that Violate the Policy

For this specific example the resources being created will be Resource Groups who have a delete-by tag value which is in the past. To accomplish this and provide a more realistic scenario the Get-Random command will be used.

The random number will be different for each resource group being created and will be used with the .addDays() function to subtract days from the $dateRan which is the starting point.

Re Add the Policy Assignment

Lastly, we need to re add the policy assignment to ensure this doesn’t drift.

This is being done with the New-AzPolicyAssignmnt function and passing in the assignment parameters as a hash table and the necessary information which was scraped from the original Policy Assignment that was saved off.

Sometimes when testing automation or the cleaning up of resources automatically it is important to create an automated way to seed test data. This will help improve consistency and help minimize the potential for human error.

Source Code

Leave a reply cancel reply.

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Assigning the Policy Set(Azure Initiative) using Powershell

I am able to assign an Azure policy using the command New-AzPolicyAssignment . Below is the document which has information about this.

https://learn.microsoft.com/en-us/powershell/module/az.resources/new-azpolicysetdefinition?view=azps-2.1.0

But I want to assign a policy set, how can I assign a policy set using Powershell?

  • azure-policy

Maytham Fahmi's user avatar

2 Answers 2

I found the answer to this:

You can find the Policy set GUID by just running the Get-AzPolicySetDefinition , this will pull all the policy sets for your subscription

  • Small correction. Get-AzPolicySetDefinition expects string as a name param, not GUID. So it should be -Name "PolicySetDefinitionID" instead –  Hardoman Commented Jan 26, 2022 at 16:52
  • @avinash, just mark your answer as answered. –  Maytham Fahmi Commented Sep 27, 2022 at 8:56
  • In my case the policies were part ARM template. So I used New-AzDeployment -Name "XYZ" -TemplateFile "arm.json" –  RSW Commented Aug 28, 2023 at 8:02

To complete your answer, this is an example of how you assign an initiative with New-AzPolicyAssignment :

Abderrahmane Mechri's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged azure powershell azure-policy or ask your own question .

  • The Overflow Blog
  • From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • What can I do when someone else is literally duplicating my PhD work?
  • add images in \longtable and remove justification
  • What is the name of the book about a boy dressed in layers of clothes who is actually a mouse?
  • My school wants me to download an SSL certificate to connect to WiFi. Can I just avoid doing anything private while on the WiFi?
  • How much missing data is too much (part 2)? statistical power, effective sample size
  • Are quantum states like the W, Bell, GHZ, and Dicke state actually used in quantum computing research?
  • Routing radiused edges between nodes in TikZ
  • Flight left while checked in passenger queued for boarding
  • When was this photo taken?
  • Power latching circuit MOSFET is stuck ON
  • What happens when a helicopter loses the engine and autorotation is not initiated?
  • Deviation from the optimal solution for Solomon instances of CVRPTW
  • Can you find what these letters might be?
  • What is it called when perception of a thing is replaced by an pre-existing abstraction of that thing?
  • Are there different conventions for 'rounding to even'?
  • Experience related to The GA4
  • Inconsistent “unzip -l … | grep -q …” results with pipefail
  • Why are most big lakes in North America aligned?
  • How are notes named in Japan?
  • ApiVersion 61.0 changes behaviour of inheritance (cannot override private methods in inner class)
  • How do I safely remove a mystery cast iron pipe in my basement?
  • Using "no" at the end of a statement instead of "isn't it"?
  • Submitting a paper as a nonacademic practitioner in a field
  • Origin of the phrase "I'm on it"

get policy assignment powershell

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Get-Execution Policy

Gets the execution policies for the current session.

Description

To display the execution policies for each scope in the order of precedence, use Get-ExecutionPolicy -List . To see the effective execution policy for your PowerShell session use Get-ExecutionPolicy with no parameters.

The effective execution policy is determined by execution policies that are set by Set-ExecutionPolicy and Group Policy settings.

For more information, see about_Execution_Policies .

Example 1: Get all execution policies

This command displays the execution policies for each scope in the order of precedence.

The Get-ExecutionPolicy cmdlet uses the List parameter to display each scope's execution policy.

Example 2: Set an execution policy

This example shows how to set an execution policy for the local computer.

The Set-ExecutionPolicy cmdlet uses the ExecutionPolicy parameter to specify the RemoteSigned policy. The Scope parameter specifies the default scope value, LocalMachine . To view the execution policy settings, use the Get-ExecutionPolicy cmdlet with the List parameter.

Example 3: Get the effective execution policy

This example shows how to display the effective execution policy for a PowerShell session.

The Get-ExecutionPolicy cmdlet uses the List parameter to display each scope's execution policy. The Get-ExecutionPolicy cmdlet is run without a parameter to display the effective execution policy, AllSigned .

Example 4: Unblock a script to run it without changing the execution policy

This example shows how the RemoteSigned execution policy prevents you from running unsigned scripts.

A best practice is to read the script's code and verify it's safe before using the Unblock-File cmdlet. The Unblock-File cmdlet unblocks scripts so they can run, but doesn't change the execution policy.

The Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the RemoteSigned policy. The policy is set for the default scope, LocalMachine .

The Get-ExecutionPolicy cmdlet shows that RemoteSigned is the effective execution policy for the current PowerShell session.

The Start-ActivityTracker.ps1 script is executed from the current directory. The script is blocked by RemoteSigned because the script isn't digitally signed.

For this example, the script's code was reviewed and verified as safe to run. The Unblock-File cmdlet uses the Path parameter to unblock the script.

To verify that Unblock-File didn't change the execution policy, Get-ExecutionPolicy displays the effective execution policy, RemoteSigned .

The script, Start-ActivityTracker.ps1 is executed from the current directory. The script begins to run because it was unblocked by the Unblock-File cmdlet.

Gets all execution policy values for the session. By default, Get-ExecutionPolicy gets only the effective execution policy.

Type:
Position:Named
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

Specifies the scope that is affected by an execution policy.

The effective execution policy is determined by the order of precedence as follows:

  • MachinePolicy . Set by a Group Policy for all users of the computer.
  • UserPolicy . Set by a Group Policy for the current user of the computer.
  • Process . Affects only the current PowerShell session.
  • LocalMachine . Default scope that affects all users of the computer.
  • CurrentUser . Affects only the current user.
Type:
Accepted values:CurrentUser, LocalMachine, MachinePolicy, Process, UserPolicy
Position:0
Default value:Effective execution policy
Required:False
Accept pipeline input:True
Accept wildcard characters:False

You can't pipe objects to this cmdlet.

ExecutionPolicy

The cmdlet always returns Unrestricted on Linux and macOS platforms. On Windows platforms it returns the current execution policy.

An execution policy is part of the PowerShell security strategy. Execution policies determine whether you can load configuration files, such as your PowerShell profile, or run scripts. And, whether scripts must be digitally signed before they are run.

Related Links

  • about_Execution_Policies
  • about_Group_Policy_Settings
  • Get-AuthenticodeSignature
  • Set-AuthenticodeSignature
  • Set-ExecutionPolicy

Additional resources

COMMENTS

  1. Get-AzPolicyAssignment (Az.Resources)

    The Get-AzPolicyAssignment cmdlet gets all policy assignments or particular assignments. Identify a policy assignment to get by name and scope or by ID.

  2. Get-CsUserPolicyAssignment (MicrosoftTeamsPowerShell)

    The user has inherited the "AllOn" policy because the priority of the assignment is higher than that of the "Kiosk" policy assignment to the other group. PowerShell. Copy. Get-CsUserPolicyAssignment -Identity 3b90faad-9056-49ff-8357-0b53b1d45d39 -PolicyType TeamsMeetingPolicy | select -ExpandProperty PolicySource.

  3. Get list of all azure policy assignment using powershell

    I'm trying to get the list of all policy assignments created in azure using the below commands. However when I scope the assignment to the resource group, below command does not return that assignm...

  4. Quickstart: Create policy assignment using Azure PowerShell

    In this quickstart, you create an Azure Policy assignment to identify non-compliant resources using Azure PowerShell.

  5. Use PowerShell to retrieve all assigned Intune policies and

    Use PowerShell to retrieve all assigned Intune policies and applications per Azure AD group!

  6. Get-AzPolicyAssignment

    Below PowerShell command can help you to retrieve the lists of policy assignments. Get-AzPolicyAssignment. After running the above command, I got the below output. PS C:\WINDOWS\system32> Get-AzPolicyAssignment. Identity : Location : Name : SecurityCenterBuiltIn.

  7. Manage Azure Policy using PowerShell

    In this post, we will look at how to manage Azure Policy using PowerShell for common tasks, including creating policy definitions, managing policy assignments, and reporting compliance status.

  8. How to Get All Azure Policy Assignments of a Specific Category?

    If any of the assigned policies belong to the requested category, like Guest Configuration in my case, information about those policies will be provided as output upon script execution. You can find the PowerShell script in my GitHub repo: Get-Policy-Assignments-In-Category.ps1.

  9. Powershell script to find out Teams policies by users

    Powershell script to find out Teams policies by users Hey everyone, do you know if there is a way to run a script to find what Teams policies are assigned to what user? We have a private channel policy in place- I would like to find out a list of users that policy is assigned to.

  10. Get all assigned Intune policies and apps per Azure AD group

    So for example, Device Configuration policies and Administrative templates are different and when we use the Intune Powershell SDK and the Get-IntuneDeviceConfigurationPolicy we won't get any Administrative templates or powershell scripts.

  11. Use PowerShell to Create a Report About the Teams Policies Assigned to

    PowerShell makes it easy to create a report about the Microsoft Teams policy assignments for user accounts. In this article, we explain how to extract policy information and generate a HTML report.

  12. Group Policy Assignments Using Microsoft Teams PowerShell

    According to this latest update, group policy assignments for Microsoft 365 groups, distribution lists, mail-enabled security groups, and security groups support additional policies in the Teams PowerShell Module. Apart from action control, policy assignments also set way for security controls like restricting anonymous access in meetings.

  13. Get-RoleAssignmentPolicy (ExchangePowerShell)

    Use the Get-RoleAssignmentPolicy cmdlet to view existing management role assignment policies in your organization. For information about the parameter sets in the Syntax section below, see Exchange cmdlet syntax.

  14. Regain Control of Azure Resources with Azure Policy

    PowerShell Thankfully PowerShell makes it quick and easy to assign an Azure policy definition to a policy assignment. There are two prerequisites, which is needing the latest version of Azure PowerShell installed and registering the Azure Policy Insights resource provider.

  15. Need PowerShell command to get role assignment policy for all mailboxes

    I need to know what role assignment policy is assigned to all our mailboxes in Office 365. Also, how would one change the role assignment policy in bulk for multiple mailboxes? The Get-RoleAssignmentPolicy cmdlet lists the policies but I cannot find a way to identify which mailboxes it's applied to. And the Set-RoleAssignmentPolicy sets the default policy for new mailboxes but how do you ...

  16. Testing Azure Policy via PowerShell

    Testing Azure Policy via PowerShell. Azure Policy is a powerful tool that can be used as effective guardrails to safeguard an environment. In addition it can be leverage to auto remediate anything required a developer may forget about. For some examples on Azure Policy check out my posts " Creating and Deploying Azure Policy via Terraform ...

  17. Assigning the Policy Set (Azure Initiative) using Powershell

    But I want to assign a policy set, how can I assign a policy set using Powershell?

  18. Assign policies to users and groups

    Use PowerShell Each policy type has its own set of cmdlets for managing it. Use the Grant- cmdlet for a given policy type to assign the policy. For example, use the Grant-CsTeamsMeetingPolicy cmdlet to assign a Teams meeting policy to users. These cmdlets are included in the Teams PowerShell module and are documented in the Skype for Business cmdlet reference.

  19. Get-ExecutionPolicy (Microsoft.PowerShell.Security)

    To display the execution policies for each scope in the order of precedence, use Get-ExecutionPolicy -List. To see the effective execution policy for your PowerShell session use Get-ExecutionPolicy with no parameters. The effective execution policy is determined by execution policies that are set by Set-ExecutionPolicy and Group Policy settings. For more information, see about_Execution_Policies.