3

I am trying to go through a variable, line by line, and apply regex to parse the string within it.

I am downloading the data via invoke-restmethod and am trying to do the below

$result= invoke-restmethod -uri $uri -method get

foreach($line in $result)
if($line -match $regex)
{
   #parsing
}

the above doesn't work as their is only one line. But when I output result into a file and then apply the above logic it works, like so

$result= invoke-restmethod -uri $uri -method get
$result >> $filelocation

$file = get-content $file
foreach($line in $file)
if($line -match $regex)
{
   #parsing
}

The script is time critical so I don't have the luxury to write to a file and then reopen, how could I achieve the above without using get-content?

1
  • I want to see the content of the file when you are storing in file and also the content output when you are not storing .Just give a write-host in the loop to get the output in the console and request you to post it. Commented Dec 24, 2016 at 16:44

1 Answer 1

4

It is not a problem with Invoke-Method. The following works exactly as you would want.

$result = Invoke-RestMethod -Uri https://blogs.msdn.microsoft.com/powershell/feed/
$result | %{ Write-Host $_ }

I suspect that the REST endpoint is giving you a UNIX newline instead of a windows newline. In UNIX, a new line is one character 'lf' (line feed). In windows a newline is a 'crlf' (carriage return, line feed).

Try a string split method

$result.Split("`n") | %{ Write-Host $_ }

or if you prefer your 'foreach' syntax

foreach ($line in $result.Split("`n")) {
  Write-Host $line
}

[Edit: changed 'for' to 'foreach']

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

1 Comment

the second option worked, but i had to change the for to a foreach

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.