code

PowerShell의 Invoke-WebRequest에서 JSON을 해석하는 방법

starcafe 2023. 3. 9. 22:13
반응형

PowerShell의 Invoke-WebRequest에서 JSON을 해석하는 방법

GET 요구를 서버에 송신하는 경우, 서버는 자기 서명 증명서를 사용합니다.

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$RESPONSE=Invoke-WebRequest -Uri https://yadayada:8080/bla -Method GET
echo $RESPONSE

다음과 같은 응답이 있습니다.

StatusCode        : 200
StatusDescription : OK
Content           : {123, 10, 108, 111...}
RawContent        : HTTP/1.1 200 OK
                    Content-Length: 21
                    Date: Sat, 11 Jun 2016 10:11:03 GMT

                    {
                        flag:false
                    }
Headers           : {[Content-Length, 21], [Date, Sat, 11 Jun 2016 10:11:03 GMT]}
RawContentLength  : 21

컨텐츠에 유선 번호가 포함되어 있기 때문에 RawContent를 검색했습니다.헤더를 무시하고 내부의 JSON을 해석하려면 어떻게 해야 합니까?아니면 그 번호에서 콘텐츠를 얻을 수 있는 깔끔한 방법이 있을까요?

교환할 수 있습니다.Invoke-WebRequest와 함께Invoke-RestMethod어떤 json 응답 자동 수신이psobject다음을 사용할 수 있습니다.

$response = Invoke-RestMethod -Uri "https://yadayada:8080/bla"
$response.flag 

사용할 필요가 있는 경우Invoke-WebRequest에 걸쳐서Invoke-RestMethod먼저 그것을 문자열로 변환함으로써 오브젝트로 변환할 수 있다.

$response = Invoke-WebRequest -Uri "https://yadayada:8080/bla"
$jsonObj = ConvertFrom-Json $([String]::new($response.Content))

이쪽:

$response = Invoke-WebRequest -Uri <your_uri>
if ($response.statuscode -eq '200') {
    $keyValue= ConvertFrom-Json $response.Content | Select-Object -expand "<your_key_name>"
}

언급URL : https://stackoverflow.com/questions/37762615/how-to-parse-json-from-the-invoke-webrequest-in-powershell

반응형