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

时间:2017-06-06 18:08:14

标签: powershell

我已经被赋予了在许多主机上验证安装更新的职责。通过查询表示成功的错误代码字符串来执行此验证。我希望这个输出都出现在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 off of online article, 但是,这不会将所需的字符串写入外部文件路径,也不会在控制台中显示。

任何人都可以解释查询多个字符串然后将其输出到文件的最佳方法吗?

1 个答案:

答案 0 :(得分:1)

你的例子比必要的复杂得多。

你可以链接Select-String。如果你想在文件和管道中输出内容,那么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

对于每个模式,上述行为类似于逻辑“和”。如果你想“或”模式,你可以使用模式是正则表达式的事实:

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

另请注意Select-String输出Microsoft.PowerShell.Commands.MatchInfo个对象而不是字符串。如果将这些换行直接传送到Tee-Object,您可能会在输出中收到不需要的换行符。因此,我将这些转换为Foreach-Object

中的字符串