How to filter an object of devices to a single one based on hostname in powershell? [duplicate]

僤鯓⒐⒋嵵緔 提交于 2019-12-18 09:29:02

问题


I'm trying to get the sitename of a device by using the hostname of a single device from an object that contains the details of 100's of devices in Powershell. How do I filter it?

The data is originally from an API and is being pulled in as Json, I've converted it using ConvertFrom-Json so it should be in an object now.

I have tried piping the object through Select-Object and Where-Object unsuccessfully, the way I'm using the commands don't seem to do anything but I'm not sure what I'm doing wrong.

The data is initially pulled using:

$allDevices = New-AemApiRequest @params -ApiAccessToken $apiAccessToken

And is then converted to an object using:

$allDevicesObj = $allDevices | ConvertFrom-Json

The results of that can then be seen using:

Write-Host $allDevicesObj.devices

Which will show data similar to this:

@{id=1234; uid=123-456-789; siteId=1; siteUid=11aa; siteName=site1; deviceType=; hostname=DESKTOP-abc123;}
@{id=2345; uid=987-654-321; siteId=2; siteUid=22bb; siteName=site2; deviceType=; hostname=DESKTOP-abc456;} 
@{id=3456; uid=234-345-456; siteId=3; siteUid=33bb; siteName=site3; deviceType=; hostname=DESKTOP-abc789;} 

I want to be able to filter the output to 1 of the results based on the hostname, so I tried using a combination of the Where-Object and Select-Object functions:

Write-Host $allDevicesObj.devices | Where-Object {$_.hostname -eq DESKTOP-abc123}

That just seems to do nothing and displays everything again. I tried being a bit less specific, but to also only select the siteName:

Write-Host $allDevicesObj.devices | Where-Object -Contains "123" | Select-Object -Property siteName

But that just showed everything again too. I tried similar variants with Select-Object with the same results.

When using the Where-Object to specify the object I want and then to just select the siteName value/property using Select-Object I am hoping to get the output to just be

site1

回答1:


Write-Host writes a string representation of your object to the console and doesn't send anything down the pipeline. Filter using Where-Object and just allow it to be written to the Output stream.

$allDevicesObj | Where-Object {$_.hostname -eq 'DESKTOP-abc123'}

To get just the site you can pipe from where-object to select-object

$allDevicesObj | Where-Object {$_.hostname -eq 'DESKTOP-abc123'} | Select-Object -property SiteName


来源:https://stackoverflow.com/questions/55840468/how-to-filter-an-object-of-devices-to-a-single-one-based-on-hostname-in-powershe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!