简体   繁体   English

变量内每行的Powershell

[英]Powershell for each line within variable

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 我正在通过invoke-restmethod下载数据,并尝试执行以下操作

$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? 该脚本是时间紧迫的,因此我没有足够的精力来写文件然后重新打开,如何在不使用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. 我怀疑REST端点给您的是UNIX换行符,而不是Windows换行符。 In UNIX, a new line is one character 'lf' (line feed). 在UNIX中,新行是一个字符“ lf”(换行)。 In windows a newline is a 'crlf' (carriage return, line feed). 在Windows中,换行符是'crlf'(回车,换行)。

Try a string split method 尝试字符串分割方法

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

or if you prefer your 'foreach' syntax 或者,如果您更喜欢“ foreach”语法

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

[Edit: changed 'for' to 'foreach'] [编辑:将“ for”更改为“ foreach”]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM