如何操作invoke-restmethod返回的对象?

时间:2016-11-21 11:33:18

标签: powershell

这是我Invoke-RestMethod出现问题的又一次。希望在你的帮助下我能够进步。这次问题是我正在努力获得ipaddress=10.128.64.44的对象的端口值。

运行此代码:

$user = "admin"
$pass = 'Password1'
$ipdir = '10.128.64.44'
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass)))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))


$uri = 'https://myhostname/MAM/wfservice/workers/'
$rep = Invoke-restmethod -method get -Header $headers -Uri $uri

 Foreach($worker_port in $rep){

      write-output $worker_port.WorkersList.Worker

 }

终端中返回:

ActiveJobs          : 
ForbiddenAgentsList : ForbiddenAgentsList
IPAddress           : 10.128.64.34
LastMsgTime         : 2016-11-21T00:16:04.2813148+01:00
Name                : Worker02
NumOfSlots          : NumOfSlots
Port                : 52268
SelectedAgentsList  : SelectedAgentsList
Status              : Active 
Version             : 2.29.3740.0
Iteration           : 2016/2 SP3 (87)

ActiveJobs          : 
ForbiddenAgentsList : ForbiddenAgentsList
IPAddress           : 10.128.64.44 
LastMsgTime         : 2016-11-21T00:16:04.2813148+01:00
Name                : Worker05
NumOfSlots          : NumOfSlots
Port                : 53246
SelectedAgentsList  : SelectedAgentsList
Status              : Active
Version             : 2.29.3740.0
Iteration           : 2016/2 SP3 (87)

我想过运行这样的东西来获得一个端口:

if ( ($worker_port.WorkersList.Worker.IPaddress) -eq '10.128.64.44'){Write-Output $worker_port.Worker.Port }
         else {write-host "ouch!""}

......但似乎这不是道路。它返回两个端口:

53246
52268

有人知道这里有什么问题吗?如何解析它以获得仅限10.128.64.44的端口号。任何建议都非常感谢。

1 个答案:

答案 0 :(得分:1)

使用Where-Object cmdlet根据所需的IPAddress过滤对象,然后选择Port

$rep.WorkersList.Worker | Where IPAddress -eq '10.128.64.44' | Select -expand Port