I have a text file 'abc.txt' that contains the below.
hello_1
hello_2
..
..
hello_n
I need to write a script to open the file abc.txt and read each line and store that each line in a variable called $temp. I need to read the line only that starts with 'hello'. What is wrong with the below code?
I have the below Code:
foreach ($line in Get-Content "c:\folder\abc.txt")
{
if($line Select-String -Pattern 'hello')
$temp=$line
}
You missing pipeline after $line
, and curly braces are missing in the whole scriptblock {
and }
after the foreach
, should be:
foreach ($line in Get-Content "c:\folder\abc.txt")
{
{
if($line | Select-String -Pattern 'hello')
$temp=$line
}
}
Also, I don't know what is your purpose, but if you want $line
will not be overwrited each time you should create an array outside of the iterration and fill it each time:
so first is: $line = @()
and instead of $temp=$line
change to $temp += $line
But then again if all your purpose is to filter the hello
string from the text file then this should be enough:
$temp = (Get-Content "c:\folder\abc.txt") -match '^hello'
Try this -
$temp = @()
(Get-Content "c:\folder\abc.txt") | % {$temp += $_ | Select-String -Pattern "hello"}
$temp
The code is getting the content of abc.txt
, and for each object checking if the pattern matches hello
. If it's a match, then it stores the corresponding value in the array defined as $temp
.
OR
You can rephrase your original code like this -
$temp = @()
foreach ($line in Get-Content "c:\folder\abc.txt")
{
if($line | Select-String -Pattern 'hello') {
$temp += line
}
}
In you original code, you are missing a pipeline in the statement if($line Select-String -Pattern 'hello')
. And you are missing braces {}
to enclose the if statement.
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.