Home > front end >  Powershell Removing lines from string
Powershell Removing lines from string

Time:01-18

I'm quering 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" : { },

CodePudding user response:

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.

  • Related