Powershell使用Where-Object获取内容

Bac*_*ave 2 powershell

我有这样一个文件:

line one email1
line two email1
line three email2
line four email1
Run Code Online (Sandbox Code Playgroud)

如果我只想提取包含"email1"的行,我这样做:

$text = Get-Content -Path $path | Where-Object { $_ -like *email1* }
Run Code Online (Sandbox Code Playgroud)

$ text现在是一个包含3行元素的数组,我按照这样迭代:

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

但是,如果我想获取包含"email2"的行.

$text = Get-Content -Path $path | Where-Object { $_ -like *email2* }
Run Code Online (Sandbox Code Playgroud)

返回一个字符串,而不是一个元素的数组.当我遍历它时,它遍历字符串中的每个字符.

如何使用一个元素而不是字符串使其成为一个数组?

Rom*_*min 7

为了总是得到一个数组,即使是1(即非字符串)或0(即不是$null)项,使用运算符@():

$text = @(Get-Content -Path $path | Where-Object { $_ -like *email1* })
Run Code Online (Sandbox Code Playgroud)


Bac*_*ave 5

解决了。

我需要将 $text 声明为 type [String[]]

[String[]]$logText = Get-Content -Path $path | Where-Object { $_ -like *email1* }
Run Code Online (Sandbox Code Playgroud)