PowerShell:从API响应中检索特定单词并编译成HTML表



我试图从API中检索特定的单词,不幸的是,API响应只是一个包含以下文本的主体响应-示例如下:

他们发现这是由于第三方工作室Square Melon的问题,他们已经联系并正在制定解决方案。问题解决后将进行更新,等待团队的反馈
事件指挥官:Barrie James
Remedy INC1063757 PD 387049

检索"Barrie James"&以及INC编号(INC1063757(。不幸的是,我已经被困了一段时间,因为可能会发生多起不同的事件,这意味着名称和INC编号将发生变化。

有什么想法吗?

假设您将来自此API的响应分配给一个变量$response,我们首先需要将其从一个字符串分解为一个字符串数组,我们将这样做

$response = Invoke-RestMethod -uri www.mycoolsite.com #or maybe Invoke-WebRequest
$response
>They have found that this is due to in issue with the 3rd party Studio, Square Melon, who have been contacted and are working on a solution. Updates to follow once the issue has been resolved, pending feedback from the teams.
Incident Commander: Barrie James
Remedy INC1063757 PD 387049
$response.Count
>1
#we need response to be an array of strings for Select-string to work.  
$response.Split("`n").Count
>3

我们对变量$response调用了Split()方法,并在它看到隐藏的'nPowerShell换行符的任何地方将其分解。

接下来,我们可以使用|管道字符将字符串数组发送到Select-String,并查找其中包含特定字符串的行。

$response.Split("`n") | select-string "Incident Commander:"

这会将结果解析为有用的内容,如下所示。

$response.Split("`n") | select-string "Incident Commander:"
IgnoreCase : True
LineNumber : 2
Line       : Incident Commander: Barrie James
Filename   : InputStream
Path       : InputStream
Pattern    : Incident Commander:
Context    : 
Matches    : {0}

从这里,我们只需选择行属性,其中包含文本Incident Commander: Barrie James

($response.Split("`n") | select-string "Incident Commander:").Line
>Incident Commander: Barrie James

剩下的就是去掉冒号,我们将使用.Split()方法。这将把字符串分解成单独的字符串,无论它在哪里看到我们提供的字符。

($response.Split("`n") | select-string "Incident Commander:").Line.Split(":")
Incident Commander
Barrie James

现在,只选择第二个项目,这是我们通过索引来完成的。PowerShell中的索引从零开始(当然(,所以我们实际上要求"索引1处的项",这意味着第二个位置。

($response.Split("`n") | select-string "Incident Commander:").Line.Split(":")[1].Trim()
Barrie James

就这样。这就是你的做法,也是我们每走一步的原因。

最新更新