繁体   English   中英

Powershell-使用Get-ChildItem在文件内搜索时的奇怪输出

[英]Powershell - Strange output when using Get-ChildItem to search within files

我有一个问题,希望有人可以提供帮助。

我有一个包含以下行的powershell脚本:

$output = Get-ChildItem -path $target -recurse | Select-String -pattern hello | group path | select name
Write-Output "Output from the string match is $output"

我得到的错误:

Output from the string match Microsoft.Powershell.Commands.GroupInfo Microsoft.Powershell.Commands.GroupInfo

当我独自运行此命令时(即不在脚本内),它可以完美运行并返回该位置上包含单词“ hello”的两个文件。

似乎它知道找到了两件事,因为它两次打印了“ Microsoft.Powershell.Commands.GroupInfo”文本(如上面的错误所示)。 但是,为什么要打印此文件而不是打印文件的路径呢?

我必须忽略一些明显的东西,但是我不知道是什么。

非常感谢您的帮助,谢谢

您看到它的原因是因为$ output是Selected.Microsoft.PowerShell.Commands.GroupInfo对象的数组-当传递给Select-Object时由Group-Object返回的对象(没有Select-Object,它们只是Microsoft .PowerShell.Commands.GroupInfo对象)。 您可以通过运行以下命令来确认$ ouput中的对象类型:

$output | Get-Member

检查显示在输出顶部的TypeName。

当您在控制台中交互式运行这些命令时,您会看到路径,因为PowerShell知道如何在控制台中显示GroupInfo对象,以使它们易于阅读。 请注意,当您仅在控制台中调用$ output时,您会看到一个带有短划线的带下划线的“名称”标头-这是PowerShell解释您为其提供的GroupInfo对象并在控制台中为您显示Name属性。

当您尝试在字符串中输出$ output数组时,会发生问题。 然后,PowerShell无法使用其更高级的格式化逻辑,而仅尝试将对象转换为要插入到字符串中的字符串。 当这样做时,它没有足够的逻辑来知道您真正想在字符串中显示的是这些GroupInfo对象的Name属性,因此,如果仅打印出每个对象的类型名称的字符串,在$ output数组中。 这就是为什么您两次看到类型名称的原因。

此问题的简单解决方案是Select-Object的-ExpandProperty参数。 这样做就可以了- 扩展了使用Select-Object所需的属性,并返回该属性,而不返回父对象。 因此,GroupInfo对象的Name属性是一个字符串。 如果调用Select-Object Name ,则会获得具有Name属性的GroupInfo对象。 如果调用Select-Object -ExpandProperty Name ,则只会获得Name属性作为String对象。 在这种情况下,我期望您要这样做。

因此,请尝试以下操作:

$output = Get-ChildItem -path $target -recurse | Select-String -pattern hello | group path | select -ExpandProperty name

我认为在这里进行foreach是适当的。 尝试这个:

$output = Get-ChildItem -path $target -recurse | where {$_.name -like "*hello*"} | select name
foreach ($file in $output) {
   write-host $file.name
}

或这个:

$output = Get-ChildItem -path $target -recurse | select-string -pattern "hello" | select name
foreach ($file in $output) {
   write-output $file.name
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM