powershell 如何将字符串转换为可用格式

lskq00tm  于 2023-03-02  发布在  Shell
关注(0)|答案(1)|浏览(184)

我试图自动化一个过程,本质上我们接收一个文件的错误代码和行号,我写的脚本需要得到错误代码和行号,然后深入文件并检索行。
除了将错误代码和行号解析为某种可用格式以便我可以循环遍历它们之外,其他一切都正常工作
格式为:
错误代码行号
一二三四○ ○二三二○ ○二三三○ ○七八七
小行星3333
一一一一零一二三二二一三二
我试过了

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

但是在遍历哈希表和处理偶尔出现的CSV值方面,我还是一片空白。
我确实想过把整个东西转换成CSV,但我碰到了我知识的边缘...

xwbd5t1u

xwbd5t1u1#

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

# read target file into memory for later extraction
$fileContents = Get-Content C:\path\to\source\file.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]
        }
    }
}

相关问题