这里有一些Powershell菜鸟..
我正在研究Windows Defender ATP的Microsoft API。我需要了解如何从自定义Powershell对象提取特定值,该对象作为Invoke-RestMethod的输出返回。
$webResponse = Invoke-RestMethod -Method Get -Uri $url -Headers $headers
Write-Output $webResponse
这将产生以下内容:
@ odata.context值 -------------- ----- https://api.securitycenter.windows.com/api/ $ metadata#Machines {@ {id = f7749cafd089c66e53g21332ba0b426f6f88c953; computerDnsName = desktop-h2134uc; firstSeen = 4/30/19 10:03:40 PM; lastSeen = 5/3/19 4:15:17 AM; osPlatform = Windows10; osVersion ...
我的问题是-如何提取ID,computerDnsName等的各个字段值。
谢谢!
答案 0 :(得分:0)
$response = Invoke-WebRequest -Uri www.google.at
$response | Get-Member
TypeName: Microsoft.PowerShell.Commands.HtmlWebResponseObject
Name MemberType Definition
---- ---------- ----------
...
Headers Property System.Collections.Generic.Dictionary[string,string] Headers {get;}
Images Property Microsoft.PowerShell.Commands.WebCmdletElementCollection Images {get;}
InputFields Property Microsoft.PowerShell.Commands.WebCmdletElementCollection InputFields {get;}
Links Property Microsoft.PowerShell.Commands.WebCmdletElementCollection Links {get;}
ParsedHtml Property mshtml.IHTMLDocument2 ParsedHtml {get;}
RawContent Property string RawContent {get;set;}
RawContentLength Property long RawContentLength {get;}
RawContentStream Property System.IO.MemoryStream RawContentStream {get;}
Scripts Property Microsoft.PowerShell.Commands.WebCmdletElementCollection Scripts {get;}
StatusCode Property int StatusCode {get;}
StatusDescription Property string StatusDescription {get;}
通过Get-Member
,您将知道此对象支持哪些属性。然后,您可以在给定的对象上调用这些属性:
$response.StatusCode
200
如果要选择多个属性,可以使用Select-Object
:
$response | select statuscode, statusdescription
StatusCode StatusDescription
---------- -----------------
200 OK
您当然可以将Select-Object
的结果存储在变量中。
Invoke-RestMethod
可以使用更多或更少的相同内容:
Invoke-RestMethod -Uri https://blogs.msdn.microsoft.com/powershell/feed/ | Get-Member
TypeName: System.Xml.XmlElement
Name MemberType Definition
---- ---------- ----------
...
comments Property System.Object[] comments {get;}
creator Property System.Xml.XmlElement creator {get;}
description Property System.Xml.XmlElement description {get;}
encoded Property System.Xml.XmlElement encoded {get;}
...
您可以选择/使用的属性取决于响应正文中返回的格式。在上面的示例中,您有一个XML正文,但是它也可以是JSON或其他形式。