从PowerShell v2开始对控制台进行JSON响应?

时间:2018-03-29 14:59:12

标签: .net json web-services powershell powershell-v2.0

get请求的基本排序:

thufir >
thufir >
thufir > $PSVersionTable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.8762
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1


thufir >
thufir > type .\foo.ps1

"start"

$request = [System.Net.WebRequest]::Create("http://ipinfo.io/json")
$request.Method = "GET"
[System.Net.WebResponse]$response = $request.GetResponse()

$response

"done"

thufir >
thufir > .\foo.ps1
start


IsMutuallyAuthenticated : False
Cookies                 : {}
Headers                 : {Vary, x-cloud-trace-context, Access-Control-Allow-Or
                          igin, X-Content-Type-Options...}
ContentLength           : 173
ContentEncoding         :
ContentType             : application/json; charset=utf-8
CharacterSet            : utf-8
Server                  :
LastModified            : 29/03/2018 7:54:31 AM
StatusCode              : OK
StatusDescription       : OK
ProtocolVersion         : 1.1
ResponseUri             : http://ipinfo.io/json
Method                  : GET
IsFromCache             : False

done


thufir >
thufir >

如何输出原始JSON?或格式化?

2 个答案:

答案 0 :(得分:2)

您可以使用WebClient将JSON下载为字符串:

$wc = New-Object System.Net.WebClient
$json = $wc.DownloadString("http://ipinfo.io/json")

要使用WebResponse,您需要ex。一个StreamReader来阅读回复。例如:

$request = [System.Net.WebRequest]::Create("http://ipinfo.io/json")
#GET is default
#$request.Method = "GET"
$response = $request.GetResponse()
$reader = New-Object -TypeName System.IO.StreamReader -ArgumentList $response.GetResponseStream(), $response.CharacterSet

#Get JSON response
$JSON = $reader.ReadToEnd()

#Cleanup
$reader.Close()
$response.Close()

答案 1 :(得分:0)

您可以按如下方式获得原始回复

(Invoke-WebRequest http://ipinfo.io/json ).rawcontent

或解析JSON,然后选择您感兴趣的属性:

Invoke-WebRequest http://ipinfo.io/json | ConvertFrom-Json