powershell脚本格式表输出中的颜色词
是否可以使用格式表为 powershell 输出仅对某些单词(而不是完整的行)进行着色。例如,此脚本递归扫描文件夹中的字符串,然后使用格式表输出结果。
dir -r -i *.* | Select-String $args[0] |
format-table -Property @{label="Line #"; Expression={$_.LineNumber}; width=6},
Path, Line -wrap
如果能够用特定的颜色来格式化我们正在搜索的单词,那就太好了,这样您就可以准确地看到它在行中的位置。
Is it possible to color only certain words (not complete lines) for a powershell output using format-table. For example, this script scans a folder recursively for a string and then output the result with format-table.
dir -r -i *.* | Select-String $args[0] |
format-table -Property @{label="Line #"; Expression={$_.LineNumber}; width=6},
Path, Line -wrap
It would be nice to be able to format the word we are searching for with a specific color, so that you can see exactly where it was found on the line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将表通过管道传输到
Out-String
中,然后使用Write-Host
和-NoNewLine
开关将字符串分段写入。像这样的东西:
You could pipe the table into
Out-String
, then write the string in parts usingWrite-Host
with the-NoNewLine
switch.Something like this:
我喜欢 Rynant 的方法。这是一个替代实现,使用
-split
而不是IndexOf
:如果该行以给定单词开头或结尾,则拆分包含空字符串,因此有额外的“如果不是第一个”逻辑。
编辑:根据 Rynant 的评论,这是另一个支持简单模式和正则表达式模式的实现:
以下示例的输出显示了差异:
I like Rynant's approach. Here is an alternate implementation, using
-split
instead ofIndexOf
:Split includes empty strings if the line starts or ends with the given word, hence the extra "if not first" logic.
Edit: Following Rynant's comment, here's another implementation that supports both simple and regex patterns:
The output from the following examples shows the difference:
我喜欢@Ryant 给出的答案。我这里有一个修改版本,可用于通过传入数组或单词和颜色来对输出中的多个单词进行着色。诀窍是您必须根据换行符将输入文本拆分为行。
并将执行如下
I love answer @Ryant gave. I have a modified version here that can be used for colouring multiple words in an output by passing in arrays or words and colours. The trick is that you have to split the input text into lines based on the newline separator.
and would be executed as follows