将Invoke-RestMethod输出转换为object

时间:2016-09-30 22:04:18

标签: rest powershell

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

作为一个例子,当我使用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之类的操作来操纵$object.EWREST_category作为对象并获得“网络”。所以我一直在试图弄清楚如何使用maniuplate $object,它只是具有属性的传统PowerShell对象的一串属性。

有人可以就如何解决这个问题提供一些指示吗?

2 个答案:

答案 0 :(得分: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)

$obah=@{}                                 # 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)

答案 1 :(得分:1)

由于你已经有一个带键/值对的字符串,我只需要做一点清理(删除单引号和分号),将字符串转换为哈希表,然后从中构建一个自定义对象: / p>

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

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

编辑:要将多行值修改为一行,您可以使用另一个带有负向后置断言((?<!...))的替换,只有在前面没有换行时才会删除换行符单引号后跟分号。但是,由于同一属性包含其他分号,因此您还需要修改分号替换,以便只有在分号后跟换行符或字符串结尾时才会删除分号(使用正向前瞻断言{{1} }})。

(?=...)
相关问题