2016-09-30 65 views
0

我试图在售票系统的API上使用PowerShell Invoke-RestMethod,然后将输出转换为PowerShell对象。将Invoke-RestMethod输出转换为对象

作为一个例子,当我使用Invoke-RestMethod来获得票的属性,我得到了这个。

$object = Invoke-RestMethod '[URI here]' 
$object.GetType() 

IsPublic IsSerial Name          BaseType 
-------- -------- ----          -------- 
True  True  String         System.Object 


$object 

EWREST_supported_user0='Yes'; 
EWREST_updater_team='Support Team'; 
EWREST_eng_id='CLT'; 
EWREST_testlabelsub='Test Label'; 
EWREST_time_created='17:21:03'; 
EWREST_cr_conversion_related_to='Support Case'; 
EWREST__1901_full_name='secuser Testuser1'; 
EWREST_summary='Ticket Title'; 
EWREST_i_would_like_to_reopen_my_ticket='No'; 
EWREST_assigned_team_leader='Agiloft Admin'; 
EWREST_id='183255'; 
EWREST_severity='Sev 4'; 
EWREST_problem_description='<div>This is an example of a ticket note that takes up multiple lines when read via API<\/div><div>&nbsp;<\/div><div>Example note info here<\/div><div>&nbsp;<\/div> 
<div>Additional example note info here<\/div><div>&nbsp;<\/div><div>Even more note info here<\/div>'; 
EWREST_demo_data='No'; 

我想做什么就能做的是做这样的事情$object.EWREST_category操纵$object作为一个对象,并获得“网络”。所以我一直在试图弄清楚如何将maniuplate $object这只是一个属性的字符串传递给具有属性的传统PowerShell对象。

有人可以提供一些关于如何去做?

回答

1

既然你已经有一个键/值对的字符串我只是做了一些清理(删除单引号和分号),将字符串转换为一个哈希表,然后从构建自定义对象:

$response = Invoke-RestMethod '[URI here]' 

$props = $response -replace "'" -replace ';' | ConvertFrom-StringData 
$object = New-Object -Type PSObject -Property $props 

编辑:要裂伤成一条线,你可以使用另一个替换负向后断言((?<!...))只有当他们没有通过一个单引号后面是先去除新行的多值分号。但是,由于同一个属性包含其他分号,所以您还需要修改分号替换,以便仅在分号后跟随换行符或字符串结尾时才使用分号(使用肯定前瞻断言(?=...))。

$props = $response -replace "(?<!';)`n" -replace "'" -replace ";(?=`n|`$)" | 
      ConvertFrom-StringData 
+0

谢谢,这看起来像它会适合我。我确实有一个问题,其中一个属性是多行属性。这似乎打破了ConvertFrom-StringData命令。即在第一个新行上它获得“数据线新行在行:3字符44不是名称=值格式”任何想法如何防止? – floyd

+0

这取决于实际数据的样子。请更新您问题中的示例。 –

+0

我在我的问题中更新了示例以包含属性EWREST_problem_description,该属性是多行,并导致ConvertFrom-StringData命令出现问题。当它到达该属性的第二行时,它不会将其视为name = value格式。 – floyd

1

也许下一个天真的脚本可以吗?

$ob= "EWREST_supported_user0='Yes'; 
EWREST_category='Networking'; 
EWREST_updater_team='Admin Team'; 
EWREST_time_created='12:56:53'; 
EWREST_cr_conversion_related_to='Support Case'; 
"           # this is that string 

     # transform string to an array: 
$oba = $ob.Split("`r`n", [System.StringSplitOptions]::RemoveEmptyEntries) 

[email protected]{}         # create empty hash table 
              # and fill it from array then: 
$oba | ForEach-Object { 
     $aux=$_.split('=;')    #  key/value pair 
     $obah[$aux[0]] = $aux[1] }  # hash[key] = value 

$obah.Keys     # display hash table keys (only debug) 
$obah.EWREST_time_created # hash table item use (example: property) 
$obah['EWREST_category']  # hash table item use (another approach: index)