Cloud Engineer Lab
Cloud Engineer Lab
Cloud Engineer Lab
Cloud Engineer Lab
© 2026
The Prompt I Use to Write PowerShell Scripts with ChatGPT (And Why It Works)

The Prompt I Use to Write PowerShell Scripts with ChatGPT (And Why It Works)

Most people ask ChatGPT to write PowerShell the wrong way and get generic, untested code. This guide shows the exact prompt structure I use to get production-quality scripts first time — including the four elements that make the difference.

9 min read
Share

The first time I asked ChatGPT to write a PowerShell script, I got something that looked right but did not work. The variable names were inconsistent, the error handling was missing, and it used an old API method that had been deprecated.

The second time, I wrote a better prompt. The script ran first time with no changes needed.

The difference was not ChatGPT getting smarter — it was me asking better.

This guide shows you the exact prompt structure I use when writing PowerShell scripts with AI, why each part matters, and how to adapt it to your own use cases.


Why Most PowerShell Prompts Fail

Most people type something like this:

"Write a PowerShell script to get non-compliant Intune devices"

That prompt is missing four critical pieces of information:

  • Context — what environment is this for? What modules are available?
  • Constraints — should it work without interactive login? What PowerShell version?
  • Output format — what should the script produce? CSV? On-screen table? Email?
  • Error handling — what should happen if the API call fails or returns no results?

Without these details, ChatGPT fills in the gaps with assumptions — and those assumptions are often wrong for your specific situation.


The Four Elements of a Good PowerShell Prompt

Role — tell it what kind of expert to act as
Context — describe your environment and constraints
Task — describe exactly what the script should do
Output requirements — format, error handling, comments

Let me show you each element and then combine them into the full prompt.


Element 1: Role

Start by telling ChatGPT what kind of expert to act as. This sets the tone and expertise level for the entire response.

Act as a senior Microsoft 365 and PowerShell engineer with deep experience 
in Microsoft Graph API, Microsoft Intune, and enterprise IT automation.

This matters because ChatGPT adjusts its responses based on the role. A "senior engineer" response will use better patterns, proper error handling, and professional variable naming. A response without a role tends to be more beginner-level.


Element 2: Context

Describe your environment so ChatGPT knows what tools and constraints apply.

Environment:
- PowerShell 7.4 on Windows Server 2022
- Microsoft.Graph PowerShell module (latest version) is installed
- The script will run unattended via Windows Task Scheduler — no interactive login
- Authentication: Entra ID App Registration with Client ID, Tenant ID, and Client Secret
- The script needs to work on tenants with up to 10,000 devices

Without this context, ChatGPT might:

  • Use Connect-MgGraph with interactive login (breaks scheduled tasks)
  • Use the old AzureAD module instead of Microsoft.Graph
  • Not handle pagination (breaking on tenants with more than 1,000 devices)

Element 3: Task

Describe what the script should actually do, in clear steps.

Task:
Write a PowerShell script that does the following:
1. Connects to Microsoft Graph using a Client Secret credential (no browser popup)
2. Retrieves ALL managed devices from Microsoft Intune (use -All to handle pagination)
3. Filters for devices where ComplianceState is "noncompliant"
4. Selects these fields: DeviceName, UserPrincipalName, OperatingSystem, OsVersion, 
   LastSyncDateTime, ComplianceState, Manufacturer, Model
5. Exports the results to a CSV file at C:\Reports\NonCompliant_Report.csv
6. Prints a summary to the console showing total devices scanned and non-compliant count
7. Disconnects from Microsoft Graph when done

The numbered list is important. It gives ChatGPT a clear sequence to follow and makes it easy for you to verify that each requirement was met.


Element 4: Output Requirements

Tell it exactly how to write the code — style, comments, and error handling.

Requirements for the code:
- Add clear comments explaining what each section does
- Use proper error handling with try/catch blocks
- Use meaningful variable names (not $x, $data, $temp)
- If the CSV export folder does not exist, create it automatically
- If no non-compliant devices are found, write a message to the console and exit cleanly
- Do not use deprecated cmdlets or modules

The Full Prompt (Copy and Use This)

Here is the complete prompt combined, ready to paste into ChatGPT or Copilot:

Act as a senior Microsoft 365 and PowerShell engineer with deep experience 
in Microsoft Graph API, Microsoft Intune, and enterprise IT automation.

Environment:
- PowerShell 7.4 on Windows Server 2022
- Microsoft.Graph PowerShell module (latest version) is installed
- The script will run unattended via Windows Task Scheduler — no interactive login
- Authentication: Entra ID App Registration with Client ID, Tenant ID, and Client Secret
- The script needs to work on tenants with up to 10,000 devices

Task:
Write a PowerShell script that does the following:
1. Connects to Microsoft Graph using a Client Secret credential (no browser popup)
2. Retrieves ALL managed devices from Microsoft Intune (use -All to handle pagination)
3. Filters for devices where ComplianceState is "noncompliant"
4. Selects these fields: DeviceName, UserPrincipalName, OperatingSystem, OsVersion, 
   LastSyncDateTime, ComplianceState, Manufacturer, Model
5. Exports the results to a CSV file at C:\Reports\NonCompliant_Report.csv
6. Prints a summary to the console showing total devices scanned and non-compliant count
7. Disconnects from Microsoft Graph when done

Requirements for the code:
- Add clear comments explaining what each section does
- Use proper error handling with try/catch blocks
- Use meaningful variable names (not $x, $data, $temp)
- If the CSV export folder does not exist, create it automatically
- If no non-compliant devices are found, write a message to the console and exit cleanly
- Do not use deprecated cmdlets or modules

Save this template somewhere. Replace the Environment section and Task section for each new script request. The Role and Requirements sections stay the same almost every time.


What the Improved Prompt Gets You

When I run this prompt compared to a vague one, here is what changes:

Vague PromptDetailed Prompt
Uses interactive login (Connect-MgGraph with browser)Uses Client Secret for unattended auth
No error handlingTry/catch on every major operation
Single letter variable namesDescriptive names: $AllDevices, $NonCompliantDevices
Missing paginationUses -All flag correctly
No folder checkCreates output folder if missing
No summary outputPrints device counts to console
May use deprecated AzureAD moduleUses Microsoft.Graph module only

How to Adapt This Template for Other Tasks

The same four-element structure works for any PowerShell task. Here are the parts to swap out:

For an Autopilot deployment script:

Task:
Write a PowerShell script that:
1. Reads a CSV file of device serial numbers from C:\Devices\import.csv
2. Registers each device in Windows Autopilot via Microsoft Graph
3. Assigns the devices to the "Corporate-Autopilot" deployment profile
4. Logs success or failure for each device to a separate log file

For a Teams channel report:

Task:
Write a PowerShell script that:
1. Connects to Microsoft Graph
2. Gets all Teams in the tenant where the last activity was more than 90 days ago
3. Exports Team name, owner email, and last activity date to CSV

The structure is always the same. Only the Task section changes.


Iterating on the Output

Even with a great prompt, ChatGPT's first response is a starting point, not always a finished product. Here is how I iterate:

Run the script in a test environment first

Never run AI-generated scripts directly in production. Run it in a dev tenant or against a small test group first and verify the output looks correct.

Ask for specific changes, not rewrites

If something is wrong, be specific: "The LastSyncDateTime is showing as UTC. Convert it to local time before exporting." Do not say "fix the date problem" — that is too vague.

Ask it to explain sections you do not understand

Paste a section of the generated code and say: "Explain what this block does, line by line." This helps you understand and maintain the script later.

Ask for edge cases

Say: "What could go wrong with this script in a production environment with 8,000 devices? What would you add to make it more robust?" ChatGPT is good at spotting its own gaps when asked directly.


A Note on Trusting AI-Generated Code

AI-generated PowerShell is a productivity tool, not a replacement for understanding what the code does.

Before running any AI-generated script against your production Intune environment:

  • Read through the whole script and make sure you understand each section
  • Check that the Graph API permissions requested match what your App Registration has
  • Test with a small scope first (one device, one user) before running at scale
  • Review the output before treating it as accurate data

ChatGPT sometimes uses Microsoft Graph API endpoints or cmdlet parameters that have changed or do not exist. Always test before trusting. The Microsoft Graph documentation at learn.microsoft.com is your source of truth for what is actually available.


Summary

The difference between a useless AI prompt and a useful one comes down to four things:

  • Role — tell it what expert to act as
  • Context — describe your environment and constraints
  • Task — list exactly what the script must do, step by step
  • Output requirements — specify comments, error handling, and variable style

Use the template in this guide as your starting point. Swap out the Task section for whatever you are building. Test the output before using it in production.

AI does not replace your knowledge of PowerShell and Microsoft Graph — it just removes the time spent on boilerplate so you can focus on the logic that actually matters.

CChetan Yamger

Written by

Chetan Yamger

Cloud Engineer · AI Automation Architect · Blogger

Cloud Engineer and AI Automation Architect with deep expertise in Azure, Intune, PowerShell, and AI-driven workflows. I use ChatGPT, Gemini, and prompt engineering to build intelligent automation that improves productivity and decision-making in real IT environments.

AI AutomationAzure & IntunePowerShell & PythonNode.js / Next.jsApplication PackagingPower BIGeminiVDI / WVDGitHub ActionsM365Graph APIPrompt Engineering
Newsletter

Stay in the loop.
New articles, straight to you.

Deep-dive technical articles on Intune, PowerShell, and AI — no noise, no spam.

New article notifications
No spam, ever
Free forever

Discussion

Share your thoughts — your email stays private

Leave a comment

0/2000

Your email is used to prevent spam and will never be displayed.