如何在powershell脚本中匹配文本文件内容的每一行

How to match each line of a text file contents in powershell script

我有一个包含以下内容的文本文件 'abc.txt'。
hello_1
hello_2
..
..
hello_n

我需要编写一个脚本来打开文件 abc.txt 并读取每一行并将每一行存储在一个名为 $temp 的变量中。我只需要阅读以 'hello' 开头的行。下面的代码有什么问题?
我有以下代码:

foreach ($line in Get-Content "c:\folder\abc.txt")    
{    
    if($line Select-String -Pattern 'hello')
    $temp=$line
}

您在 $line 之后缺少管道,并且在 foreach 之后的整个脚本块 {} 中缺少花括号应该是:

foreach ($line in Get-Content "c:\folder\abc.txt")    
{    
    {
    if($line | Select-String -Pattern 'hello')
    $temp=$line
    }
}

此外,我不知道你的目的是什么,但如果你想要 $line 不会每次都被覆盖,你应该在迭代之外创建一个数组并每次填充它:

所以首先是:$line = @() 而不是 $temp=$line 更改为 $temp += $line

但是话又说回来,如果您的全部目的是从文本文件中过滤 hello 字符串,那么这应该足够了:

$temp = (Get-Content "c:\folder\abc.txt") -match '^hello'

试试这个 -

$temp = @()
(Get-Content "c:\folder\abc.txt") | % {$temp += $_ | Select-String -Pattern "hello"}
$temp

代码正在获取 abc.txt 的内容,并为每个对象检查模式是否匹配 hello。如果匹配,则将相应的值存储在定义为 $temp.

的数组中

您可以像这样改写您的原始代码 -

$temp = @()
foreach ($line in Get-Content "c:\folder\abc.txt")    
{    
    if($line | Select-String -Pattern 'hello') {
    $temp += line
    }
}

在您的原始代码中,您缺少 pipeline in the statement if($line Select-String -Pattern 'hello'). And you are missing braces{} 来包含 if 语句。