Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Get-Content with Where-Object

Tags:

powershell

I have a file like this:

line one email1
line two email1
line three email2
line four email1

If I want to extract only the lines that contain "email1", I do this:

$text = Get-Content -Path $path | Where-Object { $_ -like *email1* }

$text is now an array with 3 elements containing those lines, and I iterate through it like this:

for ($i = 0; $i -lt $text.Length; $i++)
{
#do stuff here
}

However, if I want to get the lines containing "email2".

$text = Get-Content -Path $path | Where-Object { $_ -like *email2* }

returns a string, rather than an array of one element. And when I iterate through it, it iterates through each char in the string.

How can I make it an array with one element rather than a string?

like image 293
David Klempfner Avatar asked Dec 01 '22 16:12

David Klempfner


2 Answers

In order to get an array always, even with 1 (i.e. not string) or 0 (i.e. not $null) items, use the operator @():

$text = @(Get-Content -Path $path | Where-Object { $_ -like *email1* })
like image 194
Roman Kuzmin Avatar answered Dec 09 '22 19:12

Roman Kuzmin


Worked it out.

I need to declare $text as type [String[]].

[String[]]$logText = Get-Content -Path $path | Where-Object { $_ -like *email1* }
like image 42
David Klempfner Avatar answered Dec 09 '22 19:12

David Klempfner