You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell错误日志问题:捕获错误后无法继续执行脚本

PowerShell装机脚本错误日志与继续执行问题解决方案

问题分析

  1. 错误后无法继续执行:原代码将整个装机逻辑放在单个Try块中,一旦触发错误就会跳出Try块进入Catch,随后直接执行脚本末尾代码,无法继续后续步骤。
  2. 部分错误未写入日志:默认情况下PowerShell仅捕获终止错误,非终止错误不会触发Catch;同时原代码的错误判断和日志写入逻辑存在瑕疵。

代码修正方案

方案1:拆分步骤+独立Try-Catch(推荐,更灵活)

将每个装机步骤单独包裹在Try-Catch中,确保单个步骤出错不影响后续流程,同时统一处理错误日志:

# 初始化错误日志路径
$logPath = "C:\Users\$env:UserName\Desktop\LogOfErrors.txt"

# 检查并创建日志文件
if (Test-Path -Path $logPath) {
    Write-Host "错误日志文件已存在" -ForegroundColor Green
} else {
    New-Item -Path $logPath -ItemType File | Out-Null
    Write-Host "错误日志文件已创建" -ForegroundColor Green
}
Write-Host "继续执行..." -ForegroundColor Green
Write-Host ""

# 自定义错误日志写入函数(统一处理日志格式)
function Write-ErrorLog {
    param(
        [Parameter(Mandatory=$true)]
        [string]$ErrorMessage
    )
    # 加入时间戳便于排查
    $logEntry = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $ErrorMessage"
    Add-Content -Path $logPath -Value $logEntry -Force
}

# ------------------------------
# 装机步骤1:示例操作
# ------------------------------
try {
    Write-Host "执行装机步骤1..." -ForegroundColor Cyan
    # 替换为实际装机命令,添加 -ErrorAction Stop 强制触发终止错误
    # Example-Command1 -Parameter Value -ErrorAction Stop
} catch {
    Write-ErrorLog -ErrorMessage $_.Exception.Message
    Write-Host "步骤1执行出错,已记录日志,继续后续步骤..." -ForegroundColor Yellow
}

# ------------------------------
# 装机步骤2:示例操作
# ------------------------------
try {
    Write-Host "执行装机步骤2..." -ForegroundColor Cyan
    # 替换为实际装机命令
    # Example-Command2 -Parameter Value -ErrorAction Stop
} catch {
    Write-ErrorLog -ErrorMessage $_.Exception.Message
    Write-Host "步骤2执行出错,已记录日志,继续后续步骤..." -ForegroundColor Yellow
}

# 更多装机步骤以此类推...

# ------------------------------
# 脚本收尾部分
# ------------------------------
$FinishTime = Get-Date

Write-Host "############################################################################" -ForegroundColor Green
Write-Host "#                                                                          #" -ForegroundColor Green
Write-Host "#      装机完成,PowerShell将在10分钟后关闭。                              #" -ForegroundColor Green
Write-Host "#                                                                          #" -ForegroundColor Green
Write-Host "############################################################################" -ForegroundColor Green

Write-Host ""
Write-Host "脚本完成时间: $FinishTime" -ForegroundColor Green
Write-Host ""
Write-Host "请删除以下文件夹: C:\Scripts" -ForegroundColor Red

Start-Sleep -Seconds 600
Exit

方案2:全局错误陷阱(简洁高效)

使用trap语句全局捕获所有错误,无需为每个步骤单独写Try-Catch:

# 初始化错误日志路径
$logPath = "C:\Users\$env:UserName\Desktop\LogOfErrors.txt"

# 检查并创建日志文件
if (-not (Test-Path -Path $logPath)) {
    New-Item -Path $logPath -ItemType File | Out-Null
    Write-Host "错误日志文件已创建" -ForegroundColor Green
} else {
    Write-Host "错误日志文件已存在" -ForegroundColor Green
}
Write-Host "继续执行..." -ForegroundColor Green
Write-Host ""

# 设置全局错误陷阱:捕获所有错误并记录,随后继续执行脚本
trap {
    $logEntry = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $($_.Exception.Message)"
    Add-Content -Path $logPath -Value $logEntry -Force
    Write-Host "执行出错: $($_.Exception.Message),已记录日志,继续执行..." -ForegroundColor Yellow
    continue # 关键:让脚本继续执行后续代码
}

# 全局设置:将所有非终止错误转为终止错误,确保trap能捕获到
$ErrorActionPreference = "Stop"

# ------------------------------
# 装机脚本主体内容
# ------------------------------
Write-Host "开始执行装机流程..." -ForegroundColor Cyan

# 替换为实际装机命令
# Example-Command1
# Example-Command2
# ...其他装机步骤

# ------------------------------
# 脚本收尾部分
# ------------------------------
$FinishTime = Get-Date

Write-Host "############################################################################" -ForegroundColor Green
Write-Host "#                                                                          #" -ForegroundColor Green
Write-Host "#      装机完成,PowerShell将在10分钟后关闭。                              #" -ForegroundColor Green
Write-Host "#                                                                          #" -ForegroundColor Green
Write-Host "############################################################################" -ForegroundColor Green

Write-Host ""
Write-Host "脚本完成时间: $FinishTime" -ForegroundColor Green
Write-Host ""
Write-Host "请删除以下文件夹: C:\Scripts" -ForegroundColor Red

Start-Sleep -Seconds 600
Exit

关键修正点说明

  1. 错误判断逻辑修正:原代码中$LogOfErrors -Contains "True"错误,Test-Path返回布尔值,直接用if ($LogOfErrors)判断即可。
  2. 错误捕获范围扩展:通过-ErrorAction Stop或全局$ErrorActionPreference = "Stop",将所有非终止错误转为终止错误,确保所有错误都能被捕获记录。
  3. 继续执行逻辑实现:
    • 方案1通过拆分步骤为独立Try-Catch,单个步骤出错后不影响后续步骤;
    • 方案2通过trap中的continue关键字,让脚本在捕获错误后继续执行后续代码。
  4. 日志优化:添加时间戳,便于后续排查错误发生的时间点。

内容的提问来源于stack exchange,提问作者jack bridgewater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 02:46:23