Archive | PowerShell RSS feed for this section

Windows 365 Local Admin – Cloud PC Configurations vs User Settings + PowerShell (Graph REST API)

8 Oct

Granting a user local administrator rights on their Windows 365 Cloud PC used to have exactly one home: User settings. That has now changed. The same capability is available in the newer Cloud PC configurations policy type under Cloud PC Settings, and Microsoft recommends using it for all new local-admin assignments.

Both options produce the same end result – the targeted user becomes a member of the local Administrators group on their own Cloud PC. The differences are in the policy framework: how conflicts are resolved, how settings are expressed, and which one Microsoft is investing in going forward.

Naturally, instead of only clicking through the Intune portal, I wanted to see what the portal actually sends to Microsoft Graph when you create one of these policies – and then reproduce it with PowerShell. So I captured a HAR trace while creating the policy and worked backwards from there.

In this post I’ll cover:

  • Why there are now two places to enable local admin
  • A few important things to understand
  • Cloud PC configurations vs User settings
  • What the Intune portal actually sends to Graph (HAR capture)
  • Creating the Cloud PC configuration with PowerShell
  • Validating the policy – and the overlap I found
  • Migrating existing User settings policies

Why are there two places to enable local admin?

Windows 365 has been moving settings that can change after provisioning into the new Cloud PC Settings model. Cloud PC configurations is one template inside that model, alongside capabilities such as AI-enabled Cloud PCs and business continuity / disaster recovery controls.

Local admin is the setting that overlaps both worlds:

  • User settings (legacy) – a checkbox, Enable local admin, sitting next to user reset, user-initiated restore and cross-region disaster recovery.
  • Cloud PC configurations (new) – a setting called Enable local admin with the values Enabled, Disabled or Not configured.

Existing User settings policies keep working for now, but support for managing local admin through User settings is being phased out. The User settings object itself isn’t going away – it still owns user reset, restore and other user-facing controls.

My mental model: Cloud PC configurations replaces User settings only for the overlapping local-admin capability. It does not make the entire User settings object obsolete.

A few important things to understand

There are several caveats worth highlighting before anyone starts moving local-admin assignments around.

1. User settings is legacy for local admin

Microsoft explicitly recommends Cloud PC configurations for new local-admin assignments and advises migrating existing ones. Nothing breaks today, but I would not build anything new on the User settings checkbox.

2. Disabled is not the same as Not configured

This is the one that will catch people out.

  • Enabled – Windows 365 grants the targeted user local-admin rights.
  • Disabled – the policy explicitly requires local admin to be off.
  • Not configured – the policy doesn’t manage the setting and doesn’t take part in conflict resolution for it.

If you build a Cloud PC configuration purely for another feature (AI-enabled Cloud PCs, for example), leave local admin as Not configured. Set it to Disabled and that policy can now compete with the one that intentionally enables local admin.

Rule of thumb: only touch the settings you mean to manage. Everything else stays Not configured.

3. Conflict resolution works differently

  • Cloud PC configurations use a global policy rank. Rank 1 has the highest priority and you can rerank policies. Conflicts are evaluated per configured setting.
  • User settings use the older rule – the most recently created policy wins, regardless of which was most recently updated. The other policies are ignored.

4. Both are user-scoped, not device-scoped

Although the permission lands on a Cloud PC, both policies are assigned to user groups. The targeted user becomes admin only on the Cloud PCs assigned to them – not on every Cloud PC in the tenant.

5. Changes apply at sign-in

A user who is already signed in must sign out and sign back in to see the change. Keep that in mind when you validate.

6. This is not just-in-time elevation

Neither method gives task-specific or time-bound elevation. It is persistent local Administrators membership for as long as the policy applies. Use a dedicated group, keep membership to approved exceptions, and consider whether app packaging or endpoint privilege management could meet the need instead.

Cloud PC configurations vs User settings

AreaCloud PC configurationsUser settings
Local-admin resultUser becomes local admin on their own Cloud PCSame
Recommended for new deploymentsYesNo – legacy for local admin
LifecycleCurrent, strategic policy modelSupported for now; local-admin support being phased out
Setting valuesEnabled / Disabled / Not configuredCheckbox
Conflict handlingPolicy rank (1 = highest), rerankableMost recently created policy wins
GranularityPer configured setting; Not configured doesn’t participateWinning policy used, others ignored
Other capabilitiesAI-enabled features, BCDR controlsUser reset, user-initiated restore, cross-region DR
Assignment targetUser groupsUser groups
Scope tagsSupported in the create workflowNot shown in the create workflow
Graph endpoint (beta)virtualEndpoint/settingProfilesvirtualEndpoint/userSettings
Note–Doesn’t apply to Windows 365 Flex Cloud PCs in Shared mode

For most organisations I suspect the end state will be:

Local admin → Cloud PC configurations. Reset, restore and DR → User settings.

What the Intune portal actually sends to Graph

In the Intune admin center I went to:

Devices → Windows 365 → Settings → Create → Cloud PC configurations

Then I set Enable local admin = Enabled, assigned my test user group, left the default scope tag and clicked Create – with the browser developer tools recording a HAR file.

Three Graph calls tell the whole story.

Call 1 – Creating the policy (POST)

POST https://graph.microsoft.com/beta/deviceManagement/virtualEndpoint/settingProfiles

The request body (group ID replaced with a placeholder):

{
"displayName": "EnableLocal-Admin-01",
"description": "The new Cloud PC Config to enable local admin",
"profileType": "template",
"templateId": "W365.CloudPCConfiguration",
"settings": [
{
"@odata.type": "#microsoft.graph.cloudPcBooleanSetting",
"dataType": "boolean",
"settingDefinitionId": "W365.CloudPCConfiguration.LocalAdmin.IsEnabled",
"platform": "all",
"isEnabled": true
}
],
"assignments": [
{ "groupId": "<your-group-object-id>", "assignType": "group" }
],
"roleScopeTagIds": [ "0" ]
}

A few things stood out:

  • templateId = W365.CloudPCConfiguration – this is what makes the profile a Cloud PC configuration rather than another Cloud PC Settings template.
  • Only one setting is sent. The portal doesn’t send local admin as Not configured for anything else – unconfigured settings are simply absent from the settings array.
  • settingDefinitionId = W365.CloudPCConfiguration.LocalAdmin.IsEnabled with a cloudPcBooleanSetting. Setting isEnabled to false is how you would express Disabled.
  • Assignments are inline. Unlike provisioning policies, where I used a separate /assign call, the group assignment goes straight into the create body.
  • roleScopeTagIds – "0" is the built-in Default scope tag.

Graph returned 200 OK in under 400 ms.

Call 2 – Reading the legacy User settings (GET)

The same page also loads the legacy policies:

GET https://graph.microsoft.com/beta/deviceManagement/virtualEndpoint/userSettings?$expand=assignments

This returned my existing CPC-PowerUsers policy with "localAdminEnabled": true, assigned to three groups.

The response headers are also telling. Graph returned Deprecation and Sunset headers plus Link headers pointing to change-log entries for properties on this resource – including selfServiceEnabled, crossRegionDisasterRecoveryEnabled, frequencyInHours and notificationSetting. These relate to individual properties rather than the whole endpoint, but they are a clear signal that the userSettings object keeps evolving underneath you.

Beta caveat: everything here is on the Graph beta endpoint and was captured from the portal. Beta APIs can change and shouldn’t be treated as production-stable.

Creating the Cloud PC configuration with PowerShell

With the request body from the HAR trace, reproducing it in PowerShell is straightforward. I didn’t want a script that simply fires a POST, though. Before creating anything it:

  • lists the existing Cloud PC configurations with their rank
  • lists any legacy User settings policies that still have local admin enabled
  • warns if the target group is already covered by one of those legacy policies
  • creates the Cloud PC configuration with the group assigned inline
  • reads the policy back from Graph to confirm it landed

My policy is called:

W365-CPC-LocalAdmin

and the key setting is:

settingDefinitionId : W365.CloudPCConfiguration.LocalAdmin.IsEnabled
isEnabled : true

PowerShell Script

Link GitHub – avdwin365mem/CloudPC-Config-LocalAdmin.ps1 at main · askaresh/avdwin365mem

CloudPC-Config-LocalAdmin.ps1
#############################################################################################
# Windows 365 - Enable Local Admin via Cloud PC Configurations (Cloud PC Settings)
# PowerShell + Microsoft Graph REST API (beta)
#
# - Inventories existing Cloud PC configurations (with policy rank)
# - Inventories legacy User settings policies that still grant local admin
# - Warns if the target group is already covered by a legacy local-admin policy
# - Creates a Cloud PC configuration with "Enable local admin = Enabled" and assigns it
#
# Request body shape was captured from the Intune admin center (HAR trace).
# Only requires the Microsoft.Graph.Authentication module - all work is done with raw
# Graph calls so the heavier SDK sub-modules are never loaded.
#############################################################################################
$ErrorActionPreference = "Stop"
#---------------------------------------------------------------------------------------------
# STEP 0 - Module + Authentication
#---------------------------------------------------------------------------------------------
# Install once if needed:
# Install-Module Microsoft.Graph.Authentication -Scope CurrentUser -Force
Import-Module Microsoft.Graph.Authentication
# Set your tenant explicitly - avoids home-tenant guessing and some consent failures
$TenantId = "dXXXXX-4XXX-4XXX-8XXX-fe7XXXXXXX"
Connect-MgGraph -TenantId $TenantId -Scopes "CloudPC.ReadWrite.All","Group.Read.All"
# Hard stop if we are not actually connected - prevents the rest of the script running blind
$ctx = Get-MgContext
if (-not $ctx) { throw "Not connected to Microsoft Graph. Resolve the sign-in error before continuing." }
Write-Host "Connected as $($ctx.Account) to tenant $($ctx.TenantId)" -ForegroundColor Cyan
$baseUri = "https://graph.microsoft.com/beta/deviceManagement/virtualEndpoint"
# Confirm you hold the Cloud PC RBAC permissions before you start
Invoke-MgGraphRequest -Method GET -OutputType PSObject -Uri "$baseUri/getEffectivePermissions"
#---------------------------------------------------------------------------------------------
# STEP 1 - Variables
#---------------------------------------------------------------------------------------------
$policyName = "W365-CPC-LocalAdmin-02"
$policyDescription = "Cloud PC configuration - enable local admin for approved users"
$groupName = "W365-CPC-Grp" # dedicated, tightly controlled group
$enableLocalAdmin = $true # $true = Enabled, $false = Disabled
# (Not configured = leave the setting out)
#---------------------------------------------------------------------------------------------
# STEP 2 - Discovery: existing Cloud PC configurations and their rank
#---------------------------------------------------------------------------------------------
# Same filter the Intune portal uses on the Cloud PC Settings page
$filter = "templateId in ('W365.CloudPCConfiguration','W365.WindowsApp','W365.RemoteConnectionExperience')"
$settingProfilesUri = "$baseUri/settingProfiles?`$filter=$([uri]::EscapeDataString($filter))"
$cpcConfigs = (Invoke-MgGraphRequest -Method GET -OutputType PSObject -Uri $settingProfilesUri).value |
Where-Object { $_.templateId -eq "W365.CloudPCConfiguration" }
Write-Host "`nExisting Cloud PC configurations (rank 1 = highest priority):" -ForegroundColor Cyan
$cpcConfigs |
Sort-Object { $_.priorityMetaData.priority } |
Format-Table @{n = "Rank"; e = { $_.priorityMetaData.priority } }, displayName, isAssigned, lastModifiedDateTime -AutoSize
if ($cpcConfigs.displayName -contains $policyName) {
throw "A Cloud PC configuration named '$policyName' already exists - stopping to avoid a duplicate."
}
#---------------------------------------------------------------------------------------------
# STEP 3 - Discovery: legacy User settings policies that still grant local admin
#---------------------------------------------------------------------------------------------
$userSettings = (Invoke-MgGraphRequest -Method GET -OutputType PSObject `
-Uri "$baseUri/userSettings?`$expand=assignments").value
$legacyLocalAdmin = $userSettings | Where-Object { $_.localAdminEnabled -eq $true }
Write-Host "`nLegacy User settings policies with local admin enabled:" -ForegroundColor Yellow
$legacyLocalAdmin | ForEach-Object {
[pscustomobject]@{
Policy = $_.displayName
Created = $_.createdDateTime
Groups = ($_.assignments.target.groupId -join ", ")
}
} | Format-Table -AutoSize -Wrap
#---------------------------------------------------------------------------------------------
# STEP 4 - Resolve the assignment group
#---------------------------------------------------------------------------------------------
$filterEnc = [uri]::EscapeDataString("displayName eq '$groupName'")
$group = (Invoke-MgGraphRequest -Method GET -OutputType PSObject `
-Uri "https://graph.microsoft.com/v1.0/groups?`$filter=$filterEnc&`$select=id,displayName,securityEnabled").value |
Select-Object -First 1
# Or hard-code the object ID instead:
# $group = Invoke-MgGraphRequest -Method GET -OutputType PSObject `
# -Uri "https://graph.microsoft.com/v1.0/groups/<group-object-id>?`$select=id,displayName,securityEnabled"
if (-not $group) { throw "Group '$groupName' not found in tenant $($ctx.TenantId)." }
if (-not $group.securityEnabled) { throw "Group '$($group.displayName)' is not security-enabled." }
Write-Host "`nAssignment target: $($group.displayName) [$($group.id)]" -ForegroundColor Cyan
# Overlap check - is this group already getting local admin from a legacy policy?
$overlap = $legacyLocalAdmin | Where-Object { $_.assignments.target.groupId -contains $group.id }
if ($overlap) {
Write-Warning ("Group '$($group.displayName)' is already assigned to legacy User settings " +
"policy '$($overlap.displayName -join "', '")' with local admin enabled. " +
"Plan to remove it from the legacy policy after validation.")
}
#---------------------------------------------------------------------------------------------
# STEP 5 - Build the Cloud PC configuration body (matches the Intune portal request)
#---------------------------------------------------------------------------------------------
$params = @{
displayName = $policyName
description = $policyDescription
profileType = "template"
templateId = "W365.CloudPCConfiguration"
# Only include the settings you intend to manage.
# Anything not in this array is "Not configured" and does not take part in conflicts.
settings = @(
@{
"@odata.type" = "#microsoft.graph.cloudPcBooleanSetting"
dataType = "boolean"
settingDefinitionId = "W365.CloudPCConfiguration.LocalAdmin.IsEnabled"
platform = "all"
isEnabled = $enableLocalAdmin
}
)
# Assignments go inline - no separate /assign call needed
assignments = @(
@{
groupId = $group.id
assignType = "group"
}
)
# "0" is the built-in Default scope tag
roleScopeTagIds = @("0")
}
#---------------------------------------------------------------------------------------------
# STEP 6 - Create the policy
#---------------------------------------------------------------------------------------------
$settingProfile = Invoke-MgGraphRequest -Method POST -OutputType PSObject `
-Uri "$baseUri/settingProfiles" `
-Body ($params | ConvertTo-Json -Depth 10) -ContentType "application/json"
#---------------------------------------------------------------------------------------------
# STEP 7 - Verify (read it back rather than trusting the POST)
#---------------------------------------------------------------------------------------------
# Use the ID from the POST response; if it isn't returned, look the policy up by name
if (-not $settingProfile.id) {
Start-Sleep -Seconds 3
$settingProfile = (Invoke-MgGraphRequest -Method GET -OutputType PSObject -Uri $settingProfilesUri).value |
Where-Object { $_.displayName -eq $policyName } | Select-Object -First 1
}
if (-not $settingProfile.id) { throw "Policy '$policyName' not returned by Graph - check the portal." }
Write-Host "`nCreated Cloud PC configuration: $policyName [$($settingProfile.id)]" -ForegroundColor Green
# Full read-back of the policy (settings, assignments, rank) as JSON
try {
Invoke-MgGraphRequest -Method GET -OutputType PSObject -Uri "$baseUri/settingProfiles/$($settingProfile.id)" |
ConvertTo-Json -Depth 10
}
catch {
Write-Warning "Read by ID failed ($($_.Exception.Message)) - showing the list entry instead."
$settingProfile | Select-Object id, displayName, templateId, isAssigned, roleScopeTagIds,
@{n = "Rank"; e = { $_.priorityMetaData.priority } }, lastModifiedDateTime | Format-List
}
Write-Host ("New policies are added at the bottom of the rank. Rerank in Intune if another " +
"Cloud PC configuration manages local admin.") -ForegroundColor Yellow
# Disconnect-MgGraph
#---------------------------------------------------------------------------------------------
# Troubleshooting
#---------------------------------------------------------------------------------------------
# AADSTS650051 on Connect-MgGraph: the Microsoft Graph Command Line Tools enterprise app
# can't be consented in this tenant as requested. Ask a Global Administrator to grant admin
# consent for CloudPC.ReadWrite.All and Group.Read.All, then sign in again.
#
# 403 on settingProfiles / userSettings: check the getEffectivePermissions output above -
# you need a Windows 365 Administrator (or equivalent Cloud PC RBAC) role.

Two small but important details in the body:

  • To express Disabled, set $enableLocalAdmin = $false. To express Not configured, don’t include the setting at all.
  • The script uses the same $filter as the portal. I deliberately kept it identical so the results match what you see in Intune.

Validating on the Cloud PC

After the user signs out and back in, confirm the membership on the Cloud PC itself:

Get-LocalGroupMember -Group "Administrators"

Migrating existing User settings policies

Existing User settings policies don’t need to be ripped out today. I would still plan the move in controlled waves rather than one big switch:

  1. Inventory all existing User settings policies (Step 3 of the script does this).
  2. Identify the groups where Enable local admin is selected.
  3. Check for overlapping group memberships across policies.
  4. Create the equivalent Cloud PC configuration policies.
  5. Assign them to a controlled pilot group first.
  6. Have pilot users sign out and sign back in.
  7. Verify local Administrators membership and effective access.
  8. Remove the group from the old User settings policy.
  9. Repeat by deployment wave.
  10. Delete the legacy local-admin User settings policy once nothing depends on it.

Careful with step 10: a User settings policy often carries more than local admin. My CPC-PowerUsers policy also controls user reset and restore points every 12 hours. Untick local admin rather than deleting the policy if those capabilities are still needed.

The standard I would put in place:

All new Windows 365 local-admin assignments use Cloud PC configurations. Existing User settings assignments are migrated in waves. User settings remains only for capabilities specific to it, such as reset and restore.

Final thoughts

On the surface this is a small change – one checkbox moving from one policy to another. Underneath, it is a good look at where Windows 365 policy management is heading:

User settings (legacy)
+
newest-created policy wins

to:

Cloud PC Settings templates
+
per-setting evaluation + explicit rank

The new model is clearly better – explicit ranking, Enabled / Disabled / Not configured, scope tags and inline assignments. The trade-off is that you now have to think about rank and the difference between Disabled and Not configured, and keep an eye out for the same users being targeted by both models during migration.

The HAR trace also hinted at more Cloud PC Settings templates (W365.WindowsApp and W365.RemoteConnectionExperience), so I suspect this model will keep absorbing more settings over time. Something I will keep an eye on.

Thanks,
Aresh Sarkari

Azure Virtual Desktop with Terraform – Pooled, Personal, RemoteApp + Monitoring, Dashboards and Scaling – All-in-one

16 Mar

During Workplace Ninja US, I did an in-person session on this topic, and now I am releasing for all. I’ve built Azure Virtual Desktop environments in a few different ways over the years — quick POCs, “just one host pool” builds, and full-blown enterprise deployments. The problem is the same every time: it starts simple and then you end up stitching together monitoring, scaling plans, RBAC, dashboards, and cost alerts… usually across multiple Terraform folders.

So I pulled everything into one modular Terraform repo that can deploy four AVD patterns (pooled/personal + desktop/RemoteApp), with optional enterprise-grade monitoring, dashboards, cost management, and scaling.

Repo – askaresh/avd_terraform: Azure Virtual Desktop and Terraform. Everything you need in a single repo!

What we are building

This repo deploys a complete AVD environment and supports four deployment types:

  • pooled_desktop (shared desktops)
  • personal_desktop (dedicated 1:1 desktops)
  • pooled_remoteapp (published apps, shared hosts)
  • personal_remoteapp (published apps, dedicated hosts)

It also follows Microsoft Cloud Adoption Framework (CAF) naming patterns for the main AVD + network resources (host pool, app group, workspace, vnet/subnet/nsg, etc.).

Why this repo is “enterprise ready”

A few highlights that make this more than a basic host pool deployment:

  • Scaling plans for pooled deployments (desktop + RemoteApp) and environment-specific schedules
  • Monitoring & observability using Log Analytics + diagnostics
  • Custom dashboards for operational visibility
  • Cost management with budgets + alerts
  • CAF-friendly naming so your portal stays clean and consistent

Supported deployment types (quick view)

The configuration automatically adjusts host pool/app group settings depending on deployment_type (pooled vs personal, desktop vs RemoteApp).

Deployment typeHost pool typeApp group typeNotes
pooled_desktopPooledDesktopScaling supported
personal_desktopPersonalDesktopStart VM on connect behavior differs
pooled_remoteappPooledRemoteAppScaling supported
personal_remoteappPersonalRemoteAppDedicated apps per user

Pre-requisites

  • Terraform + required providers (azurerm/azuread/random/azapi)
  • An Azure subscription with AVD enabled
  • Object IDs for users/groups/service principals that should be granted access (security_principal_object_ids)

Session host default image SKU in the repo is Windows 11 multi-session + M365 (win11-24h2-avd-m365).

Deployment steps (what I run)

Clone the repo

git clone https://github.com/askaresh/avd_terraform
cd avd_terraform

Pick a deployment file (.tfvars)

The repo includes pre-configured examples for different deployment types (dev/prod, pooled/personal, desktop/RemoteApp), plus enhanced options.

Examples:

  • dev-pooled-desktop.tfvars
  • dev-personal-desktop.tfvars
  • dev-pooled-remoteapp.tfvars
  • prod-personal-remoteapp.tfvars
  • dev-pooled-desktop-enhanced-scaling.tfvars

Update the must-have variables

At minimum, set:

  • security_principal_object_ids (who gets access)
  • admin_password (local admin password for session hosts)

RemoteApp tip: for RemoteApp deployment types, you’ll also define published_applications (apps to publish).

<!-- INSERT SCREENSHOT: tfvars edits (redact secrets) -->

Authentication (repo way: .env + set-auth.ps1)

The deployment guide uses a Service Principal stored in a local .env file (ignored by git), and a set-auth.ps1 script that loads the values into ARM_* environment variables for Terraform.

High level flow:
.env → set-auth.ps1 → ARM_* env vars → Terraform

Create your .env from .env.example, then run:

.\set-auth.ps1

Scaling plans note: your Service Principal needs the Desktop Virtualization Power On Off Contributor role at subscription scope for scaling to work properly.

Terraform init / plan / apply

terraform init
terraform plan -var-file=dev-pooled-desktop.tfvars
terraform apply -var-file=dev-pooled-desktop.tfvars

Monitoring, dashboards, cost alerts (optional but worth it)

If you use one of the monitoring/scaling-enabled tfvars options, the repo can deploy:

  • Log Analytics + diagnostics
  • Dashboards for ops visibility
  • Budgets/alerts for cost tracking

A quick note on dependency ordering (why it matters)

The repo is intentional about resource ordering — especially for scaling plans — to avoid portal oddities and ensure the host pool association is reliable. The dependency flow is documented and includes a separate scaling plan host pool association resource.

Resoure Group (RG)

Application Groups (AG)

Wrap up

If you want a repeatable way to deploy AVD that supports pooled + personal and desktop + RemoteApp, while also giving you the option to turn on monitoring, dashboards, budgets/alerts, and scaling, this repo is designed for exactly that.

Thanks,
Aresh Sarkari

Windows 365 Cloud Apps – Provisioning Policy – PowerShell (Graph Rest API) – Part 1

26 Sep

This is part one of a two-part series on Windows 365 Cloud Apps. In this post, we’ll walk through what Cloud Apps are and how to create the provisioning policy with PowerShell. In part two, we’ll publish the apps themselves. I’ll also include the PowerShell script that uses Azure/Graph REST APIs.

What is Windows 365 Cloud Apps?

Windows 365 Cloud Apps let you give users access to specific apps streamed from a Cloud PC—without handing out a full desktop to everyone. Under the hood, Cloud Apps run on Windows 365 Frontline Cloud PCs in Shared mode. That licensing model is designed for shift or part-time staff: many users can be assigned, but only one active session per license at a time.

Think of it as “just-the-apps” VDI: Outlook, Word, your line-of-business app—delivered from the cloud—with the management simplicity of Windows 365 and Intune.

Why customers care: You streamline app delivery, lower overhead, and modernize VDI without building and babysitting a big remote desktop estate.

Cloud Apps vs AVD Published Apps vs “Traditional” VDI Published Apps

TopicWindows 365 Cloud AppsAzure Virtual Desktop Published AppsTraditional VDI Published Apps
What users seeIndividual apps streamed from a Cloud PC; no full desktopIndividual apps from session hosts in Azure Virtual DesktopIndividual apps from on-prem or hosted RDS/Horizon/Citrix farms
Infra you manageCloud PC lifecycle via Intune; Microsoft operates the fabricYou design & operate host pools, scaling, FSLogix, imagesYou run the farm: brokers, gateways, hypervisors, storage
Licensing / sessionsFrontline: many users per license, 1 active session per licensePer-user/per-device or CALs + Azure consumption; multiple sessions per hostPer-user/device + on-prem infra costs
Admin planeIntune + Windows 365Azure Portal + ARM + Host pool automationVendor consoles + on-prem change management
App packagingStart-menu discovered apps from the image (MSIX/Appx discovery expanding)MSI/MSIX; MSIX App Attach; image-basedMSI/MST/App-V/Citrix packages, etc.
Who it’s great forTask/shift workers; predictable, lightweight app accessBroad use cases; granular scale & controlHeavily customized legacy estates, on-prem constraints

Mental model:

If you need elastic host pools or platform primitives, choose AVD.

  • If you’re tied to on-prem or specific vendor features, you might keep traditional VDI, but expect more ops work.
  • If you like the “managed Cloud PC” experience and want app-only access, choose Cloud Apps.
  • If you like the “managed Cloud PC” experience and want app-only access, choose Cloud Apps.

PowerShell: create the policy via REST/Graph

  • Auth: Provide $TenantId, $ClientId, $ClientSecret from your app registration. Grant/admin-consent the scopes listed above. If you are not aware of how to create the app registration, you can follow here – How to register an app in Microsoft Entra ID – Microsoft identity platform | Microsoft Learn
  • Image: Set $ImageType (e.g., "gallery") and $ImageId for your chosen image.
  • Region: $RegionName (e.g., australiaeast or "automatic").
  • Assignment:
    • $GroupId: Entra group whose members should see the Cloud Apps.
    • $ServicePlanId: the Frontline size (e.g., FL 2vCPU/8GB/128GB in the example).
    • $AllotmentCount: how many concurrent sessions you want available for this policy.
    • $AllotmentDisplayName: a friendly label that shows up with the assignment.
  • Verification/Polling: The script dumps the policy with assignments and can optionally poll for provisioned Cloud PCs tied to the policy.
  • Get-or-Create a Cloud Apps provisioning policy (userExperienceType = cloudApp, provisioningType = sharedByEntraGroup, Azure AD Join in a specified region).
  • Assigns the policy to an Entra group with service plan, capacity (allotment), and a friendly label

Required permissions (app registration – admin consent):

  • CloudPC.ReadWrite.All (and CloudPC.Read.All)
  • DeviceManagementServiceConfig.ReadWrite.All (for policy config)
<#
Create (or reuse) a Windows 365 "Cloud Apps" provisioning policy, assign an Entra group
with size + capacity + label, then verify assignment (via $expand=assignments) and optionally
poll for provisioned Cloud PCs. Uses Microsoft Graph beta.

Key note: /assignments endpoint returns 404 by design; use $expand=assignments. See MS docs.
#>

# ==========================
# 0) CONFIG — EDIT THESE
# ==========================
$TenantId     = "<Copy/Paste Tenant ID>"
$ClientId     = "<Copy/Paste Client ID>"
$ClientSecret = "<Copy/Paste ClientSecret ID>"

# Policy
$DisplayName  = "Cloud-Apps-Prov-4"
$Description  = "Cloud Apps Prov Policy - Frontline"
$EnableSSO    = $true
$RegionName   = "australiaeast"   # or "automatic"
$Locale       = "en-AU"
$Language     = "en-AU"

# Image (gallery)
$ImageType    = "gallery"
$ImageId      = "microsoftwindowsdesktop_windows-ent-cpc_win11-24H2-ent-cpc-m365"

# Assignment
$GroupId              = "b582705d-48be-4e4b-baac-90e5b50ebdf2"   # Entra ID Group
$ServicePlanId        = "057efbfe-a95d-4263-acb0-12b4a31fed8d"   # FL 2vCPU/8GB/128GB
$AllotmentCount       = 1
$AllotmentDisplayName = "CP-FL-Shared-CloudApp-1"

# Optional provisioning poll
$VerifyDesiredCount   = $AllotmentCount
$VerifyMaxTries       = 30
$VerifyDelaySec       = 30

# ==========================
# Helpers
# ==========================
function New-GraphUri {
  param(
    [Parameter(Mandatory)][string]$Path,        # e.g. "/beta/deviceManagement/virtualEndpoint/provisioningPolicies"
    [hashtable]$Query
  )
  $cleanPath = '/' + ($Path -replace '^\s*/+','' -replace '\s+$','')
  $b = [System.UriBuilder]::new("https","graph.microsoft.com")
  $b.Path = $cleanPath
  if ($Query -and $Query.Count -gt 0) {
    Add-Type -AssemblyName System.Web -ErrorAction SilentlyContinue | Out-Null
    $nvc = [System.Web.HttpUtility]::ParseQueryString([string]::Empty)
    foreach ($k in $Query.Keys) { $nvc.Add($k, [string]$Query[$k]) }
    $b.Query = $nvc.ToString()
  } else { $b.Query = "" }
  return $b.Uri.AbsoluteUri
}

function Invoke-Graph {
  param(
    [Parameter(Mandatory)][ValidateSet('GET','POST','PATCH','DELETE','PUT')][string]$Method,
    [Parameter(Mandatory)][string]$Uri,
    [hashtable]$Headers,
    $Body
  )
  try {
    if ($PSBoundParameters.ContainsKey('Body')) {
      return Invoke-RestMethod -Method $Method -Uri $Uri -Headers $Headers -Body ($Body | ConvertTo-Json -Depth 20)
    } else {
      return Invoke-RestMethod -Method $Method -Uri $Uri -Headers $Headers
    }
  } catch {
    Write-Warning "HTTP $Method $Uri failed: $($_.Exception.Message)"
    try {
      $resp = $_.Exception.Response
      if ($resp -and $resp.GetResponseStream()) {
        $reader = New-Object IO.StreamReader($resp.GetResponseStream())
        $text   = $reader.ReadToEnd()
        Write-Host "Response body:" -ForegroundColor DarkYellow
        Write-Host $text
      }
    } catch {}
    throw
  }
}

# ==========================
# 1) AUTH — Client Credentials
# ==========================
$TokenEndpoint = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
$tokenForm = @{
  client_id     = $ClientId
  client_secret = $ClientSecret
  scope         = "https://graph.microsoft.com/.default"
  grant_type    = "client_credentials"
}
$auth = Invoke-RestMethod -Method Post -Uri $TokenEndpoint -Body $tokenForm -ContentType 'application/x-www-form-urlencoded'
if (-not $auth.access_token) { throw "No access_token returned. Ensure CloudPC.ReadWrite.All (+ CloudPC.Read.All) are admin-consented." }

$Headers = @{
  Authorization = "Bearer $($auth.access_token)"
  "Content-Type" = "application/json"
  "Prefer"       = "include-unknown-enum-members"
}

# Base paths
$PoliciesPath = "/beta/deviceManagement/virtualEndpoint/provisioningPolicies"
$CloudPcsPath = "/beta/deviceManagement/virtualEndpoint/cloudPCs"

# ==========================
# 2) Ensure (Get-or-Create) the policy
# ==========================
$escapedName = $DisplayName.Replace("'","''")
$findUri     = New-GraphUri -Path $PoliciesPath -Query @{ '$filter' = "displayName eq '$escapedName'" }

Write-Host "Finding policy by name: $DisplayName" -ForegroundColor Cyan
try { $existing = Invoke-Graph -Method GET -Uri $findUri -Headers $Headers }
catch { Write-Warning "Name lookup failed; proceeding to create."; $existing = $null }

if ($existing -and $existing.value -and $existing.value.Count -gt 0) {
  $policy   = $existing.value | Select-Object -First 1
  $policyId = $policy.id
  Write-Host "Using existing policy '$DisplayName' (id: $policyId)" -ForegroundColor Yellow
} else {
  $createBody = @{
    "@odata.type"           = "#microsoft.graph.cloudPcProvisioningPolicy"
    displayName             = $DisplayName
    description             = $Description
    enableSingleSignOn      = $EnableSSO
    imageType               = $ImageType
    imageId                 = $ImageId
    managedBy               = "windows365"
    microsoftManagedDesktop = @{
      "@odata.type" = "microsoft.graph.microsoftManagedDesktop"
      managedType   = "notManaged"
    }
    windowsSetting          = @{
      "@odata.type" = "microsoft.graph.cloudPcWindowsSetting"
      locale        = $Locale
    }
    windowsSettings         = @{
      "@odata.type" = "microsoft.graph.cloudPcWindowsSettings"
      language      = $Language
    }
    userExperienceType      = "cloudApp"
    provisioningType        = "sharedByEntraGroup"
    domainJoinConfigurations = @(
      @{
        "@odata.type"  = "microsoft.graph.cloudPcDomainJoinConfiguration"
        domainJoinType = "azureADJoin"
        type           = "azureADJoin"
        regionName     = $RegionName
      }
    )
  }

  $createUri = New-GraphUri -Path $PoliciesPath
  Write-Host "Creating policy '$DisplayName'..." -ForegroundColor Cyan
  $policy   = Invoke-Graph -Method POST -Uri $createUri -Headers $Headers -Body $createBody
  $policyId = $policy.id
  if (-not $policyId) { throw "Create succeeded but no policy id returned." }
  Write-Host "Created policy id: $policyId" -ForegroundColor Green
}

# ==========================
# 3) Assign — group + size + capacity + label
# ==========================
$assignUri = New-GraphUri -Path ($PoliciesPath + "/$policyId/assign")

Write-Host "Clearing existing assignments..." -ForegroundColor DarkGray
Invoke-Graph -Method POST -Uri $assignUri -Headers $Headers -Body @{ assignments = @() } | Out-Null

$assignBody = @{
  assignments = @(
    @{
      target = @{
        "@odata.type"          = "#microsoft.graph.cloudPcManagementGroupAssignmentTarget"
        groupId                = $GroupId
        servicePlanId          = $ServicePlanId
        allotmentLicensesCount = $AllotmentCount
        allotmentDisplayName   = $AllotmentDisplayName
      }
    }
  )
}
Write-Host "Assigning policy to group $GroupId (plan $ServicePlanId, count $AllotmentCount)..." -ForegroundColor Cyan
Invoke-Graph -Method POST -Uri $assignUri -Headers $Headers -Body $assignBody | Out-Null
Write-Host "Assignment submitted." -ForegroundColor Green

# ==========================
# 4) Verify — read policy with $expand=assignments (RETRY)
# ==========================
$expandUri = New-GraphUri -Path ($PoliciesPath + "/$policyId") -Query @{ '$expand' = 'assignments' }
Write-Host "Reading back policy + assignments via $expand..." -ForegroundColor Cyan

$verify = $null
for ($try=1; $try -le 12; $try++) {
  try {
    $verify = Invoke-Graph -Method GET -Uri $expandUri -Headers $Headers
    if ($verify.assignments -and $verify.assignments.Count -gt 0) { break }
    Write-Host "Assignments not materialized yet (attempt $try). Waiting 3s..." -ForegroundColor Yellow
  } catch {
    Write-Warning "Expand read attempt $try failed; retrying in 3s..."
  }
  Start-Sleep -Seconds 3
}
if (-not $verify) { throw "Failed to read policy with assignments after retries." }

$verify | ConvertTo-Json -Depth 20 | Write-Output

# Sanity: confirm the expected assignment
$expected = $verify.assignments | Where-Object {
  $_.target.groupId -eq $GroupId -and
  $_.target.servicePlanId -eq $ServicePlanId -and
  $_.target.allotmentLicensesCount -eq $AllotmentCount -and
  ($_.target.allotmentDisplayName -eq $AllotmentDisplayName -or -not $AllotmentDisplayName)
}
if ($expected) {
  Write-Host "✅ Assignment present with expected group, plan, and count." -ForegroundColor Green
} else {
  Write-Warning "Assignment not found with expected fields. See dump above."
}

# ==========================
# 5) (Optional) Poll for provisioned Cloud PCs for this policy
# ==========================
if ($VerifyDesiredCount -gt 0) {
  $cloudPcsUri = New-GraphUri -Path $CloudPcsPath -Query @{ '$filter' = "provisioningPolicyId eq '$policyId'" }
  for ($i = 1; $i -le $VerifyMaxTries; $i++) {
    try {
      $cloudPcs   = Invoke-Graph -Method GET -Uri $cloudPcsUri -Headers $Headers
      $pcsForPlan = $cloudPcs.value | Where-Object { $_.servicePlanId -eq $ServicePlanId -or -not $_.psobject.Properties.Name.Contains('servicePlanId') }
      $count      = ($pcsForPlan | Measure-Object).Count
      if ($count -ge $VerifyDesiredCount) {
        Write-Host "Provisioned Cloud PCs for policy: $count (target $VerifyDesiredCount) ✅" -ForegroundColor Green
        $pcsForPlan | ConvertTo-Json -Depth 10 | Write-Output
        break
      } else {
        Write-Host "Provisioned Cloud PCs for policy: $count (waiting for $VerifyDesiredCount) … attempt $i/$VerifyMaxTries" -ForegroundColor Yellow
      }
    } catch {
      Write-Warning "Provisioning check failed on attempt ${i}: $($_.Exception.Message)"
    }
    Start-Sleep -Seconds $VerifyDelaySec
  }
}

GitHub Link – avdwin365mem/W365-CloudApp-Prov-Policy at main · askaresh/avdwin365mem

Provisioning Policy Details – UI

Policy

Overview

Tips, gotchas, and troubleshooting

  • App discovery: Ensure the app has a Start menu shortcut on the image. That’s how Cloud Apps gets its list.
  • Security baselines: If your tenant enforces restrictions on PowerShell in the image at discovery time, discovery can fail.
  • MSIX/Appx: Discovery is expanding—classic installers show up first; some Appx/MSIX apps (e.g., newer Teams) may not appear yet.
  • Concurrency math: Active sessions for the policy are capped by assigned Frontline license count on that policy.
  • Schema drift: These are beta endpoints. If you hit a property/enum change, the script’s warnings will surface the response body—update the field names accordingly.

What’s next (Part 2)

We’ll move to All Cloud Apps to publish the discovered apps, tweak display name/description/command line/icon index, confirm they appear in Windows App, and cover unpublish/reset workflows—with your screenshots.

I hope you find this helpful information for creating a Cloud App using PowerShell. If I have missed any steps or details, I will be happy to update the post.

Thanks,
Aresh Sarkari

Cloud PC Maintenance Windows: Scheduling Resize Operations for Maximum Efficiency + Bonus Microsoft Graph Powershell way of implementation

3 Mar

Today I’m diving into a feature that’s currently in preview but promises to be super useful for Windows 365 Cloud PC admins: Cloud PC Maintenance Windows.

If you’ve ever needed to resize multiple Cloud PCs but worried about disrupting users during work hours, this new feature is about to make your life much easier. Let’s break it down!

What Are Cloud PC Maintenance Windows?

Simply put, maintenance windows allow you to schedule when certain actions (currently just resize operations) will take place on your Cloud PCs. Instead of changes occurring immediately after you initiate them, you can schedule them to run during specified time periods.

Think of it as telling your Cloud PCs, “Hey, only accept these maintenance actions during these specific hours.” It’s perfect for organizations that need to plan around busy periods and minimize disruption.

Why You Should Care About This Feature

There are several compelling reasons to start using maintenance windows:

  • After-hours maintenance: Schedule resize operations to happen overnight or on weekends
  • Predictable changes: Users receive notifications before maintenance begins
  • Bulk operations: Apply resize actions to entire departments or teams at once
  • Organizational compliance: Meet any requirements about when system changes can occur

Setting Up Your First Maintenance Window

The setup process is straightforward and consists of two main parts: creating the window itself and then applying it to a device action.

Part 1: Creating a Maintenance Window

  • Sign into the Microsoft Intune admin center
  • Navigate to Tenant administration > Cloud PC maintenance windows (preview)
  • Click Create
  • On the Basics page:
    • Enter a descriptive Name (e.g., “Weekend Resize Window”)
    • Add a Description to help other admins understand the purpose
  • On the Configuration page:
    • Set your Weekday schedule (if applicable)
    • Set your Weekend schedule (if applicable)
    • Remember: Each window must be at least two hours long
    • Select when users will receive notifications (15 minutes to 24 hours in advance)
  • On the Assignments page:
    • Add the groups whose Cloud PCs will use this maintenance window
  • Review your settings and click Create

Part 2: Using Your Maintenance Window

Once your window is created, it won’t do anything by itself until you create a bulk device action that uses it:

  • In the Intune admin center, go to Devices > Windows Devices > Bulk device actions
  • For the configuration:
    • OS: Windows
    • Device type: Cloud PCs
    • Device action: Resize
  • Select your source and target sizes
  • Important: Check the box for Use Cloud PC maintenance windows
  • Add the devices/groups and create the action

When the maintenance window becomes active, the resize operation will run, and users will receive notifications based on the lead time you specified.

Powershell way to implement Cloud PC maintence

Step 1 – Install the MS Graph Beta Powershell Module

#Install Microsoft Graph Beta Module
PS C:WINDOWSsystem32> Install-Module Microsoft.Graph.Beta

Step 2 – Connect to scopes and specify which API you wish to authenticate to. If you are only doing read-only operations, I suggest you connect to “CloudPC.Read.All” in our case, we are creating the policy, so we need to change the scope to “CloudPC.ReadWrite.All”

#Read-only
PS C:WINDOWSsystem32> Connect-MgGraph -Scopes "CloudPC.Read.All" -NoWelcome
Welcome To Microsoft Graph!

OR

#Read-Write
PS C:WINDOWSsystem32> Connect-MgGraph -Scopes "CloudPC.ReadWrite.All" -NoWelcome
Welcome To Microsoft Graph!
Permissions for MS Graph API

Step 3 –  Check the User account by running the following beta command.

#Beta APIs
PS C:WINDOWSsystem32> Get-MgBetaUser -UserId admin@wdomain.com

Create Cloud Maintenace Policy Window

We are creating a provisioning policy that involves the following: avdwin365mem/createcloudpcmaintwindow at main · askaresh/avdwin365mem

  • displayname – Name of the policy “CloudPC-Window-askaresh”
  • Description – Enter details to remember for the future
  • notification – 60 min (tweak based on your company policies)
  • Schedule – Weekday (Ensure don’t enter business hours)
# Ensure the Microsoft.Graph.Beta module is installed
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Beta)) {
    Write-Host "Installing Microsoft.Graph.Beta module..." -ForegroundColor Cyan
    Install-Module Microsoft.Graph.Beta -Force -AllowClobber
}
Import-Module Microsoft.Graph.Beta

# Connect to Microsoft Graph with the required permissions for maintenance operations
Write-Host "Connecting to Microsoft Graph..." -ForegroundColor Cyan
Connect-MgGraph -Scopes "CloudPC.ReadWrite.All" -NoWelcome

# Define the endpoint for Cloud PC maintenance windows
$uri = "beta/deviceManagement/virtualEndpoint/maintenanceWindows"

# Construct the JSON payload for the maintenance window
$maintenancePayload = @{
    displayName                   = "CloudPC-Window-askaresh"
    description                   = "A window for test"
    notificationLeadTimeInMinutes = 60
    schedules                     = @(
        @{
            scheduleType = "weekday"
            startTime    = "01:00:00.0000000"
            endTime      = "04:00:00.0000000"
        },
        @{
            scheduleType = "weekend"
            startTime    = "01:00:00.0000000"
            endTime      = "04:00:00.0000000"
        }
    )
} | ConvertTo-Json -Depth 5

# Call the Microsoft Graph API to create the maintenance window
try {
    Write-Host "Creating Cloud PC maintenance window..." -ForegroundColor Cyan
    $result = Invoke-MgGraphRequest -Method POST -Uri $uri -Body $maintenancePayload
    Write-Host "Maintenance window created successfully." -ForegroundColor Green
    $result | Format-List
}
catch {
    Write-Error "Error creating maintenance window: $_"
}

# Optionally disconnect from Microsoft Graph when done
Disconnect-MgGraph

The User Experience

From the user perspective, they’ll receive a notification in their Cloud PC session when a maintenance window is approaching. The notification will indicate that maintenance is scheduled and when it will occur. They can’t override or postpone the maintenance, but at least they’ll be prepared.

Current Limitations

It’s worth noting that this feature is still in preview, and has some limitations:

  • Currently only supports resize operations (likely to expand in the future)
  • The maintenance window itself doesn’t guarantee the success of operations
  • Doesn’t handle Windows updates, Intune payloads, or OS updates
  • Each window must be at least two hours long

When NOT to Use Maintenance Windows

If you have an urgent situation requiring immediate resizing of Cloud PCs, simply don’t check the “Use Cloud PC maintenance windows” box when creating your bulk action. This way, the resize will happen immediately rather than waiting for the next scheduled window.

Conclusion

Having played with this feature for a bit, I’m impressed with how it streamlines the management of Cloud PCs. Before this, scheduling maintenance was much more manual and potentially disruptive. While I wish it supported more actions beyond just resizing, this is a solid foundation that I expect Microsoft will build upon.

This feature is particularly valuable for organizations with users across different time zones or with strict requirements about when system changes can occur. It’s also a huge time-saver for admins who manage large fleets of Cloud PCs. I hope you find this helpful information for creating a Cloud PC maintenance window using PowerShell. If I have missed any steps or details, I will be happy to update the post.

Thanks,
Aresh Sarkari

Windows 365 – Report – Cloud PC actions + PowerShell Report Download

18 Dec

In the Dec 4th, 2023 for Windows 365 Enterprise, the reports for Cloud PC actions were announced. In today’s post, I will showcase how to access and make sense of the new report available within Microsoft Intune.

What does the report offer?

The Cloud PC Actions Report, currently in public preview, is a powerful report within the Windows 365 ecosystem. It provides detailed information on various actions taken by administrators on the Cloud PCs. Imagine you have multiple teams and admins within your organisation. This report can help you track the actions along with the Status and Date initiated, which can come in handy for troubleshooting and audit purposes.

Accessing the report – Cloud PC Actions

To view the report in Microsoft Intune portal, you can follow these steps:

What Actions are displayed?

The following actions are included in the report:

ActionDescription
Create SnapshotThis action allows administrators to capture the current state of a Cloud PC. It’s useful for backup purposes or before making significant changes, ensuring that there’s a point to revert back to if needed.
Move RegionThis feature enables the relocation of a Cloud PC to a different geographic region. It’s particularly beneficial for organizations with a global presence, ensuring that Cloud PCs are hosted closer to where the users are located, potentially improving performance and compliance with regional data laws.
Place Under ReviewThis action is used to flag a Cloud PC for further examination. It could be due to performance issues, security concerns, or compliance checks. Placing a PC under review may restrict certain functionalities until the review is completed.
Power On/Off (W365 Frontline only)Specific to Windows 365 Frontline, this action allows administrators to remotely power on or off a Cloud PC. This is crucial for managing devices in a frontline environment, where PCs might need to be controlled outside of regular working hours.
ReprovisionReprovisioning a Cloud PC involves resetting it to its initial state. This action is useful when a PC needs to be reassigned to a different user or if it’s experiencing significant issues that can’t be resolved through regular troubleshooting.
ResizeThis action refers to changing the size/specifications of a Cloud PC, such as adjusting its CPU, RAM, or storage. It’s essential for adapting to changing workload requirements or optimizing resource allocation.
RestartAdministrators can remotely restart a Cloud PC. This is a basic but critical action for applying updates, implementing configuration changes, or resolving minor issues.
RestoreThis action allows the restoration of a Cloud PC to a previous state using a saved snapshot. It’s a vital feature for recovery scenarios, such as after a failed update or when dealing with software issues.
TroubleshootThis is a general action that encompasses various diagnostic and repair tasks to resolve issues with a Cloud PC. It might include running automated diagnostics, checking logs, or applying fixes.

How This Report Benefits You

  • Enhanced Troubleshooting: Quickly identify failed actions and understand potential reasons for failure.
  • Efficient Management: Monitor ongoing actions and ensure smooth operation of Cloud PCs.
  • Actionable Insights: Make informed decisions based on the status and details of actions taken.

If you have a failed action you can select and click on retry and it will try to perform the action on your behalf.

Bonus – PowerShell Access to Cloud PC Actions Report

To get the csv download of the report via MS Graph follow these steps:

Connect to MS Graph API

Step 1 – Install the MS Graph Powershell Module

#Install Microsoft Graph Beta Module

PS C:WINDOWSsystem32> Install-Module Microsoft.Graph.Beta

Step 2 – Connect to scopes and specify which API you wish to authenticate to. If you are only doing read-only operations, I suggest you connect to “CloudPC.Read.All” in our case, we are creating the policy, so we need to change the scope to “CloudPC.ReadWrite.All”

#Read-only

PS C:WINDOWSsystem32> Connect-MgGraph -Scopes "CloudPC.Read.All" -NoWelcome
Welcome To Microsoft Graph!

OR

#Read-Write
PS C:WINDOWSsystem32> Connect-MgGraph -Scopes "CloudPC.ReadWrite.All" -NoWelcome
Welcome To Microsoft Graph!

Step 3 – Check the User account by running the following beta command.

#Beta APIs

PS C:WINDOWSsystem32> Get-MgBetaUser -UserId admin@wdomain.com

Download the csv Report

You will pass the following $prams variable with all the fields within the report. GitHub link – avdwin365mem/cloudpcactionreport at main · askaresh/avdwin365mem (github.com)

$params = @{

top = 50
skip = 0
search = ""
filter = ""
select = @(
"Id"
"CloudPcId"
"CloudPcDeviceDisplayName"
"DeviceOwnerUserPrincipalName"
"Action"
"ActionState"
"InitiatedByUserPrincipalName"
"RequestDateTime"
"LastUpdatedDateTime"
)
orderBy = @(
"LastUpdatedDateTime desc"
)
}

Get-MgBetaDeviceManagementVirtualEndpointReportActionStatusReport -BodyParameter $params

The Cloud PC Actions Report is a significant addition to Windows 365, offering a level of transparency and control that administrators have long sought. I hope you will find this helpful information for tracking the Cloud PC actions via this report. Please let me know if I have missed any steps or details, and I will be happy to update the post.

Thanks,
Aresh Sarkari

Windows 365 Cloud PC Audit Logs with Azure Log Analytics & Graph API using PowerShell

3 Nov

Are you looking to keep a vigilant eye on your Windows 365 environment? Good news! You can now send Windows 365 audit events to Azure Log Analytics, Splunk, or any other SIEM system that supports it.

Understanding the Scope of Windows 365 Audit Logs

When it comes to monitoring your Cloud PC environment, Windows 365 audit logs are an indispensable resource. These logs provide a comprehensive chronicle of significant activities that result in modifications within your Cloud PC setup (https://intune.microsoft.com/). Here’s what gets captured:

  • Creation Events: Every time a Cloud PC is provisioned, it’s meticulously logged.
  • Update Events: Any alterations or configurations changes made to an existing Cloud PC are recorded.
  • Deletion Events: If a Cloud PC is decommissioned, this action is also captured in the logs.
  • Assignment Events: The process of assigning Cloud PCs to users doesn’t go unnoticed; it’s all in the logs.
  • Remote Actions: Activities such as remote sign-outs or restarts are tracked for administrative oversight.

These audit events encompass most actions executed via the Microsoft Graph API, ensuring that administrators have visibility into the operations that affect their Cloud PC infrastructure. It’s important to note that audit logging is an always-on feature for Windows 365 customers. This means that from the moment you start using Cloud PCs, every eligible action is automatically logged without any additional configuration.

Windows 365 and Azure Log Analytics

Windows 365 has made it easier than ever to integrate with Azure Log Analytics. With a few simple PowerShell commands, you can create a diagnostic setting to send your logs directly to your Azure Log Analytics workspace.

  • Sign in to the Microsoft Intune admin center, select Reports > Diagnostic settings (under Azure monitor)> Add Diagnostic settings.
  • Under Logs, select Windows365AuditLogs.
  • Under Destination details, select the Azure Log Analytics and choose the Subscription & Workspace.
  • Select Save.

Query the Azure Log Analytics

Once your logs are safely stored in Azure Log Analytics, retrieving them is a breeze. You can use Kusto Query Language (KQL) to extract and analyze the data. Here’s a basic example of how you might query the logs:

  • Sign in to the Microsoft Intune admin center, select Reports > Log analytics (under Azure monitor)> New Query
  • Paste the below query under and click on Run
  • Optional you may save the Select Save. to use the query in the future.
Windows365AuditLogs
| where TimeGenerated > ago(7d)
| extend ParsedApplicationId = tostring(parse_json(ApplicationId)[0].Identity)
| extend ParsedUserPrincipalName = tostring(parse_json(UserPrincipalName)[0].Identity)
| extend ParsedUserId = tostring(parse_json(UserId)[0].Identity)
| project TenantId, TimeGenerated, OperationName, Result, 
          ParsedApplicationId, 
          ParsedUserPrincipalName, 
          ParsedUserId
| sort by TimeGenerated desc

Leverage Graph API to retrieve Windows 365 audit events

Connect to MS Graph API

Step 1 – Install the MS Graph Powershell Module

#Install Microsoft Graph Beta Module
PS C:WINDOWSsystem32> Install-Module Microsoft.Graph.Beta

Step 2 – Connect to scopes and specify which API you wish to authenticate to. If you are only doing read-only operations, I suggest you connect to “CloudPC.Read.All” in our case, we are creating the policy, so we need to change the scope to “CloudPC.ReadWrite.All”

#Read-only
PS C:WINDOWSsystem32> Connect-MgGraph -Scopes "CloudPC.Read.All" -NoWelcome
Welcome To Microsoft Graph!

OR

#Read-Write
PS C:WINDOWSsystem32> Connect-MgGraph -Scopes "CloudPC.ReadWrite.All" -NoWelcome
Welcome To Microsoft Graph!
Permissions for MS Graph API

Step 3 –  Check the User account by running the following beta command.

#Beta APIs
PS C:WINDOWSsystem32> Get-MgBetaUser -UserId admin@wdomain.com

Get entire list of audit events, including the audit actor

To get the entire list of audit events including the actor (person who performed the action), use the following command:

Get-MgBetaDeviceManagementVirtualEndpointAuditEvent | Select-Object -Property Actor,ActivityDateTime,ActivityType,ActivityResult -ExpandProperty Actor | Format-Table UserId, UserPrincipalName, ActivityType, ActivityDateTime, ActivityResult


Get a list of audit events

To get a list of audit events without the audit actor, use the following command:

Get-MgBetaDeviceManagementVirtualEndpointAuditEvent -All -Top 100

Integrating Windows 365 with Azure Log Analytics is a smart move for any organization looking to bolster its security and compliance posture. With the added flexibility of forwarding to multiple endpoints, you’re well-equipped to handle whatever audit challenges come your way.

I hope you will find this helpful information for enabling and quering Windows 365 Audit Logs in Azure Logs Analytics or using Graph API with PowerShell. Please let me know if I have missed any steps or details, and I will be happy to update the post.

Thanks,
Aresh Sarkari

Microsoft Intune – Add additional DNS Client Servers across the managed devices

24 Aug

I recently wrote a blog post about adding DNS Client via GPO, highlighting which methods work and which don’t. If you’re interested, you can read more about it on – GPO – PowerShell – Intune – Add additional DNS Client Servers across the enterprise | AskAresh. As promised, here are the steps for performing the same task in Microsoft Intune for all of your managed devices.

Note – The best method of assigning the DNS Servers is through the DHCP server. If you are setting the IP using DHCP, always make sure you add/remove additional DNS Client Servers from there. In my situation, there was no DHCP server, hence the detailed blog post.

Prerequsites

We are going to implement this configuration via Microsoft Intune using the Scripts:

  • The necessary Microsoft Intune permissions to create, the PowerShell Scripts.
  • A device group available within Microsoft Entra with all the devices you want to target this change.

    PowerShell Script for DNSClient (Additional DNS Servers)

    Save the below script and place on the desktop and we shall be uploading it to Microsft Intune portal – “AddDNSClient.ps1″

    • Please enter the proper DNS Server Address within the script based on your environment and requirement. In the example below the existing two DNS servers are 8.8.8.8 and 8.8.8.4. We are adding additional two DNS Servers 9.9.9.9 and 9.9.9.4.
    $dnsclient=Get-DnsClient  | Get-DnsClientServerAddress | where{$_.ServerAddresses -contains "8.8.8.8" -or $_.ServerAddresses -contains "8.8.8.4"}
    foreach($nic in $dnsclient){
    Set-DnsClientServerAddress -InterfaceIndex $nic.InterfaceIndex -ServerAddresses ("8.8.8.8","8.8.8.4","9.9.9.9","9.9.9.4")
    }

    Create a script policy and assign it – Intune

    1. Sign in to the Microsoft Intune admin center.
    2. Select Devices > Scripts > Add > Windows 10 and later.Screenshot that shows creating a new script for a Windows 10 device.
    3. In Basics, enter the following properties, and select Next:
      • Name: AddDNSClientServers
      • Description: Additional DNS Server 3 & 4
    4. In Script settings, enter the following properties, and select Next:
      • Script location: Browse to the PowerShell script. saved previously and upload it (AddDNSClient.ps1)
      • Run this script using the logged on credentials: Select No.
      • Enforce script signature check: Select No 
      • Run script in 64-bit PowerShell host: Select Yes to run the script in a 64-bit PowerShell host on a 64-bit client architecture.
    5. Select Assignments > Select groups to include. Add the AAD group “Win11-P-DG”

    Wait for approx. 15-20 minutes and the policy will apply to the managed devices. (Machine Win11-Intune-15)

    Managed Device

    You can validate that the settings have been applied to the client by going to the path – C:\ProgramData\Microsoft\IntuneManagementExtension\Logs and opening the file IntuneManagementExtension.txt. I copied the policy ID – cf09649b-78b7-4d98-8bcc-b122c29e5527 from the Intune portal hyperlink and searched within the log file. We can see the policy has been applied successfully.

    I hope you will find this helpful information for applying additional DNS servers via Intune – Scripts and PowerShell. Please let me know if I have missed any steps or details, and I will be happy to update the post.

    Thanks,
    Aresh Sarkari

    GPO – PowerShell – Intune – Add additional DNS Client Servers across the enterprise

    16 Aug

    Let’s say you have the entire Windows member server fleet of Windows Server 2016/2019/2022, Windows 11 Pro/Enterprise etc., using DNS Server 1 and Server 2 within their TCP-IP properties and now you decide to add DNS Server address 3 and Server 4 to the member servers to increase resiliency.

    In the blog post, I will demonstrate how you can add the additional DNS Server using Group Policy Object and PowerShell with your enterprise.

    What doesn’t work?

    It would be best if you didn’t waste time – The GPO Computer Configuration –> Administrative Templates –> Network –> DNS Client –> DNS Servers doesn’t work. The “Supported On” version doesn’t include Windows Server 2016\Windows 10 in the compatibility. Even if you apply this GPO, it will apply to the server within the registry, but there will be no visible change under the TCP-IP properties.

    Prerequsites

    We are going to implement this configuration via group policy object within the enterprise:

    • The necessary active directory permissions to create, apply and link the GPOs
    • Access to the Sysvol folder to store the script
    • WMI Filters to target the script\GPO to specific subnets (More details below)

    PowerShell Script for DNSClient (Additional DNS Servers)

    Save the below script and place it within the location – \\DOMAINNAME\SYSVOL\DOMAINNAME\scripts\SetDNSAddress.ps1″

    • Please enter the proper DNS Server Address within the script based on your environment and requirements.
    $dnsclient=Get-DnsClient  | Get-DnsClientServerAddress | where{$_.ServerAddresses -contains "192.168.0.3" -or $_.ServerAddresses -contains "192.168.0.4"}
    foreach($nic in $dnsclient){
    Set-DnsClientServerAddress -InterfaceIndex $nic.InterfaceIndex -ServerAddresses ("192.168.0.3","192.168.0.4","192.168.0.5","192.168.0.6")
    }

    Create the GPO (Additional DNS Servers)

    On a member server with administrative privileges, press Win + R to open the Run box. Type gpmc.msc and press Enter to open the Group Policy Management Console.

    • In the GPMC, expand the forest and domain trees on the left pane to locate the domain you want to create the GPO in.
    • Right-click on “Group Policy Objects” under the domain and select “New” to create a new GPO.
    • In the “New GPO” dialog box, provide a name for the GPO (e.g., “Additional DNS Servers”) and click “OK”.
    • Right-click on the newly created GPO and select “Edit” to open the Group Policy Management Editor.
    • Navigate to Computer Configuration > Preferences > Control Panel Settings > Scheduled Tasks
    • Right Click on Scheduled Tasks > Configure the task as Immediate Task.
    • Give it a name – SetDNSClient
    • Set the user account as SYSTEM. It will automatically convert into NT Authority\system.
    • Set the check “run with highest privileges”
    • In the Actions tab, create a new “Start a program” action.
    • Set the Program as: PowerShell.exe
    • Set the Add Arguments point to this line, and modify including your network share and file: ExecutionPolicy Bypass -command “& \\DOMAINNAME\SYSVOL\DOMAINNAME\scripts\SetDNSAddress.ps1”
    • Set the following in common Tab. – “Apply once and do not reapply”

    Bonus Tip – WMI Filters

    You want to target the GPO to a specific set of member servers who’s IP range starts with a particular IP address. Then you can create a WMI filter such as the below to target particular computers that meet the below range. In the below example, the GPO will apply to the machine starting with IP Address 10.XX OR 10.XX.

    Select * FROM Win32_IP4RouteTable
    WHERE (Mask='255.255.255.255'
    AND (Destination Like '192.168.%' OR Destination Like '192.169.%'))

    Intune (Configuration Profiles – Doesn’t Work)

    As of writing the blog post the Intune built-in setting\CSP is showing similar behaviour like the DNS Server GPO it doesn’t work.

    CSP

    Under both situations (CSP & ADMX templates), the report says the policy is applied successfully. However, there is no visible impact on the operating system’s TCP-IP properties. I am optimistic that using the Scripts method and PowerShell can achieve the same results in Intune. Please let me know in the comments sections if you got it working or/else if you would like to see a blog post on using Intune Scripts to set the DNS Client on member servers.

    Following are the references and important links worth going through for more details:

    DescriptionLinks
    Static DNS Servers via GPOUpdate DNS static servers in your local Network (itdungeon.blogspot.com)
    DNS Server GPO doesn’t workDNS Server GPO Settings Invisible in IPConfig – CB5 Solutions LLC (cbfive.com)

    I hope you will find this helpful information for applying additional DNS servers via the GPO and PoweShell. I want to thank my friend Eqbal Hussian for his assistance and additional rounds of testing\validations. Please let me know if I have missed any steps or details, and I will be happy to update the post.

    Thanks,
    Aresh Sarkari

    PowerShell – GPO Analysis – Search for a specific or list of GPO Setting across multiple GPOs within a domain

    20 Jul

    Suppose you’ve ever had to search for a particular or a list of GPO settings across a large number of Group Policy Objects (GPOs) within your domain. In that case, you know how tedious it can be to find specific settings across hundreds or thousands of GPOs. PowerShell comes to the rescue with a powerful script that can search for GPO settings across all your existing GPOs and generate an organized CSV output. In this blog post, we’ll walk you through the process and ensure you have all the prerequisites to get started.

    Usecase

    You have approx. 50 to 60 GPO settings from the Center of Internet Security (CIS) benchmark policies document (CIS Microsoft Windows Desktop Benchmarks/CIS Microsoft Windows Server Benchmarks), which you may want to search against your domain, whether they are already preconfigured\existing available within a GPO or not present in the environment. Instead of searching manually one by one, you may want to use the below PowerShell to get results like a champion.

    Prerequisites

    Before using the PowerShell script, ensure you have the following prerequisites in place:

    1. Windows PowerShell version 5.0 and above
    2. Active Directory Module for Windows PowerShell
    3. Permissions: Ensure you have sufficient permissions to access and analyze GPO settings. Typically, you need to be a member of the Domain Administrators group or have equivalent privileges.
    4. Execute the script from a member server that is part of the domain and has the necessary permissions.
    5. Prepare the input file (inputgpo.txt) and enter the GPO setting one per line and save the file. In my situation, it’s present in C:\Temp
    Relax minimum password length limits
    Allow Administrator account lockout
    Generate security audits
    Impersonate a client after authentication
    Lock pages in memory
    Replace a process level token
    Accounts: Block Microsoft accounts
    Interactive logon: Machine inactivity limit
    Microsoft network server: Server SPN target name validation level
    Network access: Remotely accessible  registry paths
    Network security: Configure encryption types allowed for Kerberos
    Audit Security State Change
    Do not allow password expiration time longer than required by policy
    Password Settings: Password Complexity
    Password Settings: Password Length
    Password Settings: Password Age (Days)

    PowerShell Script

    Now that you have the prerequisites in place, let’s dive into the PowerShell script. GitHub – avdwin365mem/GPOSettingsSearch at main · askaresh/avdwin365mem (github.com)

    • Enter the name of your domain (E.g askaresh.com)
    • Make sure the Input file is present in C:\Temp
    #Domain
    $DomainName = "askaresh.com"
    
    # Initialize matchlist
    $matchlist = @()
    
    # Collect all GPOs
    $GPOs = Get-GPO -All -Domain $DomainName
    
    # Read search strings from text file
    # A list of GPOs settings you want to search
    $SearchStrings = Get-Content -Path "C:\Temp\inputgpo.txt"
    
    # Hunt through each GPO XML for each search string
    foreach ($searchString in $SearchStrings) {
        $found = $false
        foreach ($gpo in $GPOs) {
            $GPOReport = Get-GPOReport -Guid $gpo.Id -ReportType Xml
            if ($GPOReport -match $searchString) {
                $match = New-Object PSObject -Property @{
                    "SearchString" = $searchString
                    "GPOName" = $gpo.DisplayName
                }
                $matchlist += $match
                $found = $true
            }
        }
        if (-not $found) {
            $match = New-Object PSObject -Property @{
                "SearchString" = $searchString
                "GPOName" = "No results found"
            }
            $matchlist += $match
        }
    }
    
    # Output results to CSV, Search results
    
    # This step will take time depending how many 100's or 1000's policies present in the enviornment
    $matchlist | Export-Csv -Path "C:\Temp\gposearch.csv" -NoTypeInformation
    

    Output (Results)

    The ouput will look like the following within CSV:

    I hope you will find this helpful information for searching GPO settings across 100’s and 1000’s of GPOs within your domain. Please let me know if I have missed any steps or details, and I will be happy to update the post.

    Thanks,
    Aresh Sarkari

    PowerShell – Frontline Workers – Create Windows 365 Cloud PC Provisioning Policy

    23 May

    I have a blog post about creating a Windows 365 Cloud PC Provisioning Policy using PowerShell. In this post blog, I will demonstrate how to create the provisioning policy using PowerShell and MS Graph API with beta modules for Windows 365 Cloud PC – Frontline Workers.

    Windows 365 Frontline Worker

    Introduction

    I will not attempt to explain Frontline, but the best explanation is here: What is Windows 365 Frontline? | Microsoft Learn.

    Example – Each Windows 365 Frontline license can be shared with up to three employees. This means that if you have 30 employees, you only need to purchase 10 licenses to provision the CloudPC for all 30 employees with access over the day. However, note you are buying the frontline license based on the active sessions. You must purchase the license accordingly if you have more than 10 active workers in a shift.

    What happens when license are exhausted?

    In my demo tenant, I have two licenses for Frontline workers. When I try to log in to the third one (Note I have already logged into 2 active sessions and running them.) Get the following message.

    Connect to MS Graph API

    Step 1 – Install the MS Graph Powershell Module

    #Install Microsoft Graph Beta Module
    PS C:WINDOWSsystem32> Install-Module Microsoft.Graph.Beta

    Step 2 – Connect to scopes and specify which API you wish to authenticate to. If you are only doing read-only operations, I suggest you connect to “CloudPC.Read.All” in our case, we are creating the policy, so we need to change the scope to “CloudPC.ReadWrite.All”

    #Read-only
    PS C:WINDOWSsystem32> Connect-MgGraph -Scopes "CloudPC.Read.All" -NoWelcome
    Welcome To Microsoft Graph!
    
    OR
    
    #Read-Write
    PS C:WINDOWSsystem32> Connect-MgGraph -Scopes "CloudPC.ReadWrite.All" -NoWelcome
    Welcome To Microsoft Graph!
    Permissions for MS Graph API

    Step 3 –  Check the User account by running the following beta command.

    #Beta APIs
    PS C:WINDOWSsystem32> Get-MgBetaUser -UserId admin@wdomain.com

    Create Provisioning Policy (Frontline Worker)

    We are creating a provisioning policy that involves the following: avdwin365mem/win365frontlineCreateProvPolicy at main · askaresh/avdwin365mem · GitHub

    • Azure AD Joined Cloud PC desktops
    • The region for deployment – Australia East
    • Image Name – Windows 11 Enterprise + Microsoft 365 Apps 22H2 (from the Gallery)
    • Language & Region – English (United States)
    • Network – Microsoft Managed
    • Cloud PC Naming format – FLW-%USERNAME:5%-%RAND:5% (FLW – Frontline Worker)
    $params = @{
    	displayName = "Demo-FrontLine"
    	description = "Front Line Workers Prov Policy"
    	provisioningType = "shared"
    	managedBy = "windows365"
    	imageId = "MicrosoftWindowsDesktop_windows-ent-cpc_win11-22h2-ent-cpc-m365"
    	imageDisplayName = "Windows 11 Enterprise + Microsoft 365 Apps 22H2"
    	imageType = "gallery"
    	microsoftManagedDesktop = @{
    		type = "starterManaged"
    		profile = $null
    	}
    	enableSingleSignOn = $true
    	domainJoinConfigurations = @(
    		@{
    			type = "azureADJoin"
    			regionGroup = "australia"
    			regionName = "automatic"
    		}
    	)
    	windowsSettings = @{
    		language = "en-US"
    	}
    	cloudPcNamingTemplate = "FLW-%USERNAME:5%-%RAND:5%"
    }
    
    New-MgBetaDeviceManagementVirtualEndpointProvisioningPolicy -BodyParameter $params

    Note – Post provisioning, you need to add the assignment of a AAD group consisting of all the frontline users. In the future I can demonstrate the API call for assignments. You can also use Andrew Taylors post around using Graph to create the Windows 365 Group – Creating Windows 365 Groups and assigning licenses using Graph and PowerShell

    Powershell Output

    Policy will show up in the MEM Portal

    Optional Properties

    If you are doing on-premise network integration (Azure Network Connection) , then the following additional property and value is required. In my lab, I am leveraging the Microsoft Managed Network, so this is not required.

    OnPremisesConnectionId = "4e47d0f6-6f77-44f0-8893-c0fe1701ffff"

    I hope you will find this helpful information for creating a frontline worker provisioning policy using PowerShell. Please let me know if I have missed any steps or details, and I will be happy to update the post.

    Thanks,
    Aresh Sarkari