Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

PowerShell Advanced

БесплатноЗапускает вложенные скриптыНе проверен

Advanced PowerShell 7 / Windows PowerShell workarounds on Windows: parsing and quoting, native argument passing, error handling, reliable process capture…

deepseekoracleот deepseekoracle463 установки в других каталогах

Об этом скилле

PowerShell Advanced

Audited environment: PowerShell 7.6.7 (C:\Program Files\PowerShell\7\pwsh.exe) and Windows PowerShell 5.1 (C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe).

0. Know which engine you are in

$PSVersionTable
$PSVersionTable.PSEdition          # Core or Desktop
[Environment]::Is64BitProcess
$PSHOME

Rules:

  • Write for PowerShell 7 unless the target is explicitly 5.1.
  • pwsh and powershell.exe are different engines with different JSON, encoding, and parallel behavior.
  • Do not assume a module installed for 5.1 is visible in 7 (or the reverse).
  • $PSVersionTable.PSVersion.Major -ge 7 gates ForEach-Object -Parallel, ConvertFrom-Json -AsHashtable, and utf8NoBOM.

1. Parsing and quoting

PowerShell has two modes: expression and argument. The same token can mean different things.

Input Mode Result
Write-Output 2+2 argument string "2+2"
Write-Output (2+2) expression integer 4
Write-Output $a+2 argument string, e.g. "4+2"
Write-Output ($a+2) expression integer 6

Practical rules:

  • Put expressions in parentheses when passing to a command.
  • Use single quotes for literal strings, double quotes for expansion.
  • Escape $ in an expandable string with a backtick: "`$HOME".
  • Do not use backtick line continuation when a natural break exists (after |, ,, (, {, an operator). Use splatting for many parameters.
  • --% stops PowerShell parsing for a native command; use it only when needed and remember it stops at newline/pipe.
  • -- ends PowerShell parameters; for native commands it is usually passed through.
  • $PSNativeCommandArgumentPassing (7.3+) changes native quote behavior. If a native call worked in 5.1 but breaks in 7, inspect this variable.
# Preferred: splatting
$p = @{
    Path        = 'C:\Program Files\App\app.exe'
    ErrorAction = 'Stop'
}
Get-Item @p

2. Error handling

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

try {
    Get-Item -LiteralPath 'C:\missing' -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException] {
    Write-Error "Not found: $($_.Exception.Message)"
}
catch {
    Write-Error ("{0}`n{1}" -f $_.Exception.Message, $_.ScriptStackTrace)
}
finally {
    # always runs, including on many terminating paths
}

Key facts:

  • Cmdlets often emit non-terminating errors; try/catch will not see them unless -ErrorAction Stop or $ErrorActionPreference='Stop'.
  • throw creates a terminating error.
  • $ErrorActionPreference='SilentlyContinue' can suppress throw; do not use it globally in a library.
  • $? and $LASTEXITCODE are not the same. $LASTEXITCODE is for native processes.
  • catch matches exception type by inheritance; put specific catches before general ones.

3. Native process capture without deadlocks

The common failure: & tool with large stdout/stderr, or Start-Process with -Wait and redirected streams, hangs. Capture via System.Diagnostics.Process with ArgumentList for exact quoting.

Template: scripts/Invoke-SafeProcess.ps1.

$psi = [System.Diagnostics.ProcessStartInfo]::new()
$psi.FileName = 'C:\Program Files\Git\bin\git.exe'
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.CreateNoWindow = $true
$psi.ArgumentList.Add('status')
$psi.ArgumentList.Add('--short')

$p = [System.Diagnostics.Process]::new()
$p.StartInfo = $psi
[void]$p.Start()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
$p.WaitForExit()
$exit = $p.ExitCode

Rules:

  • Use ArgumentList, not a hand-built argument string, when paths/quotes matter.
  • Read stdout and stderr before WaitForExit for large output, or use async event handlers.
  • For a child that may outlive the helper, redirect to files or DEVNULL; do not leave a pipe open.
  • Start-Process -Wait waits for the process tree in some cases; Wait-Process waits for the process object only.
  • cmd /c changes quoting; avoid it when a native exe can be called directly.

4. Parallelism: choose the right tool

Need Use
A few CPU-bound jobs, PS 7 ForEach-Object -Parallel -ThrottleLimit N
Jobs needing separate runspaces Start-ThreadJob
Child process isolation Start-Job
Long-lived worker pool RunspacePool
Native process concurrency Start-Process + wait/handles
$items = 1..8
$results = $items | ForEach-Object -Parallel {
    Start-Sleep -Milliseconds 200
    [pscustomobject]@{ n = $_; pid = $PID }
} -ThrottleLimit 4
$results

Caveats:

  • -Parallel scriptblocks run in separate runspaces; variables do not flow in automatically. Use $using:name.
  • Do not mutate a shared
Полный SKILL.md на ClawHub

Установить PowerShell Advanced в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл PowerShell Advanced?

Advanced PowerShell 7 / Windows PowerShell workarounds on Windows: parsing and quoting, native argument passing, error handling, reliable process capture, parallel jobs, JSON/HTTP, encoding, ACLs, scheduled tasks, modules, Pester, and Windows-specific debugging. Use when a basic one-liner fails, output deadlocks, quoting breaks, a job hangs, or a script must be safe enough to ship.

Как установить скилл PowerShell Advanced?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл PowerShell Advanced запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить PowerShell Advanced с