【问题标题】:How to convert a string into a useable format如何将字符串转换为可用格式
【发布时间】:2023-02-10 20:15:03
【问题描述】:

我正在尝试自动化一个过程,本质上我们收到一个文件的错误代码和行号。我正在编写的脚本需要获取错误代码和行号,然后深入文件并检索行。

一切正常,除了将错误代码和行号解析为某种可用格式,以便我可以遍历它们

格式为:

错误代码 行号

1234 00232,00233,00787

3333 00444

1111 01232,2132

我试过了

$a = $a -replace "\s+","="
$a|ConvertFrom-StringData

但是当谈到遍历哈希表和处理偶尔出现的 CSV 值时,我一片空白。

我确实想过将整个东西转换为 CSV,但我正面临知识的边缘......

【问题讨论】:

  • 您可能想考虑转换为一个 csv 文件,每个条目有一个错误代码和一个行号。这将很容易循环。

标签: arrays string powershell hashtable data-manipulation


【解决方案1】:

使用匹配空格后跟数字或大写字母的正则表达式,然后用定界符替换所述匹配项,最后将结果字符串解析为 CSV 文档:

# read target file into memory for later extraction
$fileContents = Get-Content C:path	osourceile.txt

# define error report, replace with `Get-Content` if data if coming from file too
$errorReport = @'
Error code Line number
1234 00232,00233,00787
3333 00444
1111 01232,2132
'@

# replace the middle space and parse as CSV
$errorMappingList = $errorReport -replace '(?-i) (?=p{Lu}|d)', '|' |ConvertFrom-Csv -Delimiter '|'

# go through each entry in the error mapping list
foreach($errorMapping in $errorMappingList){
    # go through each line number associated with the error code
    foreach($lineNo in $errorMapping.'Line Number' -split ','){
        # extract the line from the file contents, output 1 new object per line extracted
        [pscustomobject]@{
            ErrorCode  = $errorMapping.'Error code'
            LineNumber = $lineNo
            Line       = $fileContents[$lineNo - 1]
        }
    }
}

【讨论】:

    猜你喜欢
    • 2013-09-22
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 2019-04-01
    • 2013-07-11
    • 2021-11-17
    • 2018-01-02
    相关资源
    最近更新 更多