Get our Bestselling Ethical Hacker Course V13 for Only $12.99

For a limited time, check out some of our most popular courses for free on Udemy.  View Free Courses.

Using PowerShell to Automate Device Configuration in Microsoft Endpoint Manager

Vision Training Systems – On-demand IT Training

Microsoft Endpoint Manager gives IT teams a central place to handle device management, but the real payoff comes when repetitive work is automated. If you are running an Intune course lab, building an automation framework, or trying to cut down on repetitive PowerShell scripting tasks, the goal is the same: consistent endpoint configuration across every device without touching each one by hand.

PowerShell is the practical companion to Endpoint Manager because it lets you turn manual clicks into repeatable actions. Instead of opening the portal to update one policy, assign one profile, or export one report, you can script the same work for dozens or thousands of objects. That matters when your environment grows, when change windows are short, and when human error is expensive.

The business value is straightforward. Automation reduces drift, speeds up onboarding, standardizes security settings, and gives you a better audit trail. A good script also helps you scale across business units, regions, and tenant structures without rebuilding every process from scratch.

This post focuses on practical use cases, the PowerShell tools that matter, the prerequisites you need before you start, and the patterns that make scripts safe in production. You will also see where Microsoft Graph fits, how to handle groups and assignment filters, and how to troubleshoot the problems that tend to show up after the first successful run.

Understanding Microsoft Endpoint Manager And Where PowerShell Fits

Microsoft Endpoint Manager is Microsoft’s centralized management umbrella for endpoint policy, application delivery, and device compliance. In practice, most admins use Intune for cloud-based device management while Microsoft Entra ID handles identity and access. The control plane is now heavily Graph-driven, which is why PowerShell scripting matters so much for modern endpoint configuration.

Microsoft documents Intune management and Microsoft Graph integration through Microsoft Learn and the Microsoft Graph overview. That division is important: the portal is ideal for one-off changes, while Graph and PowerShell are better for repetitive work, bulk operations, and reporting at scale. If you are following an Intune course, this is one of the first architectural concepts to understand.

PowerShell is especially useful for objects that repeat across many devices or business groups. Common examples include:

  • Device configuration profiles
  • Compliance policies
  • Administrative templates and settings catalog objects
  • App assignment logic
  • Device and user inventory
  • Targeted assignments and exclusions

Not every task belongs in a script. If a setting changes rarely and needs a lot of human review, the admin portal can still be the best choice. If a task happens often, needs to be replicated across rings, or must be reported to auditors, scripting wins.

Automation is not about replacing administrators. It is about removing the repetitive steps that cause mistakes and slow down every change.

Typical time-saving scenarios include bulk policy updates after a security review, onboarding a new business unit with a standard baseline, and generating recurring compliance reports. These are the jobs that eat time when done manually and become predictable when handled through automation.

Prerequisites And Setup For Endpoint Automation

Before you write a script, make sure your permissions, tools, and authentication model are set correctly. In Microsoft Intune and Graph, a script may need delegated permissions, application permissions, or specific Intune admin roles depending on what it touches. Microsoft’s role-based access guidance is documented in Intune RBAC and Graph permissions reference.

For interactive work, install the Microsoft Graph PowerShell SDK and sign in with a user account that has the right Intune role. For unattended runs, use an app registration and certificate-based authentication. That approach is more appropriate for scheduled jobs, pipelines, or server-based automation than storing passwords in a script.

Core setup steps usually include:

  1. Assign the correct Intune role and scope tags.
  2. Create or verify an Entra ID app registration for unattended access.
  3. Grant only the Graph permissions the script needs.
  4. Install the required modules on a test system.
  5. Validate access in a pilot tenant or lab before production.

Use secure secret handling from the start. Certificate-based auth is preferred over client secrets for long-lived jobs, and Microsoft recommends managed identities where supported in Azure automation services. For secret storage, use Azure Key Vault rather than plaintext files or hardcoded variables.

Warning

Do not test endpoint automation for the first time in production. A script that updates the wrong filter, overwrites assignments, or removes a profile can affect hundreds of devices in minutes.

A lab or pilot environment should mimic production as closely as possible. That means similar group structure, similar device types, and similar naming standards. If you are taking an Intune course, this is where a realistic test tenant pays off, because it exposes issues before they become outages.

Core PowerShell Modules And APIs To Know

The primary modern interface for endpoint management automation is the Microsoft Graph PowerShell SDK. Microsoft positions Graph as the unified API for working with Microsoft 365 services, and Intune is one of the major workloads exposed through it. The SDK provides cmdlets that map to Graph endpoints and make requests more readable than hand-building raw REST calls.

Legacy Intune PowerShell cmdlets still appear in older environments, and you may see them in scripts that were written before Graph became the recommended path. They can still be useful for reading existing logic, but Graph is the better long-term choice because it is the supported direction for Microsoft endpoint management.

Useful Graph areas for device work include deviceManagement, deviceConfiguration, and managedDevices. These endpoints let you query policies, create or update configuration objects, inspect enrolled devices, and manage assignments. Microsoft’s reference documentation at Microsoft Learn is the best place to verify object paths and supported operations.

Common PowerShell patterns include:

  • Get objects to inventory existing policies and devices.
  • New objects to create a profile or assignment.
  • Update objects to modify a setting in place.
  • Remove objects to retire unused configuration.

When you work with Graph at scale, JSON payloads matter. Many settings are nested objects, arrays, or hashtables that must be shaped correctly before you send them. You also need to understand pagination, because inventory calls can return partial results unless you follow next links or use SDK paging helpers.

Key Takeaway

In Endpoint Manager automation, Graph is the API layer, PowerShell is the control language, and JSON is often the payload format that ties them together.

Automating Common Device Configuration Tasks

Most administrators start with repetitive profile work. That makes sense, because configuration profiles are easy to standardize and easy to validate. If you manage Windows, macOS, iOS, and Android devices, PowerShell can help you create, update, and assign profiles in a repeatable way rather than editing each policy by hand.

Common tasks include Wi-Fi profiles, VPN settings, email configuration, certificate deployment, security baselines, and endpoint protection settings. Microsoft documents each workload differently, but the underlying pattern is consistent: define the setting, target the right group, and verify the assignment result. For Windows profile documentation, see Microsoft Learn.

A practical automation example is creating a standard baseline for a new department. You might apply:

  • A device restriction profile
  • A password or compliance policy
  • A Wi-Fi configuration for corporate networks
  • A VPN profile for remote access
  • A certificate profile for trusted authentication

Another useful pattern is bulk policy updates. If your security team changes a setting after a threat review, scripting lets you update the policy once and reapply it across multiple rings or tenants. That is much safer than editing the same setting in ten separate profiles and hoping they stay aligned.

For multi-business-unit environments, standardization becomes the real win. You can create a common baseline and then layer business-specific changes on top. That keeps the core endpoint configuration consistent while still allowing exceptions where they are genuinely needed.

One area that benefits from careful scripting is cross-platform consistency. Windows and macOS may not support identical settings, but PowerShell can still manage the logic that keeps naming, assignments, and reporting aligned. That is especially valuable if you are building an automation model for a mixed-device fleet.

Building Safe And Reusable PowerShell Scripts

Good scripts do not just work once. They should be reusable, easy to review, and safe to run again without creating duplicates or damaging existing configuration. That is why defensive PowerShell scripting matters as much as API knowledge.

Use functions to separate tasks such as authentication, lookup, validation, update, and reporting. A script that does everything in one block becomes hard to troubleshoot. A script built from functions can be tested in pieces, which is much easier when a policy update fails halfway through.

Strong scripts usually include:

  • Parameters for tenant, group, profile name, or environment
  • Logging and transcript output for audit trails
  • Try/catch blocks for error handling
  • Verbose mode for troubleshooting
  • Idempotent logic so reruns do not duplicate objects

Idempotent design is critical in device management. If a script creates a profile only when it does not already exist, you avoid duplicate configurations. If it updates a setting only when the current value differs, you reduce noise and unexpected changes. That is a major advantage in regulated environments where every change may need evidence.

Use configuration files for environment-specific values such as tenant ID, group names, or assignment filters. That way the same script can move from test to pilot to production without code changes. For detailed logging, a transcript file and a structured CSV or JSON output are often enough for audit review and incident investigation.

Pro Tip

Build a dry-run mode early. In PowerShell, a well-designed WhatIf pattern lets you validate logic before anything is written back to Intune.

Working With Groups, Filters, And Dynamic Assignments

Entra ID groups drive policy targeting in Intune, so group design has direct impact on how well your automation behaves. If your groups are messy, your assignments will be messy too. Microsoft’s guidance on group-based assignment in Intune is documented in Microsoft Learn.

PowerShell can help create or update assignments that target security groups, dynamic device groups, or a mix of include and exclude logic. This is where automation becomes more than convenience. It becomes a control system for consistent rollout.

Assignment filters are especially useful when you need targeting based on operating system version, manufacturer, ownership, or enrollment profile. Instead of creating a separate group for every case, you can define a narrow filter and let the policy apply only where it belongs.

Security group targeting Best when membership is deliberate and controlled by process.
Dynamic device groups Best when devices should self-place based on attributes such as OS or name pattern.
Assignment filters Best when you want to refine targeting without creating more groups.

Ring-based deployment is another strong use case. You can automate a pilot ring, a broad production ring, and a final catch-all ring. That gives change control teams a way to test policy behavior on a small set of devices before exposing the entire fleet to the same settings.

Common mistakes include over-targeting, duplicate assignments, and relying on poorly named groups that nobody can audit later. If the same device ends up in too many overlapping policies, troubleshooting becomes slow and the final applied state can be hard to predict.

For environments that use automation heavily, clean assignment logic is the difference between a stable system and a constant fire drill. This is one of the places where a disciplined Intune course can pay off because the theory maps directly to production behavior.

Reporting, Auditing, And Monitoring With PowerShell

Reporting is where many teams discover whether their endpoint management strategy is actually working. PowerShell and Graph can pull device inventory, compliance status, and configuration assignment details into CSV, JSON, or HTML outputs that are easy to share with operations, security, and audit teams.

That matters because management wants summary data, while administrators need detail. A CSV export is ideal for filtering and sorting in a spreadsheet. A JSON output is better for downstream automation. An HTML report is useful when the result needs to be reviewed quickly in a browser or attached to a ticket.

Useful reporting scenarios include:

  • Identifying noncompliant devices
  • Finding stale or unused configuration profiles
  • Detecting failed deployment rings
  • Finding orphaned assignments
  • Tracking endpoint configuration drift over time

Microsoft Graph can expose the raw data, and then PowerShell can shape it into something operationally useful. For recurring checks, schedule scripts through Azure Automation, Azure Functions, Task Scheduler, or CI/CD pipeline jobs depending on your environment and governance model.

Periodic reporting helps maintain configuration hygiene. It also gives you early warning when a profile is still assigned but no longer needed, or when a compliance policy is failing on a subset of devices after a software update. That early signal is valuable in environments that need strict control over endpoint posture.

Good reporting does not just show status. It tells you where drift, failure, and hidden risk are starting to build.

Real-World Automation Scenarios And Example Workflows

A first-day device setup workflow is one of the best practical examples of Endpoint Manager automation. A new device enrolls, receives policy assignments, gets the right apps, and runs compliance checks before the user finishes logging in. When this workflow is scripted well, the admin does not have to manually stitch together each step.

The workflow often looks like this: device enrolls, group membership resolves, configuration profiles apply, required apps install, compliance evaluates, and conditional access responds. If any stage fails, your script or report should show exactly where the process stopped. That makes remediation much faster.

Another strong use case is remediation. A script can scan for devices that no longer match the intended baseline, identify the cause, and reapply the correct settings. This is useful after accidental assignment changes, merged business units, or a security baseline update that needs broad correction.

Decommissioning is just as important. When a device is retired, you may need to remove assignments, revoke access, wipe compliance state, and clean up device records. If that process is manual, it is easy to miss a step. If it is scripted, it is repeatable and easier to audit.

For mergers or rapid expansion, automation supports standard operating procedures. You can reuse the same policy structure, adjust group mapping, and bring a new set of devices into the same baseline without rebuilding your model. That is also how teams support zero-touch provisioning and consistent endpoint baselines without adding a lot of administrative overhead.

Note

When you automate onboarding or decommissioning, document the exact sequence. Small differences in ordering can change whether a device becomes compliant or gets blocked.

Security, Governance, And Best Practices

Endpoint automation should be treated like any other privileged change process. That means least privilege, scoped access, peer review, and strong documentation. Microsoft’s security guidance and NIST’s control frameworks both support this approach, especially for scripts that modify policy or identity state. See Microsoft Security documentation and NIST Cybersecurity Framework.

Use separated duties for production automation whenever possible. The person who writes a script should not always be the same person who approves or runs it in production. Store scripts in version control, review changes before deployment, and keep a rollback plan for every major update.

Credential handling deserves special attention. Use certificates, managed identities, or a secure vault rather than embedding secrets in files. Rotate secrets regularly and remove app permissions that are no longer needed. If a script can reach the wrong API scope, it can cause real damage.

At scale, throttling and retry logic become important. Graph APIs can return rate-limit responses, temporary service errors, or partial results. A robust script should pause, retry, and log the failure rather than crash after the first API limit response.

Document every workflow in a runbook. Include what the script changes, what success looks like, how to verify the outcome, and how to roll back if needed. That kind of operational discipline is what turns PowerShell scripting from a clever shortcut into a supportable part of enterprise endpoint configuration.

Troubleshooting Common Issues

Most failures in Endpoint Manager automation fall into a few buckets: authentication problems, permission problems, malformed payloads, and timing issues. The fastest way to troubleshoot is to isolate one variable at a time. Start with authentication, then permissions, then the request body, and finally the assignment logic.

Authentication failures often trace back to expired certificates, revoked app permissions, or the wrong tenant context. If you are using app registration auth, confirm that the certificate is still valid and that the app has the exact Graph permissions required. For permission troubleshooting, the Microsoft Graph Explorer and the Graph permissions documentation are useful references.

API errors frequently come from invalid JSON or from sending a property that the endpoint does not accept. A script might work for one object type and fail for another because the payload schema differs slightly. This is where testing a request in Graph Explorer helps you validate the structure before putting the same logic into PowerShell.

Eventual consistency can also cause confusion. A profile may be created successfully but not appear in a group assignment report immediately. That does not always mean the script failed. It often means the cloud service needs time to replicate the change across back-end systems.

Assignment issues are another common pain point. A policy may look correct in the portal but not apply because of an exclusion, duplicate targeting, or filter mismatch. If devices do not receive the expected settings, check the effective assignment path, not just the top-level profile. Verbose logging and targeted test queries usually narrow the issue quickly.

When you are building an Intune course lab or troubleshooting in production, keep a small set of known-good test devices. They help separate script problems from tenant-wide issues and make it easier to confirm that a fix really worked.

Conclusion

PowerShell can turn Microsoft Endpoint Manager from a manual console-driven platform into a scalable, repeatable operating model. It helps you standardize device management, automate endpoint configuration, and reduce the errors that come from updating the same settings over and over again by hand. When you combine Graph, Intune, and disciplined automation, you gain speed without giving up control.

The most effective approach is to start small. Pick one workflow that wastes time today, such as policy reporting, assignment updates, or a standard onboarding sequence. Build it with secure authentication, clear logging, and a rollback plan. Then expand to the next workflow once the first one has been tested, reviewed, and proven reliable.

Good script design matters as much as the API calls themselves. Use least privilege, version control, approval steps, and retry logic. Those habits are what make PowerShell scripting maintainable in production rather than fragile after the first change window.

If your team still spends hours clicking through repetitive settings, now is the time to audit those manual tasks. Vision Training Systems can help you identify the best candidates for automation, build a practical rollout plan, and strengthen the skills your admins need to manage Endpoint Manager at scale.

Common Questions For Quick Answers

How does PowerShell help automate device configuration in Microsoft Endpoint Manager?

PowerShell helps you automate repetitive device configuration tasks in Microsoft Endpoint Manager by turning manual admin actions into repeatable scripts. Instead of configuring settings one device or profile at a time, you can use scripts to apply consistent changes across many endpoints, which is especially useful in larger environments and lab scenarios.

This approach is valuable for tasks like setting local policies, collecting inventory data, preparing devices for enrollment, or enforcing standard configuration baselines. By combining PowerShell with Intune and Microsoft Endpoint Manager workflows, IT teams can reduce human error, speed up deployment, and keep endpoint settings aligned with organizational requirements.

What types of device configuration tasks are best suited for PowerShell automation?

PowerShell is best suited for configuration tasks that are repetitive, scriptable, and consistent across devices. Common examples include installing or removing software, creating local accounts, modifying registry settings, checking device status, setting environment values, and applying custom configuration steps that are not always easy to handle through standard policy profiles.

It is also useful for pre-checks and remediation workflows, such as validating whether a device meets a baseline before deployment or correcting drift after changes occur. A good rule of thumb is to use PowerShell when a task needs precision, repeatability, and clear logic, while still using Microsoft Endpoint Manager for centralized policy control and assignment.

How can you make PowerShell scripts safer and more reliable in Intune and Endpoint Manager?

Safe and reliable scripting starts with testing, logging, and narrow scope. Before deploying a script widely, validate it in a lab or pilot group to confirm it behaves as expected on supported device types. Include clear logging so you can review outcomes, troubleshoot failures, and identify unexpected results without guessing what happened on the endpoint.

It also helps to make scripts idempotent, meaning they can run more than once without causing problems. Use checks before making changes, handle errors gracefully, and avoid hard-coding values that may vary across environments. When possible, keep the script focused on one task, use clear comments, and pair it with Microsoft Endpoint Manager assignment targeting so only the intended devices receive it.

What are the best practices for using PowerShell with Microsoft Endpoint Manager?

Best practices begin with keeping scripts simple, modular, and easy to maintain. Break larger automation efforts into smaller functions or separate scripts so each part has a clear purpose. This makes it easier to troubleshoot, update, and reuse code across different endpoint management tasks.

It is also important to use consistent naming, document prerequisites, and define what success looks like before deployment. Where possible, prefer scripts that avoid user interaction and can run silently in managed environments. Pair PowerShell automation with reporting and validation so you can confirm the desired configuration state, rather than assuming the script completed successfully.

A practical checklist includes:

  • Test in a pilot group before broad deployment
  • Use logging for troubleshooting and auditability
  • Handle errors and validation checks explicitly
  • Keep scripts version-controlled for change tracking
What is the difference between using PowerShell scripts and built-in configuration profiles in Endpoint Manager?

Built-in configuration profiles are ideal for standard settings that Microsoft Endpoint Manager can manage natively, such as common device restrictions, security baselines, and policy-driven configurations. They are designed for centralized administration, consistency, and easier reporting through the Intune console.

PowerShell scripts, by contrast, are better when you need custom logic or need to manage settings that fall outside the standard policy options. Scripts can check conditions, branch based on device state, and perform actions that require more flexibility than a fixed configuration profile provides. In many environments, the most effective strategy is to use both together: configuration profiles for standard policy enforcement and PowerShell for specialized automation and remediation.

Get the best prices on our best selling courses on Udemy.

Explore our discounted courses today! >>

Start learning today with our
365 Training Pass

*A valid email address and contact information is required to receive the login information to access your free 10 day access.  Only one free 10 day access account per user is permitted. No credit card is required.

More Blog Posts