AI is the fastest PowerShell pair programmer available: it drafts scripts from a task description, explains legacy code line by line, debugs from an error message and optimises slow pipelines. This topic covers all four modes plus the two artefacts endpoint admins ship most — Intune detection and remediation scripts — and the error-handling and logging patterns that make scripts production-grade. One rule overrides everything else: Never blindly execute AI-generated administrative scripts in production. Validate and test them first.
AI for PowerShell means four working modes: generate (task description in, commented script out), explain (unknown script in, line-by-line walkthrough plus a risk list out), debug (script + exact error + $PSVersionTable in, cause and fix out) and optimise (slow script in, pipeline and performance critique out). On top of those sit the two artefacts endpoint admins ship most: detection scripts — fast, silent, exit 0 or 1 — and remediation scripts that change state idempotently with logging. And one mode applies to all of them, always: Never blindly execute AI-generated administrative scripts in production. Validate and test them first.
PowerShell is the automation layer of every Microsoft stack you administer — Windows, Intune, Entra ID, Azure — and AI moves the bottleneck from writing to reviewing. Tasks that used to cost an hour of documentation diving (paging through a Graph SDK reference for the right cmdlet) become minutes of prompting. Review, though, is the new job: a script with admin privileges that nobody has read is an unreviewed change to production. Teams that pair generation with a strict review-and-test habit ship automation an order of magnitude faster; teams that skip validation become the incident.
Generation quality is decided in the prompt. Name the module and version ('Microsoft.Graph PowerShell SDK 2.x'), and demand the patterns you would demand of a human junior: try/catch with meaningful messages, -WhatIf via SupportsShouldProcess on anything state-changing, no aliases, comment-based help, objects instead of formatted text. For debug mode, paste the exact error, the failing section and $PSVersionTable — AI debugs context, not vibes. For detection scripts the contract is rigid: exit 0 when compliant, exit 1 when not, no output, done in seconds. Remediation scripts: detect, change, re-detect, log. Then the human loop — review line by line, run in a VM with Start-Transcript, deploy to a pilot Intune group before wide assignment.
Task: generate / explain / debug / optimise
↓
Prompt with role, context, constraints
↓
AI drafts → human reviews line by line
↓
Test in a VM (-WhatIf + transcript)
↓
Deploy via Intune — scoped and loggedThe Monday report. Task: 'list devices missing the latest Windows quality update.' The prompt pins the module (Microsoft.Graph SDK), the cmdlet family (Get-MgDeviceManagementManagedDevice), pagination, try/catch and CSV output. The first draft compiles but pagination is missing and it invents a property; review catches both in ninety seconds. The second draft runs in a VM under Start-Transcript and exports a clean CSV. The same session produces a detection script checking a registry value for the app version — exit 0/1, no output — and a remediation script that reinstalls the app when detection fails. Both go to a pilot device group, not to All Devices, and the pilot's transcript becomes the evidence that they are safe.
'Role: senior Windows engineer. Task: export all Intune managed devices with OS version to CSV via Microsoft Graph. Context: Microsoft.Graph PowerShell SDK 2.x, {DEVICE_COUNT} devices. Constraints: Get-MgDeviceManagementManagedDevice, handle pagination, try/catch with meaningful messages, no aliases, no Read-Host. Output: commented script plus 3 usage notes.' Specific constraints separate a usable draft from a Stack Overflow remix.
Every line that runs with privileges gets read. Checklist: does each cmdlet exist (AI invents plausible ones — Get-IntuneManagedDevice is the retired legacy SDK; the modern name is Get-MgDeviceManagementManagedDevice)? What does it touch — files, registry, services, network? What happens if the Graph token is missing mid-run? Then a second AI pass: 'Review this script as a hostile security engineer; list risks, missing error handling and side effects.'
Checkpoint a test VM, run the script with Start-Transcript on, and for anything state-changing run with -WhatIf first — which requires the script to implement SupportsShouldProcess, so demand it in the generation prompt. Watch for: unexpected reboots, services stopped, writes outside the stated scope. No script graduates from the VM to a device group without a clean transcript and a reviewed -WhatIf run.
When a script fails, paste three things: the exact error text, the failing section and $PSVersionTable output. 'It does not work' produces guesses; 'Get-MgDeviceManagementManagedDevice : The tenant must have an Intune license' produces the actual cause in one response. Then ask for the fix as a diff: 'Show only the lines that change.' Small diffs are reviewable; full rewrites hide surprises.
Detection prompt: 'Write an Intune detection script that checks registry value HKLM:\SOFTWARE\Contoso\Agent for version 2.4.1 or higher. Constraints: exit 0 if compliant, exit 1 if not, no output, no changes, completes in under 10 seconds.' Remediation prompt: '…reinstall the agent silently from {SHARE_PATH}, log to C:\ProgramData\Contoso\Logs, exit 0 on success, exit 1 on failure.' Review, VM-test both, assign to a pilot group, then read AgentExecutor.log after the first run.
Final pass, requested explicitly: 'Add try/catch/finally around every remote or state-changing call, write a Start-Transcript log to a dated path, and make exit codes meaningful — 0 success, distinct non-zero codes per failure type.' A script that cannot explain what it did is not production-grade, however well it ran in the demo. Review this hardening pass most carefully — logging done wrong lies to you during incidents.
# 1. Read every line 2. Test in a VM 3. Use -WhatIf 4. Never run as-is in productionThis topic carries one absolute rule plus the habits that make it workable: Never blindly execute AI-generated administrative scripts in production. Validate and test them first. The habits: read every line before it runs with privileges; test in an isolated VM or pilot Intune group with Start-Transcript running; use -WhatIf / SupportsShouldProcess for anything state-changing; keep secrets out of prompts and out of code — environment variables or a vault only; scope Intune assignments to a pilot group before wide deployment; and keep the prompt, the reviewed script and the test evidence together in a private repo so the next engineer can audit the decision, not just the outcome.
Not unreviewed — and that is the whole answer. The loop: read every line, verify each cmdlet against the installed module, require -WhatIf support for state changes, run in a test VM with a transcript, then a pilot group before wide deployment. AI drafts in seconds, so review is now the cost centre, and it is non-negotiable: an unread admin script is an unreviewed change to production. With that loop in place, yes — and it has made shipping automation dramatically faster.
I brief it like a junior admin I trust with drafts, not with access: role, task, context (module and version, environment size), constraints — try/catch with meaningful messages, SupportsShouldProcess, no aliases, pagination for Graph calls, comment-based help — and output format: objects, not formatted text. The constraints section is where quality comes from; every pattern I would demand in code review, stated up front, is cheaper than asking for it afterwards.
Detection answers a question and changes nothing: exit 0 when compliant, exit 1 when not, no output, fast — it runs on every device on a schedule. Remediation fixes state: detect, change, re-detect to prove the fix worked, log what it did, and exit meaningfully. The classic AI failure modes are detection scripts that print output or exit 0 on error, and remediation scripts that are not idempotent — running twice does something different from running once. Both get the same review-and-VM-test loop before assignment.
Pick one recurring chore — a report, a cleanup, a check. Generate the script with a fully constrained prompt, review it line by line and note what you caught, run it in a VM with Start-Transcript and -WhatIf, then convert it into an Intune detection script (exit 0/1, silent). Assign it to one pilot device, read the transcript, and record in your library what the review caught — that list becomes your personal quality bar for every future draft.
Any frontier model drafts competent PowerShell in 2024-era syntax; the differentiators are workflow, not brand. Use the model with the best context window for long scripts and logs, prefer one grounded in Microsoft documentation (Copilot) for tenant-specific questions, and always keep a second tool for an independent review pass. Switching models monthly costs more than the difference in output quality — invest the time in prompts and review checklists instead.
It can write the drafts — detection and remediation pairs with the right exit-code contract — but deploying them is a human decision. Intune runs these scripts with SYSTEM rights on a schedule across whole device groups, so the review-and-test loop is mandatory: review the exit paths, test in a VM, assign to a pilot group, read AgentExecutor.log, then widen. The AI-written part takes minutes; the validation is what makes the script safe to assign.
Three levers. In the prompt: name the exact module and version, and add 'use only cmdlets from the Microsoft.Graph SDK 2.x; if unsure, say so'. In the review: tab-complete or Get-Command every cmdlet against the installed module — invented ones fail instantly. In the workflow: never paste a script into production before it has run once in a VM, because a hallucinated cmdlet dies at the first execution, not the tenth.