1

I'm querying an API using PowerShell and the response I get is a string that starts with some header info I don't need, followed by the JSON I need. So I need to strip the first few lines of the string. Since I'm not sure it will always be the first 9 lines that I should strip, I'll have to search for the first empty line and split there.

I did try using split('rn') but that splits at every line and then I'd have to walk through those lines again and then when the first empty line is found, remove all the lines above and then stitch all the lines together again to make it a JSON. So I'd rather have something to split the whole string into two.

This is the result I'm getting back which I'd like to split after the date line:

HTTP/1.1 200 OK
X-VMWARE-VCLOUD-REQUEST-ID: 6dbdbd65-adea-44de-a6a1-cdc8a9671f0b
X-VMWARE-VCLOUD-REQUEST-EXECUTION-TIME: 30,30
Vary: Accept-Encoding, User-Agent
Content-Length: 2681
Cache-Control: no-store, must-revalidate
Content-Type: application/vnd.vmware.vcloud.query.records+json;version=36.2
Date: Tue, 17 Jan 2023 18:10:36 GMT

{
  "otherAttributes" : { },
  "link" : [ {
    "otherAttributes" : { },

1 Answer 1

1

Note that if you use Invoke-WebRequest call and access the return object's .Content property, you should normally get the JSON text only. If you use Invoke-RestMethod, the JSON text is automatically parsed into objects, i.e. a [pscustomobject] graph (that is, ConvertFrom-Json is implicitly applied).

If you do have to deal directly with a multiline string as shown in your question, you can use a regex-based -replace operation to strip the header lines:

# Remove everything up to and including the first empty line.
$multiLineStr -replace '(?s)^.+?\r?\n\r?\n'

For an explanation of the regex and the ability interact with it, see this regex101.com page.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for two answers :-) I switch to invoke-webrequest now, that is indeed easier instead of webclient I was using.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.