---
title: "Write PowerShell Scripts With AI: AD, Entra, Intune, dbatools"
url: "https://goremy.ai/blog/articles/write-and-debug-powershell-scripts-with-ai"
author: Luis Chavez-Mattos
editor: Luis Chavez-Mattos
editor_title: Director, Product
published: "2026-11-16T19:40:12.690Z"
updated: "2026-11-16T19:40:12.690Z"
topic: Cybersecurity and IT Systems
description: How to write and debug PowerShell scripts with AI for Active Directory, Entra ID, Intune, dbatools and desktop support, with prompts and a safety checklist.
---

# Write PowerShell Scripts With AI: AD, Entra, Intune, dbatools

> How to write and debug PowerShell scripts with AI for Active Directory, Entra ID, Intune, dbatools and desktop support, with prompts and a safety checklist.

Edited by Luis Chavez-Mattos, Director, Product · Published 2026-11-16

## How do you write PowerShell scripts with AI?

Describe the task to an AI assistant in plain English, and include four things: what you want done, which system it touches (Active Directory, Entra ID, Intune, SQL Server, a Windows PC), which PowerShell version and modules you have, and what the output should look like. Ask for a read-only version first, with `-WhatIf` on anything that changes data. Then read the script, check every cmdlet exists, and run it on a test object before it touches production.

AI is good at the first draft and at explaining unfamiliar code. It is unreliable at exact cmdlet names, parameters and permissions. Your job is to supply context and verify.

## TL;DR

- **Give the AI your environment**, not just your goal: PowerShell 5.1 or 7, which modules are installed, whether the target is on-prem AD or Entra ID, and the exact output you want.
- **Ask for read-only first.** A report that lists the accounts or devices it would change is the safest first draft of any script.
- **Verify every cmdlet** with `Get-Command` and `Get-Help` before you run anything, because AI invents plausible cmdlets and parameters.
- **For debugging, paste the full error, the script and your version info.** A pasted fragment gets a guess. The whole picture gets a diagnosis.
- **Use Microsoft Graph PowerShell for Entra and Intune.** The older AzureAD and MSOnline modules are deprecated, and AI trained on older examples still suggests them.
- **Never paste secrets or real user data** into a chat tool, and follow your company's AI policy.

## What do you need to give the AI to get a script that works?

Most bad AI scripts come from a vague prompt. "Write a script to disable old users" leaves the AI guessing about where the users live, what "old" means and what you want logged. Use this prompt template and fill in the brackets.

```
You are helping a Windows/identity administrator write a PowerShell script.

Goal: [what the script should do, in one or two sentences]
Target system: [on-prem Active Directory / Entra ID / Intune / SQL Server / local Windows PC]
Environment: [Windows PowerShell 5.1 or PowerShell 7.x], modules available: [ActiveDirectory, Microsoft.Graph, dbatools, none]
Scope: [one OU, one group, one server, a list from a CSV]
Output: [CSV report with these columns / console summary / log file]
Safety: Make the first version read-only. Any command that changes data must support -WhatIf and -Confirm. Do not hardcode credentials. Add error handling and tell me what permissions or Graph scopes are needed.

Return: 1) the script, 2) a plain-English explanation of each section, 3) the cmdlets you used so I can verify them, 4) what could go wrong.
```

The last line matters. Asking the AI to list the cmdlets it used gives you a verification checklist, and asking what could go wrong surfaces assumptions it made silently.

## How do you write Entra ID PowerShell scripts with AI?

Entra ID scripting now runs through the Microsoft Graph PowerShell SDK (the `Microsoft.Graph` modules). The older `AzureAD` and `MSOnline` modules are deprecated, and Microsoft points admins to Graph instead. If an AI hands you `Get-AzureADUser` or `Get-MsolUser`, tell it to rewrite using Microsoft Graph PowerShell.

Graph also uses permission scopes. You sign in with `Connect-MgGraph -Scopes "..."`, and the scopes you request decide what the script can read or change. Ask the AI to name the least-privileged scopes, and check them against Microsoft's Graph permissions reference.

**Worked example: find stale guest accounts.**

Prompt:

```
Write a PowerShell script using the Microsoft Graph PowerShell SDK that lists Entra ID guest users who have not signed in for 90 days or have never signed in. Read-only. Export to CSV with display name, email, created date and last sign-in date. Tell me which Graph scopes are required and any licensing caveats.
```

A good response looks like this:

```powershell
Connect-MgGraph -Scopes "User.Read.All","AuditLog.Read.All"

$cutoff = (Get-Date).AddDays(-90)

Get-MgUser -Filter "userType eq 'Guest'" -All `
    -Property Id,DisplayName,Mail,CreatedDateTime,SignInActivity |
  Where-Object {
    -not $_.SignInActivity.LastSignInDateTime -or
    $_.SignInActivity.LastSignInDateTime -lt $cutoff
  } |
  Select-Object DisplayName, Mail, CreatedDateTime,
    @{n='LastSignIn'; e={ $_.SignInActivity.LastSignInDateTime }} |
  Export-Csv .\stale-guests.csv -NoTypeInformation
```

What to check:

1. **Scopes.** Reading sign-in activity needs an audit log permission, which is why `AuditLog.Read.All` is there.
2. **Licensing.** Sign-in activity data generally requires an Entra ID P1 or P2 license in the tenant. If the column comes back empty, that is the first thing to check.
3. **Logic.** "Never signed in" also catches guests invited yesterday. Ask the AI to exclude accounts created in the last 30 days.
4. **Cmdlet names.** Run `Get-Command Get-MgUser` and `Get-Help Get-MgUser -Parameter Property` to confirm they exist in your installed version.

Only after you review the CSV with the guest owners should you ask for a second script that disables (not deletes) the accounts, with `-WhatIf` support.

## How do you write Active Directory scripts with AI?

For on-prem Active Directory, the `ActiveDirectory` module (part of RSAT) is the standard. It has stable, well-documented cmdlets such as `Get-ADUser`, `Get-ADGroupMember`, `Search-ADAccount` and `Set-ADAccountPassword`, so AI tends to do well here.

Common asks that work well:

- Report enabled accounts inactive for 90 days: `Search-ADAccount -AccountInactive -UsersOnly -TimeSpan 90.00:00:00`, filtered to enabled accounts.
- Bulk-create users from a CSV, with a naming convention you specify.
- Audit nested group membership for a sensitive group.
- Report accounts with passwords set to never expire.

Two things trip people up. First, AI often uses `-Filter *` and then filters with `Where-Object`, which is slow in a large directory. Ask it to "filter on the server side with `-Filter` or `-LDAPFilter` and limit properties with `-Properties`." Second, always set `-SearchBase` to one test OU while you develop, and have the AI make that a parameter.

## How do you write Intune scripts with AI?

Intune has two different jobs, and AI mixes them up if you don't say which one you mean.

**Scripts that run on devices.** These are PowerShell scripts you upload to Intune to run on managed Windows PCs, for detection, remediation, or configuration. Tell the AI they will run on the endpoint, often under the system account, with no user interaction. That changes how it handles paths, prompts and output. Ask for a detection script that exits 0 when compliant and 1 when not, and a matching remediation script.

**Scripts that manage Intune.** These run from your admin machine and use Microsoft Graph, for example listing managed devices, finding non-compliant ones or triggering a sync. The device management cmdlets live in the Graph SDK (`Get-MgDeviceManagementManagedDevice` is the one most people start with). Graph cmdlet names are long and change between versions, so verify them with `Get-Command *ManagedDevice*` before trusting the draft.

A prompt that works:

```
Write a PowerShell script using Microsoft Graph PowerShell that lists Intune managed Windows devices that have not checked in for 30 days. Read-only. Output a CSV with device name, primary user, OS version, last sync time. State the Graph scopes needed.
```

## How do you write dbatools PowerShell scripts with AI?

dbatools is a free, open-source PowerShell module for SQL Server administration. It has hundreds of commands, all prefixed with `Dba`, so AI can name many of them correctly, but the volume also leads to confident mistakes. Install it with `Install-Module dbatools` and confirm commands with `Get-Command -Module dbatools *Backup*`.

Useful starting points, all of which AI can wire together for you:

| Task | Commands to ask about |
|---|---|
| Check database sizes and status | `Get-DbaDatabase` |
| See when each database was last backed up | `Get-DbaLastBackup` |
| Prove backups actually restore | `Test-DbaLastBackup` |
| Migrate logins between servers | `Copy-DbaLogin` |
| Run a query across many servers | `Invoke-DbaQuery` |
| Check free disk space | `Get-DbaDiskSpace` |

Prompt:

```
Using the dbatools module, write a PowerShell script that reads a list of SQL Server instances from servers.txt and reports any user database whose last full backup is older than 7 days. Read-only. Output to CSV. Use Windows authentication. Tell me which dbatools commands you used.
```

Where to be careful: restore, copy and migrate commands can overwrite things. Ask the AI to explain each parameter it uses on those, read the dbatools help for them (`Get-Help Restore-DbaDatabase -Full`), and test against a non-production instance. Also check module version: older blog posts the AI learned from may use parameters that have changed.

## What PowerShell scripts help desktop support?

Desktop support scripts are the best place to start with AI because they are small, local and easy to test on your own machine. Good candidates:

- A one-click health check: uptime, free disk space, pending reboot, last installed updates, network reachability.
- Clearing browser or temp caches for a user profile.
- Restarting a stuck service (print spooler, a VPN client) with a log entry.
- Collecting diagnostic info into one text file a user can email you.
- Checking whether a PC can reach a server and port with `Test-NetConnection`.

Prompt:

```
Write a PowerShell 5.1 script for helpdesk use that runs on a local Windows 11 PC and prints a health summary: hostname, current user, uptime, free space on C:, last 5 installed hotfixes, whether a reboot is pending, and whether the machine can reach [internal server] on port 443. Save the same output to a text file on the desktop. No changes to the system. Use CIM cmdlets, not WMI.
```

The "CIM cmdlets, not WMI" line is a good habit. `Get-CimInstance` replaced the older `Get-WmiObject`, which doesn't exist in PowerShell 7. Specifying the PowerShell version avoids a script that works on your machine and fails on a colleague's.

## How do you debug a PowerShell script with AI?

AI is often better at debugging than writing, because it has real text to work from. Use this prompt:

```
This PowerShell script fails. Diagnose it.

Environment: [output of $PSVersionTable.PSVersion], [OS], running as [admin / standard user / SYSTEM]
Modules and versions: [output of Get-Module -ListAvailable Microsoft.Graph*, dbatools, ActiveDirectory | Select Name, Version]

Script:
[paste full script, with secrets and real names removed]

Error (full text, including the line number and category info):
[paste]

What I expected: [...]
What happened: [...]

Explain the cause in plain English first, then give the corrected code, then tell me how to confirm the fix.
```

Tips that save time:

- **Use `$Error[0] | Format-List * -Force`** to get the full error and paste that, not the red summary line.
- **Add `-ErrorAction Stop`** inside `try/catch` so failures are visible instead of silently skipped. Ask the AI to add this.
- **Ask for debug output**, such as `Write-Verbose` lines, then run with `-Verbose` and paste what you see back.
- **Change one thing at a time.** If the AI rewrites the whole script, ask it to show only the changed lines and why.
- **If the same fix fails twice**, start a fresh chat with the original script and error. Long conversations accumulate wrong assumptions.

## Where should you not trust AI-written PowerShell?

| Risk | What it looks like | How to catch it |
|---|---|---|
| Invented cmdlets or parameters | `Get-MgUserLastSignIn` sounds right, doesn't exist | `Get-Command`, `Get-Help` |
| Deprecated modules | `AzureAD`, `MSOnline`, `Get-WmiObject` | Ask for Graph and CIM; search the module name plus "deprecated" |
| Wrong permissions | Script asks for broad scopes like `Directory.ReadWrite.All` | Ask for least privilege and check Microsoft's permissions reference |
| Destructive defaults | `Remove-`, `Set-`, `Disable-` with `-Force` and no `-WhatIf` | Read every line with a verb that changes something |
| Silent partial success | Errors swallowed by `-ErrorAction SilentlyContinue` | Search for it and remove it |
| Hardcoded secrets | Passwords or client secrets in the script | Use a secrets store or interactive sign-in |
| Version mismatch | Syntax that only works in PowerShell 7 | State your version in the prompt |

## What is a safe workflow for running AI-written scripts?

1. **Check policy.** Confirm your company allows AI tools for this work. Remove tenant IDs, hostnames, usernames and anything sensitive from what you paste.
2. **Prompt with context** using the template above.
3. **Read the script and the explanation.** If you can't explain a line, ask the AI to explain it, then check the explanation against Microsoft's or dbatools' documentation.
4. **Verify cmdlets** with `Get-Command` and `Get-Help`.
5. **Run read-only** against a test OU, test device group or non-production instance.
6. **Use `-WhatIf`** on the changing version and review what it says it would do.
7. **Run small.** Five objects, then fifty, then everything.
8. **Log and keep it.** Save the script in source control or a shared repo with a comment on what it does and who reviewed it.

## Can you turn a pile of scripts into something your team can actually use?

Scripts solve the task, but they don't track who asked, who approved, or what happened. If your team gets offboarding requests by email and keeps the results in a spreadsheet, you may want a small internal tool in front of the scripts: a request form, an approval step, a status board and a history of what was run. [Remy](https://goremy.ai) builds full-stack apps from a plain-English description, with a database and sign-in included, so you could describe that request tracker and own the result. Keep PowerShell for the work on your directories and devices. The app handles the paperwork around it.

## Frequently Asked Questions

### Can AI write PowerShell scripts for Active Directory and Entra ID?

Yes. Both are well documented, so AI drafts are usually close. Expect to correct cmdlet names, Graph scopes and licensing assumptions. Always specify whether you mean on-prem Active Directory or Entra ID, and ask for Microsoft Graph PowerShell rather than the deprecated AzureAD or MSOnline modules.

### Is it safe to paste my script into ChatGPT or another AI tool?

Only if your company's policy allows it, and only after removing secrets, tenant IDs, real usernames and server names. Replace them with placeholders like `contoso.com` and `server01`. The logic is what the AI needs, not your real data.

### Why does the AI give me cmdlets that don't exist?

AI predicts text that looks right, and PowerShell cmdlet names follow predictable Verb-Noun patterns, so invented ones look plausible. Graph and dbatools have very large command sets that change between versions. Check each cmdlet with `Get-Command` and read `Get-Help` before running.

### Do I need to know PowerShell to use AI for it?

Basic knowledge helps a lot, because you are the safety check. If you are new, start with read-only desktop and reporting scripts, ask the AI to explain every line, and learn the verbs that change things (`Set`, `Remove`, `Disable`, `Restart`) so you know what to review.

### Where do dbatools scripts differ from regular PowerShell?

dbatools is a module, not part of Windows. You install it from the PowerShell Gallery, and its commands all start with `Dba`. The scripting approach is the same, but AI should cite specific dbatools commands, and you should check their parameters in the dbatools help for your installed version.
