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

在PowerShell 5.1中能否用Try/Catch/Finally块修改条件判断?

实现方案

你的需求无法通过try/catch/finally直接强制让if分支跳转到else,但可以通过调整错误标记逻辑,将捕获到的Substring错误导向else分支的处理流程,同时避免低效的前置判断。

修改后的代码

# 初始化错误标记变量
$errorOccurred = $false

try {
    $substring = $fileString.Substring(19, 2)
} 
catch [System.ArgumentOutOfRangeException] {
    $errorMessage = $_.Exception.Message
    $errorOccurred = $true
    # 移除continue,避免直接跳过后续逻辑
}

# 合并错误情况与substring不匹配的处理逻辑
if (-not $errorOccurred -and $substring -match '[0-9][0-9]') {
    if(<# 依赖上述判断的过滤条件 #>){
        Copy-Item -Path "$($copyFilePath)\$_" -Destination $copyFileBadNameDestination -Recurse -Force -Verbose
    }
} 
else {
    Copy-Item -Path "$($copyFilePath)\$_" -Destination $copyFileBadNameDestination -Recurse -Force -Verbose
}

关键改动说明

  • 移除catch块中的continue语句,确保捕获错误后仍能执行后续的分支判断
  • 用$errorOccurred标记是否发生了文件名长度不足的错误
  • 调整分支判断逻辑:只有当没有错误且substring匹配两位数字时,才进入过滤判断分支;其余情况(包括错误、substring不匹配)统一走else分支的文件复制逻辑

这样既通过异常捕获替代了低效的前置长度判断,又实现了将错误文件导向目标处理分支的需求。

内容的提问来源于stack exchange,提问作者Ralph Warner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:40:31