David Klempfner
David Klempfner

Reputation: 9870

Powershell Get-Content with Where-Object

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?

Upvotes: 6

Views: 30615

Answers (4)

Gruntzy
Gruntzy

Reputation: 443

You also could use the Select-String Cmdlet, it worked for me even with only one result in the selection :

$text1 = Get-Content -Path $path | Select-String "email1"
$text1 | % { 
    # Do some stuff here
}

$text2 = Get-Content -Path $path | Select-String "email2"
$text2 | % { 
    # Do some stuff here
}

Upvotes: 2

David Klempfner
David Klempfner

Reputation: 9870

Worked it out.

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

[String[]]$logText = Get-Content -Path $path | Where-Object { $_ -like *email1* }

Upvotes: 5

Roman Kuzmin
Roman Kuzmin

Reputation: 42035

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* })

Upvotes: 11

Kohlbrr
Kohlbrr

Reputation: 4069

Instead of getting the Length method to treat a single element statement as an array, I think a better solution would be to use a foreach loop instead of a for loop to iterate:

foreach ($element in $text) {
    #stuff happens
}

will always parse through each element in $text, even if it's a single element.

Upvotes: 3

Related Questions