Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell:查询多个字符串并输出到用户和文件_Powershell - Fatal编程技术网

Powershell:查询多个字符串并输出到用户和文件

Powershell:查询多个字符串并输出到用户和文件,powershell,Powershell,我被赋予了在许多主机上验证更新安装的职责。通过查询表示成功的错误代码字符串来执行此验证。我希望此输出既显示在shell中,也写入到文件中 $computerList = @($userInput) foreach ($_ in $computerList){ get-content -tail 20 ("filepath") ` | where {$_| select-string "All steps complete!"} `

我被赋予了在许多主机上验证更新安装的职责。通过查询表示成功的错误代码字符串来执行此验证。我希望此输出既显示在shell中,也写入到文件中

$computerList = @($userInput)
foreach ($_ in $computerList){
        get-content -tail 20 ("filepath") `
        | where {$_| select-string "All steps complete!"} `              
        | where {$_| select-string "Output Error = 0 "} `
        | out-file C:\users\me\Desktop\validation_log.txt -append                                               
        }
我基于一篇在线文章的多字符串“grep”-ing, 但是,这不会将所需字符串写入输出文件路径,也不会显示在控制台中


谁能解释一下查询多个字符串然后将其输出到文件的最佳方法

您的示例过于复杂

您可以将
选择字符串链接起来。如果您想将某些内容同时输出到文件和管道中,
Tee Object
是一种方法:

PS C:\temp> Get-Content -LiteralPath ".\input.txt"
All steps complete!
All steps complete! Output Error = 0
asdf

PS C:\temp> Get-Content -LiteralPath ".\input.txt" | Select-String -Pattern "All steps" | Select-String -Pattern "Output Error" | ForEach-Object {$_.ToString()} | Tee-Object -FilePath ".\output.txt" -Append
All steps complete! Output Error = 0

PS C:\temp> Get-Content -LiteralPath ".\output.txt"
All steps complete! Output Error = 0
对于每个模式,上面的行为类似于逻辑“and”。如果要“或”模式,可以使用模式是正则表达式这一事实:

PS C:\temp> Get-Content -LiteralPath ".\input.txt" | Select-String -Pattern "All steps|Output Error" | ForEach-Object {$_.ToString()} | Tee-Object -FilePath ".\output.txt" -Append
All steps complete!
All steps complete! Output Error = 0

还要注意,
selectstring
输出的是
Microsoft.PowerShell.Commands.MatchInfo
对象而不是字符串。如果将这些新行直接传输到
Tee对象
,则输出中可能会出现不需要的新行。因此,我将这些转换为
Foreach对象中的字符串

您不能将“where”与-and-or-or结合起来吗?嗨,Paal,非常感谢您的回答。不幸的是,我很难接受你的建议。我已经用提供的代码做了一些测试,我注意到如果我使用:
Get Content-LiteralPath.\input.txt“| Select String-Pattern”All Steps”
,那么控制台将返回所选字符串。但是,如果使用连续的Select String语句(如您的示例中)
Select String-Pattern“All steps”| Select String-Pattern“Output Error”
我观察到没有生成输出。版本5.1@Udstrat您正在体验我提到的“或”vs“和”部分。在你的屏幕截图中,你试着得到同时包含“Hello World”和“test2”的行。您的示例输入不包含这样的行,因此不会产生任何输出。