☕ Buy a Coffee
Home / Productivity & Coding

Use 'ChatGPT' to Write a PowerShell Script for You

Prompt engineering techniques to generate robust, error-handled PowerShell administration scripts with parameter validation.

Sachin Siju
Sachin Siju
Lead Systems Engineer & Tech Blogger
Jul 17, 2026 4 min read
Use 'ChatGPT' to Write a PowerShell Script for You

ChatGPT as a PowerShell Force Multiplier

ChatGPT is genuinely good at generating PowerShell — the language is well-represented in its training data, the syntax is verbose and pattern-heavy (which LLMs handle well), and admin scripting tasks tend to follow recognizable shapes. The gap between a mediocre generated script and a genuinely reusable one almost always comes down to how you prompt it. A vague ask gets you a fragile one-liner; a specific ask gets you something with proper error handling and parameter validation.

Writing a Prompt That Gets Useful Output

A weak prompt like "write a PowerShell script to check disk space" will get you something that runs once, on your exact machine, with no error handling. Instead, specify the shape of the script you actually need:

  • Input/output contract: What parameters does it take? What does it return or print?
  • Target environment: Windows Server 2019/2022? PowerShell 5.1 or 7+? Domain-joined machines only?
  • Error handling expectations: Should it stop on error, log and continue, or retry?
  • Output format: Console table, CSV export, JSON, or pipeline objects for further processing?

A well-formed prompt looks like this:

Write a PowerShell script (targeting PowerShell 5.1, compatible with Windows
Server 2019+) that checks free disk space on all fixed drives across a list
of remote computers. Requirements:
- Accept a -ComputerName parameter that takes an array of hostnames, and a
  -ThresholdPercent parameter defaulting to 15.
- Use [CmdletBinding()] and proper parameter validation (ValidateNotNullOrEmpty).
- Wrap remote calls in try/catch and log unreachable hosts to a warning
  stream instead of halting the whole run.
- Output a PSCustomObject per drive with ComputerName, Drive, FreeGB,
  TotalGB, PercentFree, and a Status field (OK/Warning) based on the
  threshold.
- Include comment-based help (.SYNOPSIS, .PARAMETER, .EXAMPLE).

What a Well-Specified Prompt Produces

With that level of detail, you get something close to production-ready rather than a demo:

function Get-DiskSpaceReport {
    <#
    .SYNOPSIS
        Reports free disk space on fixed drives across one or more computers.
    .PARAMETER ComputerName
        One or more hostnames to query.
    .PARAMETER ThresholdPercent
        Percent free space below which a drive is flagged as Warning.
    .EXAMPLE
        Get-DiskSpaceReport -ComputerName srv01,srv02 -ThresholdPercent 20
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string[]]$ComputerName,

        [ValidateRange(1,99)]
        [int]$ThresholdPercent = 15
    )

    foreach ($computer in $ComputerName) {
        try {
            $drives = Get-CimInstance -ClassName Win32_LogicalDisk `
                -ComputerName $computer -Filter "DriveType=3" -ErrorAction Stop

            foreach ($drive in $drives) {
                $percentFree = [math]::Round(($drive.FreeSpace / $drive.Size) * 100, 1)
                [PSCustomObject]@{
                    ComputerName = $computer
                    Drive        = $drive.DeviceID
                    FreeGB       = [math]::Round($drive.FreeSpace / 1GB, 2)
                    TotalGB      = [math]::Round($drive.Size / 1GB, 2)
                    PercentFree  = $percentFree
                    Status       = if ($percentFree -lt $ThresholdPercent) { "Warning" } else { "OK" }
                }
            }
        }
        catch {
            Write-Warning "Could not reach $computer`: $($_.Exception.Message)"
        }
    }
}

Iterating Instead of Accepting the First Draft

Treat the first response as a draft, not a final answer. Follow up with targeted refinement requests rather than regenerating from scratch:

  • "Add a -ExportCsv switch that writes the results to a timestamped CSV if specified."
  • "Convert the remote query to use a runspace pool so it checks all computers in parallel instead of sequentially."
  • "Add #Requires -Version 5.1 and a check that the caller has appropriate remote WMI permissions before running."

This iterative loop — generate, run, report back what broke or what's missing, refine — consistently produces better scripts than trying to write one perfect prompt up front.

Always Review Before Running

Warning: Never run AI-generated PowerShell against production systems without reading it line by line first, especially anything involving Remove-Item, Set-ADUser, registry edits, or remote invocation (Invoke-Command, Enter-PSSession). LLMs occasionally hallucinate cmdlet parameters that don't exist, or generate destructive defaults (like recursive deletes without a confirmation prompt) that look plausible but are dangerous.

A few things worth checking specifically:

  • Cmdlet parameters actually exist. Run Get-Help <cmdlet> -Full or check Microsoft Learn if a parameter name looks unfamiliar.
  • Destructive actions have safeguards. Confirm -WhatIf support is present and test with it before running for real: ./script.ps1 -WhatIf.
  • Credentials aren't hardcoded. AI-generated examples sometimes embed a plaintext password for illustration — swap that for Get-Credential or a secrets vault reference.

Test in a Safe Environment First

Run generated scripts against a single non-critical test machine or a VM snapshot before rolling out to a full fleet. Add -WhatIf and -Confirm support (via [CmdletBinding(SupportsShouldProcess)]) to any script that modifies system state, and ask ChatGPT specifically to add that support if it didn't include it — it's a one-line follow-up request that adds a real safety net.

Wrap-Up

ChatGPT turns "write me a script" into a fast first draft, but the quality gap between a toy script and a real admin tool is closed by you: specify the parameters, error handling, and output format up front, iterate with follow-up prompts instead of accepting the first answer, and always review the generated code — especially anything destructive — before it touches a production system.

Featured Infrastructure Partner

Deploy on High-Performance Hostinger Cloud

Get up to 75% OFF + free domain & SSL. Powering xube.me's sub-second response times.

Claim Discount ↗

Discussion & Insights

Related Technical Essays