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

如何在PowerShell中获取ConvertFrom-StringData的全部错误而非仅首个

如何让PowerShell的ConvertFrom-StringData返回所有重复键错误

方法一:预处理提前排查所有重复键

先对处理后的行做预处理,提取所有键并找出重复项,一次性获取所有重复问题:

# 筛选并格式化符合要求的行
$processedLines = $remoteFiles | Where-Object { $_ -match '^[a-f0-9]{32}  ' } | ForEach-Object { $_ -replace '^([a-f0-9]{32})(  )', '$1$2=  ' }

# 提取所有键并找出重复项
$allKeys = $processedLines | ForEach-Object { ($_ -split '=')[0].Trim() }
$duplicateGroups = $allKeys | Group-Object | Where-Object { $_.Count -gt 1 }

if ($duplicateGroups) {
    Write-Warning "检测到重复键:"
    foreach ($group in $duplicateGroups) {
        Write-Host "键 '$($group.Name)' 重复出现 $($group.Count) 次,对应行:"
        $processedLines | Where-Object { $_ -match "^$($group.Name)  =  " }
    }
} else {
    # 无重复时正常转换为哈希表
    $stringData = $processedLines -join "`n"
    $result = $stringData | ConvertFrom-StringData
}

方法二:逐行处理并收集所有错误

通过逐行调用ConvertFrom-StringData,手动检查重复键并收集所有错误:

$finalResult = @{}
$errorList = @()

# 先处理得到格式化后的行
$processedLines = $remoteFiles | Where-Object { $_ -match '^[a-f0-9]{32}  ' } | ForEach-Object { $_ -replace '^([a-f0-9]{32})(  )', '$1$2=  ' }

foreach ($line in $processedLines) {
    try {
        $lineHash = $line | ConvertFrom-StringData -ErrorAction Stop
        $currentKey = $lineHash.Keys[0]
        
        if ($finalResult.ContainsKey($currentKey)) {
            $errorList += "重复键 '$currentKey':已有值 '$($finalResult[$currentKey])',新行内容 '$line'"
        } else {
            $finalResult[$currentKey] = $lineHash[$currentKey]
        }
    } catch {
        $errorList += "处理行 '$line' 失败:$($_.Exception.Message)"
    }
}

# 输出所有错误
if ($errorList.Count -gt 0) {
    Write-Error "共发现 $($errorList.Count) 个错误:`n$($errorList -join "`n")"
}

# 最终结果存储在$finalResult中

为什么原命令只返回第一个错误

ConvertFrom-StringData默认遇到第一个无效数据条目(比如重复键、格式错误)就会终止处理,不会继续解析后续内容,所以只会抛出第一个错误。要获取所有错误,必须提前预处理排查,或者逐行单独处理并收集问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:10:24