PromptAIPromptAI
DemoPricingCommunityBlogPromptsLog inGet Started
Prompt library/Coding

PowerShell Script Prompt for Windows Automation

A structured prompt for PowerShell scripts with parameters, error handling, and safe defaults — with a real example script.

Enhanced prompt — ready to use
ROLE
You are a senior PowerShell developer with expertise in scripting automation. Your goal is to create a robust PowerShell script tailored to the user's needs.

TASK
Write a PowerShell script based on the user's requirements. Think step by step about the script’s functionality, handle potential edge cases, and ensure the script is clear, efficient, and maintainable.

CONTEXT
The user requests a PowerShell script but has not specified the purpose, environment, or functionality. The script should be designed for general automation tasks in a Windows environment.

REQUIREMENTS
- Develop a PowerShell script following best practices for readability and error handling.
- Include comments in the script to explain key sections.
- Consider common edge cases that may affect script execution.
- Before finalizing, verify the script for correctness and completeness.
- Assumptions: Since no specific task is provided, create a sample script that demonstrates common PowerShell automation capabilities, such as file system operations or process management.

OUTPUT FORMAT
Provide the PowerShell script code in a properly formatted code block with inline comments explaining major parts. Include a brief description of the script’s functionality above the code.

That's what PromptAI produced from this vague prompt: “write a powershell script”

Example result

```powershell
<#
.SYNOPSIS
    A versatile PowerShell automation script demonstrating common tasks:
    - Validates parameters
    - Creates and cleans up directories
    - Backs up files based on extension
    - Logs script activities and errors
    - Optionally stops specified running processes

.DESCRIPTION
    This script accepts parameters to specify:
    - The target directory to scan
    - File extension filter for backup
    - Backup destination directory
    - An optional list of process names to stop
    
    It performs the following steps:
    1. Validates input parameters and environment.
    2. Creates a backup directory if it doesn't exist.
    3. Copies files matching the given extension from the target directory (recursively) to the backup directory.
    4. Deletes files older than 30 days in the backup directory.
    5. Optionally stops specified processes, handling errors if the process does not exist or cannot be stopped.
    6. Logs all actions and errors to a timestamped log file in the script directory.

.NOTES
    - Designed for Windows PowerShell 5.1+ or PowerShell Core.
    - Handles common edge cases: missing directories, access denied, no matching files, no processes found.
    - Includes error handling and verbose output.

.EXAMPLE
    .\AutomationSample.ps1 -TargetDir "C:\Data" -FileExt ".txt" -BackupDir "D:\Backup" -StopProcesses "notepad","calc"
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [ValidateScript({ Test-Path $_ -PathType 'Container' })]
    [string]$TargetDir,

    [Parameter(Mandatory=$true)]
    [ValidatePattern('^\.\w+$')] # E.g. ".txt", ".log"
    [string]$FileExt,

    [Parameter(Mandatory=$true)]
    [string]$BackupDir,

    [Parameter(Mandatory=$false)]
    [string[]]$StopProcesses
)

function Write-Log {
    param(
        [string]$Message,
        [string]$Level = "INFO"
    )
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "$timestamp [$Level] $Message"
    Write-Output $logEntry
    Add-Content -Path $Global:LogFile -Value $logEntry
}

try {
    # Initialize log file
    $Global:LogFile = Join-Path -Path $PSScriptRoot -ChildPath ("AutomationSample_{0}.log" -f (Get-Date -Format "yyyyMMdd_HHmmss"))
    Write-Log "Script started."

    # Normalize paths
    $TargetDir = (Get-Item -LiteralPath $TargetDir).FullName
    $BackupDir = Resolve-Path -Path $BackupDir -ErrorAction SilentlyContinue
    if (-not $BackupDir) {
        # Create backup directory if it does not exist
        Write-Log "Backup directory '$BackupDir' does not exist. Attempting to create."
        try {
            New-Item -Path $BackupDir -ItemType Directory -Force -ErrorAction Stop | Out-Null
            Write-Log "Backup directory created."
        } catch {
            # If $BackupDir was null, create from path string
            try {
                New-Item -Path $(Split-Path $BackupDir -Parent) -ItemType Directory -Force -ErrorAction Stop | Out-Null
                New-Item -Path $BackupDir -ItemType Directory -Force -ErrorAction Stop | Out-Null
                Write-Log "Backup directory created."
            } catch {
                throw "Failed to create backup directory '$BackupDir'. $_"
            }
        }
        $BackupDir = Resolve-Path -Path $BackupDir
    } else {
        $BackupDir = $BackupDir.Path
        Write-Log "Backup directory found at '$BackupDir'."
    }

    # Log input summary
    Write-Log "Target directory: $TargetDir"
    Write-Log "File extension filter: $FileExt"
    Write-Log "Backup directory: $BackupDir"
    if ($StopProcesses) {
        Write-Log "Processes to stop: $($StopProcesses -join ', ')"
    } else {
        Write-Log "No processes specified to stop."
    }

    # Retrieve files matching extension recursively
    Write-Log "Searching for files with extension '$FileExt' in '$TargetDir'."
    $files = Get-ChildItem -Path $TargetDir -Recurse -File -ErrorAction Stop |
             Where-Object { $_.Extension -ieq $FileExt }
    if (-not $files) {
        Write-Log "No files with extension '$FileExt' found in '$TargetDir'." "WARN"
    } else {
        Write-Log "Found $($files.Count) file(s) to backup."
    }

    # Copy files to backup directory preserving folder structure relative to TargetDir
    foreach ($file in $files) {
        # Determine relative path
        $relativePath = $file.DirectoryName.Substring($TargetDir.Length).TrimStart('\','/')
        $destinationDir = Join-Path -Path $BackupDir -ChildPath $relativePath
        if (-not (Test-Path $destinationDir)) {
            New-Item -Path $destinationDir -ItemType Directory -Force -ErrorAction Stop | Out-Null
        }
        $destinationFile = Join-Path -Path $destinationDir -ChildPath $file.Name
        try {
            Copy-Item -Path $file.FullName -Destination $destinationFile -Force -ErrorAction Stop
            Write-Log "Copied '$($file.FullName)' to '$destinationFile'."
        } catch {
            Write-Log "Failed to copy '$($file.FullName)': $_" "ERROR"
        }
    }

    # Clean up: Delete files older than 30 days in backup directory
    Write-Log "Cleaning up files older than 30 days in backup directory."
    $thresholdDate = (Get-Date).AddDays(-30)
    $oldFiles = Get-ChildItem -Path $BackupDir -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -lt $thresholdDate }
    foreach ($oldFile in $oldFiles) {
        try {
            Remove-Item -Path $oldFile.FullName -Force -ErrorAction Stop
            Write-Log "Deleted old backup file '$($oldFile.FullName)'."
        } catch {
            Write-Log "Failed to delete old backup file '$($oldFile.FullName)': $_" "ERROR"
        }
    }
    Write-Log "Cleanup complete."

    # Optionally stop processes
    if ($StopProcesses) {
        foreach ($procName in $StopProcesses) {
            try {
                $procs = Get-Process -Name $procName -ErrorAction SilentlyContinue
                if (-not $procs) {
                    Write-Log "Process '$procName' not found." "WARN"
                    continue
                }

                foreach ($proc

How to adapt it

  • •State the Windows version and whether admin rights are available.
  • •Ask for -WhatIf support on anything destructive.

Have your own rough prompt? Enhance it into a structured prompt like this in one click.

Enhance your own prompt

Or use the ChatGPT prompt enhancer right inside ChatGPT, the AI prompt enhancer for every other tool, or the prompt enhancer for Claude Code and Cursor in your editor.

More coding prompts

Code Translation Prompt That Preserves Behavior
A structured prompt that ports code between languages idiomatically, flagging behavior differences — with a real example translation.
Coding Interview Prompt for Real Practice
A structured prompt that runs mock interview drills: problem, hints on request, then review of your solution — with a real example session.
Cron Job Prompt That Gets the Schedule Right
A structured prompt that converts plain-English schedules into correct cron expressions with timezone caveats — with a real example.
Data Analysis Prompt That Finds the Story
A structured prompt that plans an analysis: questions, methods, checks, and a chart list before any code — with a real example.
Docker Compose Prompt for Multi-Service Stacks
A structured prompt that writes a compose file with services, networks, volumes, and healthchecks — with a real example file.
Excel Formula Prompt That Just Works
A structured prompt that turns a plain-English calculation into a working Excel or Sheets formula with an explanation — with a real example.
PromptAIPromptAI

Transform your ideas into powerful, structured prompts with AI.

Product

  • Try Demo
  • Pricing
  • Chrome Extension
  • Blog
  • Prompts

Company

  • About
  • Founder
  • Contact

Legal

  • Privacy Policy
  • Terms of Service
Tools
Prompt Enhancer·ChatGPT Prompt Enhancer·Prompt Optimizer·ChatGPT Prompt Generator
For Devs
Prompt Enhancer for Cursor·Prompt Enhancer for Claude Code
Compare
AIPRM Alternative·PromptPerfect Alternative

© 2026 PromptAI. All rights reserved.

PromptAI 360 - ⌘⇧P in Cursor, Claude Code etc, get structured prompt in 2 | Product Hunt