← 返回
效率工具 中文

PowerShell Reliable Execution

Execute PowerShell commands reliably on Windows. Avoid &&, handle parameter parsing, recover from interruptions, and ensure cross-session continuity.
在Windows上可靠执行PowerShell命令。避免使用&&,处理参数解析,支持中断恢复,并确保跨会话连续性。
dalomeve
效率工具 clawhub v1.0.0 1 版本 99908.6 Key: 无需
★ 0
Stars
📥 1,093
下载
💾 87
安装
1
版本
#latest

概述

PowerShell Reliable Execution

Execute commands reliably on Windows PowerShell. Avoid common pitfalls like && chaining, parameter swallowing, and session interruptions.

Problem Statement

Windows PowerShell differs from bash in critical ways:

IssueBashPowerShellSolution
-----------------------------------
Command chainingcmd1 && cmd2cmd1 -ErrorAction Stop; if ($?) { cmd2 }Use semicolons + error handling
Parameter parsing-arg value-Argument value (case-insensitive)Use full parameter names
Path separators/\ (or / in some cmdlets)Use Join-Path
Output redirection> >>> >> (encoding issues)Use Out-File -Encoding UTF8
Environment vars$VAR$env:VARUse $env: prefix

Core Patterns

1. Safe Command Chaining

Wrong:

mkdir test && cd test && echo done

Right:

$ErrorActionPreference = 'Stop'
try {
    New-Item -ItemType Directory -Path test -Force
    Set-Location test
    Write-Host 'done'
} catch {
    Write-Error "Failed: $_"
    exit 1
}

2. Parameter Safety

Wrong:

git commit -m "message"

Right:

git commit -Message "message"
# Or use splatting:
$params = @{ Message = "message" }
git commit @params

3. Path Handling

Wrong:

$path = "C:/Users/name/file.txt"

Right:

$path = Join-Path $env:USERPROFILE "file.txt"
# Or use literal paths:
$path = 'C:\Users\name\file.txt'

4. Output Encoding

Wrong:

echo "text" > file.txt

Right:

"text" | Out-File -FilePath file.txt -Encoding UTF8

5. Session Continuity

For long-running commands:

# Start background job
$job = Start-Job -ScriptBlock {
    param($arg)
    # Long operation
} -ArgumentList $arg

# Wait with timeout
Wait-Job $job -Timeout 300

# Get results
if ($job.State -eq 'Completed') {
    Receive-Job $job
} else {
    Stop-Job $job
    Write-Warning "Job timed out"
}

Error Recovery

Retry Pattern

function Invoke-Retry {
    param(
        [scriptblock]$Command,
        [int]$MaxAttempts = 3,
        [int]$DelaySeconds = 2
    )
    
    $attempt = 0
    while ($attempt -lt $MaxAttempts) {
        try {
            $attempt++
            return & $Command
        } catch {
            if ($attempt -eq $MaxAttempts) { throw }
            Start-Sleep -Seconds $DelaySeconds
        }
    }
}

# Usage
Invoke-Retry -Command { Invoke-WebRequest -Uri $url } -MaxAttempts 3

Interruption Recovery

# Checkpoint pattern
$checkpointFile = ".checkpoint.json"

if (Test-Path $checkpointFile) {
    $state = Get-Content $checkpointFile | ConvertFrom-Json
    Write-Host "Resuming from step $($state.step)"
} else {
    $state = @{ step = 0 }
}

switch ($state.step) {
    0 { 
        # Step 1
        $state.step = 1
        $state | ConvertTo-Json | Out-File $checkpointFile
    }
    1 {
        # Step 2
        Remove-Item $checkpointFile
    }
}

Privacy Security

All execution is local:

  • NO command logging to external services
  • NO credential capture in scripts
  • NO automatic upload of execution results
  • Sensitive data handled via [SecureString]
  • Checkpoint files stored in working directory only

Sensitive Data Filter:

Before writing any checkpoint or log:

  • Exclude Password, Token, Secret, ApiKey
  • Use [SecureString] for credentials
  • Never echo sensitive variables

Executable Completion Criteria

A PowerShell command execution is reliable if and only if:

CriteriaVerification
-----------------------
No && chainingSelect-String '&&' script.ps1 returns nothing
Error handling present`Select-String 'trycatchErrorAction' script.ps1` matches
Paths use Join-Path`Select-String 'Join-Path\\$env:' script.ps1` matches
Output encoding specifiedSelect-String 'Out-File.*Encoding' script.ps1 matches
Checkpoint for long opsCheckpoint file pattern present for ops > 60s
No hardcoded secrets`Select-String 'passwordtokensecret' script.ps1` returns nothing

Quick Reference

Common Cmdlet Mappings

TaskBashPowerShell
------------------------
List filesls -laGet-ChildItem -Force
Change dircd /pathSet-Location C:\path
Create dirmkdir xNew-Item -ItemType Directory x
Copy filecp a bCopy-Item a b
Move filemv a bMove-Item a b
Deleterm xRemove-Item x
View filecat xGet-Content x
Edit filevim xnotepad x
Find textgrep xSelect-String x
Pipe`\``\` (same)
Redirect>> (use Out-File)

Splatting Template

$params = @{
    Path = $filePath
    Encoding = 'UTF8'
    Force = $true
}
Set-Content @params

References


Execute reliably. Recover gracefully.

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-03-29 20:17 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

productivity

Word / DOCX

ivangdavila
创建、检查和编辑 Microsoft Word 文档及 DOCX 文件,支持样式、编号、修订记录、表格、分节符及兼容性检查等功能。
★ 438 📥 147,277
data-analysis

Ui Design Optimizer

dalomeve
利用本地样式、色彩和排版数据集,生成实用的UI设计系统及起始页面。适用于落地页或仪表盘UI的规划与实现。
★ 0 📥 1,155
productivity

Nano Pdf

steipete
使用nano-pdf CLI通过自然语言指令编辑PDF
★ 275 📥 114,753