2017-09-27 60 views
1

我正在解析来自Web服务器(特别是Fanuc控制器)的HTML并将innerText指定给对象。解析和修改PowerShell对象

#Make sure the controller respons 
if ($webBody.StatusCode -eq 200) { 
    Write-Host "Response is Good!" -ForegroundColor DarkGreen 
    $preBody = $webBody.ParsedHtml.body.getElementsByTagName('PRE') | Select -ExpandProperty innerText 
    $preBody 
} 

输出看起来像一个小这样:

[1-184 above] 
    [185] = 0 '' 
    [186] = 0 '' 
    [187] = 0 '' 
    [188] = 0 '' 
    [189] = 0 '' 
    [and so on] 

我只希望从190,191,193例如读取数据。 这样做的最好方法是什么?我正在努力消除对象中不需要的数据。

目前我有一个输出到txt文件的vbscript应用程序,清理数据然后读取它并将其操作到sql插入。我试图用powershell改进它,并且尽可能地尝试在程序中保留所有内容。

任何帮助非常感谢。

回答

2

假设数据集不是太大而无法将所有内容放入内存中。你可以用正则表达式解析成PowerShell对象,然后你可以使用Where-Object进行过滤。

#Regex with a capture group for each important value 
$RegEx = "\[(.*)\]\s=\s(\d+)\s+'(.*)'" 
$IndexesToMatch = @(190, 191, 193) 
$ParsedValues = $prebody.trim | ForEach-Object { 
    [PSCustomObject]@{ 
     index = $_ -replace $regex,'$1' 
     int = $_ -replace $regex,'$2' 
     string = $_ -replace $regex,'$3' 
    } 
} 
$ParsedValues | Where-Object { $_.index -in $IndexesToMatch } 

输入:

[190] = 1 'a' 
[191] = 2 'b' 
[192] = 3 'c' 
[193] = 4 'd' 
[194] = 5 'e' 

输出:

index int string 
----- --- ------ 
190 1 a 
191 2 b 
193 4 d 
+0

感谢表示本,我从来没有想到使用替换前withing的自定义对象的。去书签这个以供将来参考。 – Snak3d0c