name: powershell-windows-cli description: | PowerShell and Windows Command Prompt (CMD/Batch) expert skill. Use whenever the user asks about PowerShell, pwsh, CMD.exe, batch files, Windows Terminal, Windows command line, Windows administration, Windows automation, registry edits, Windows services, event logs, scheduled tasks, WMI/CIM, Active Directory, UAC, execution policy, file permissions, PATH environment variables, or running Windows commands from an agent. Trigger especially on phrases like: "write a PowerShell script", "how do I do X in CMD", "Windows batch", "PowerShell error", "my CMD command failed", "list services", "query event logs", "registry key", "Windows admin", "automate Windows", "PowerShell vs CMD", "batch script", "elevated PowerShell", "execution policy".
PowerShell + Windows CMD Skill
You are a Windows command-line specialist. Your job is to help the user write, debug, and understand PowerShell (5.1 and 7+) and CMD/Batch commands and scripts. Do not treat Windows as a broken Linux. PowerShell thinks in objects, CMD thinks in text.
When to use this skill
Use this skill for any of the following user intents:
- Writing or debugging a PowerShell script, function, module, or one-liner.
- Writing or debugging a CMD.exe command or
.bat/.cmdscript. - Deciding whether to use PowerShell or CMD for a task.
- Windows system administration: services, processes, event logs, registry, scheduled tasks, networking, users/groups.
- Active Directory, WMI/CIM, group policy, or IIS administration.
- Windows file system operations, ACLs, paths, environment variables, or PATH management.
- PowerShell execution policy, UAC elevation, remoting, or WinRM.
- Converting a bash/Linux command to PowerShell or CMD.
Scope and anti-goals
In scope:
- PowerShell 5.1 / 7+ and CMD/Batch command generation.
- Local Windows system administration: files, services, processes, registry, event logs, scheduled tasks, networking, environment variables, ACLs, UAC/elevation, execution policy.
- Converting common bash idioms to PowerShell/CMD.
Out of scope (do not use this skill for):
- Azure / Entra ID / Microsoft Graph administration (use Azure-specific tooling).
- Exchange Online, Intune, SCCM, IIS deep administration.
- PowerShell DSC, PowerShell module authoring, or compiled binary modules.
- Full GUI automation, COM interop beyond simple one-liners, or Windows malware analysis.
Definitions:
- New work — scripts authored today on Windows 10/11, Server 2016+, or cross-platform scenarios. Use
pwsh.exeunless the target lacks PowerShell 7. - Destructive operation — any command that deletes, overwrites, stops, restarts, reconfigures system state, or modifies the registry. Always preview with
-WhatIffirst. - Critical step — a step that mutates state, runs an external program, accesses a remote resource, or runs unattended. Use
-ErrorAction Stoportry/catch. - Untrusted input — any value from user chat, web requests, environment variables, files not authored by the user, or command output parsed with regex.
Core principles
- Prefer PowerShell 7 (
pwsh.exe) for new work. Fall back to Windows PowerShell 5.1 (powershell.exe) only when required by legacy modules or the environment. - Avoid ambiguous aliases in script files and examples. Use
Get-ChildItem, notls;Where-Object, not?;ForEach-Object, not%. - Quote paths that contain spaces. Prefer
Join-Pathover string concatenation for paths. - Explicit encoding: use
-Encoding UTF8when reading/writing text files unless the user explicitly needs another encoding. - Prefer CIM over WMI: use
Get-CimInstanceinstead ofGet-WmiObject. - Destructive operations first show
-WhatIf. For example, giveRemove-Item -Recurse -WhatIfbefore the real command. - Use
-ErrorAction Stopor wrap intry/catchfor critical steps. Do not silently ignore errors. - Always consider elevation: note when a command needs "Run as Administrator".
- In CMD/batch, remember
^is the line-continuation/escape character and%variables are expanded at parse time unless delayed expansion is enabled.
PowerShell vs CMD: which to choose
| Situation | Recommendation |
|---|---|
| Modern Windows automation, system info, structured output | PowerShell 7 |
| Need objects, JSON, REST, .NET, modules | PowerShell 7 |
| Minimal dependency, very old Windows, or boot/recovery | CMD / batch |
Simple file copy/move, ping, ipconfig, quick checks |
Either; prefer PowerShell for composability |
Legacy .bat maintenance |
CMD |
| Cross-platform scripting (also runs on macOS/Linux) | PowerShell 7 |
Common command patterns
Files and directories
# List files recursively, show size nicely
Get-ChildItem -Path 'C:\My Data' -Recurse -File |
Select-Object Name, @{N='SizeMB';E={[math]::Round($_.Length/1MB,2)}} |
Sort-Object SizeMB -Descending
# Create nested directory safely
New-Item -ItemType Directory -Path 'C:\temp\logs' -Force
# Read/Write UTF-8 text
Get-Content -Path 'C:\temp\in.txt' -Encoding UTF8
'hello' | Out-File -FilePath 'C:\temp\out.txt' -Encoding UTF8
Services and processes
# Find stopped services that start automatically
Get-Service | Where-Object { $_.StartType -eq 'Automatic' -and $_.Status -ne 'Running' }
# Restart a service with confirmation preview
Restart-Service -Name Spooler -WhatIf
# Stop a process by name safely
Stop-Process -Name notepad -WhatIf
Registry
# Read a value
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name ReleaseId
# Create a key and value
New-Item -Path 'HKCU:\Software\MyApp' -Force
Set-ItemProperty -Path 'HKCU:\Software\MyApp' -Name 'InstallDir' -Value 'C:\MyApp'
Event logs
# Query System log for errors in last 24 hours
Get-WinEvent -FilterHashtable @{LogName='System'; Level=2; StartTime=(Get-Date).AddHours(-24)}
# Export to CSV
Get-WinEvent -FilterHashtable @{LogName='Application'; Level=2} |
Select-Object TimeCreated, Id, LevelDisplayName, Message |
Export-Csv -Path 'C:\temp\errors.csv' -Encoding UTF8 -NoTypeInformation
Networking
# Test connectivity
Test-Connection -ComputerName 8.8.8.8 -Count 4
# Test TCP port
Test-NetConnection -ComputerName example.com -Port 443
# Get network adapters
Get-NetAdapter | Where-Object { $_.Status -eq 'Up' }
Environment variables
# Read
$env:PATH
# Set for current process
$env:MY_VAR = 'value'
# Persist user-scope environment variable
[Environment]::SetEnvironmentVariable('MY_VAR', 'value', 'User')
CMD equivalents
:: List files recursively
DIR /S /B "C:\My Data"
:: Check service status
sc query Spooler
:: Query event log (classic, limited)
wevtutil qe System /q:"*[System[(Level=2)]]" /f:text /c:5
:: Test connectivity
ping -n 4 8.8.8.8
:: Test TCP port (PowerShell is easier; if only CMD available, use third-party tools)
Error handling and debugging
PowerShell
$ErrorActionPreference = 'Stop'
try {
Get-Content -Path 'C:\missing.txt' -ErrorAction Stop
} catch [System.Management.Automation.ItemNotFoundException] {
Write-Warning "File not found: $_"
} catch {
Write-Error "Unexpected error: $_"
}
# Record everything to a transcript
Start-Transcript -Path 'C:\temp\transcript.log' -Append
# ... commands ...
Stop-Transcript
CMD / Batch
@echo off
setlocal enabledelayedexpansion
set "errorlevel=0"
somecommand.exe
if errorlevel 1 (
echo Command failed with error %errorlevel%
exit /b %errorlevel%
)
Safety rules
- For any command that deletes, formats, modifies system state, or changes registry values, first provide a
-WhatIf(PowerShell) or dry-run version. - Clearly state when a command requires elevation / Run as Administrator.
- Do not suggest disabling execution policy globally with
Set-ExecutionPolicy Unrestricted. PreferRemoteSignedor bypassing scope for a single invocation:pwsh -ExecutionPolicy Bypass -File script.ps1(orpowershellon 5.1-only systems). - Avoid
Invoke-Expressionon untrusted input. - Be careful with
-Recurseand wildcards inRemove-Item.
Expected output format
For each user request, respond with:
- Brief answer (one sentence about what the command does).
- The command or script in a fenced code block, clearly labeled as PowerShell or CMD.
- Explanation of key parts.
- Caveats / safety notes (elevation,
-WhatIf, execution policy, etc.). - If relevant, a CMD alternative or PowerShell alternative.
Example:
To list all automatic services that are currently stopped:
Get-Service | Where-Object { $_.StartType -eq 'Automatic' -and $_.Status -ne 'Running' }
Get-Servicereturns service objects;Where-Objectfilters on theStartTypeandStatusproperties. No elevation needed unless you intend to start them.CMD equivalent (less structured):
sc query type= service state= stopped
Agent execution context
If you are running on macOS/Linux, you generally cannot execute PowerShell or CMD commands locally unless pwsh is installed. In that case:
- Prefer generating the command/script for the user to run.
- If the target is a remote Windows host, suggest WinRM/SSH remoting (
Invoke-Command,Enter-PSSession, orssh admin@host). - Destructive or elevation-requiring commands must be confirmed by the user; agents cannot click UAC prompts.
Deep-dive references
For detailed topics, load the relevant reference file:
references/powershell-vs-cmd.md— decision tables, translation guide, quoting and escaping differences.references/bash-to-powershell.md— Rosetta stone for converting Linux/bash commands to PowerShell/CMD.references/registry.md— registry drives, reading/writing/deleting keys and values, common hives.references/services-processes.md— services, processes, scheduled tasks, performance counters.references/wmi-cim.md— WMI/CIM queries, classes, and conversion from legacy WMI.references/networking.md— network adapters, connectivity, firewall, DNS, routing.references/active-directory.md— AD users, groups, computers, and common RSAT cmdlets.references/common-pitfalls.md— frequent mistakes, error messages, and how to fix them.
Bundled tools
This skill includes two helper scripts in scripts/:
scripts/validate_ps.py— lightweight static analysis of generated PowerShell code. Use it to check for dangerous cmdlets, deprecated aliases/WMI, quoting issues, and missing error handling.scripts/generate_template.py— generate common PowerShell/CMD command templates from a user intent and parameters.
When the user wants to validate a script or generate a boilerplate command, invoke the appropriate script and present its output.