0

我必须列出来自不同位置的带有一些字符串的文件,但在输出中我需要逐行路径。如果第一个位置中的文件不止一个,那么一切都可以,但是如果只有一个文件,而在其他位置中的文件比所有路径都在一行中的文件多。

例子:

$files = (Get-ChildItem "C:\temp" | Select-String "test" | group Path).Name

输出:

C:\temp\cca.msi
C:\temp\dfgfg.txt
C:\temp\dghghfgh.txt

添加第二个位置:

$files += (Get-ChildItem "C:\temp2" | Select-String "test" | group Path).Name

输出:

C:\temp\cca.msi
C:\temp\dfgfg.txt
C:\temp\dghghfgh.txt
C:\temp2\file3.txt
C:\temp2\file4.txt

以上是正确的。

下面是我的错误:

$files = (Get-ChildItem "C:\temp" | Select-String "test" | group Path).Name

输出:

C:\temp\cca.msi

添加更多路径:

$files += (Get-ChildItem "C:\temp2" | Select-String "test" | group Path).Name

一行输出:

C:\temp\cca.msiC:\temp2\file3.txtC:\temp2\file4.txt

我究竟做错了什么?

4

2 回答 2

3

如果您的第一条语句只产生一个结果,则该变量$files包含一个字符串,而不是一个数组。您可以通过强制执行数组结果来解决此问题,例如通过数组子表达式运算符( @()):

$files = @((Get-ChildItem "C:\temp" | Select-String "test" | group Path).Name)

或通过将变量定义为数组:

[array]$files = (Get-ChildItem "C:\temp" | Select-String "test" | group Path).Name
于 2018-04-12T10:05:12.877 回答
0

这很好用,但我不知道为什么我的问题中的上述代码不起作用。

$files=(Get-ChildItem "C:\temp","C:\temp2"  | Select-string "test"| group path).name
于 2018-04-12T09:47:16.970 回答