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?
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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.