如何修改PowerShell字符串查找脚本让输出按换行显示?
PowerShell查找字符串输出换行优化
我编写了一个PowerShell脚本script.ps1,用于在文件内容中查找特定字符串:
$lookup = Read-Host -Prompt "Enter the word you're looking for:" $res = sls "$lookup" (dir -Recurse *.txt, *.docx, *xlsx) Write-output "$res" Read-Host -Prompt "Press Enter to exit"
测试时输入字符串"A",当前输出所有匹配项挤在一行:
Enter the word youre looking for: A C:\Users\koyamashinji\Downloads\test\test1.txt:1:ABCDEFGHIJKLMN C:\Users\koyamashinji\Downloads\test\test2.txt:1:ABCDEFGHIJKLMN C:\Users\koyamashinji\Downloads\test\test3.txt:1:ABCDEFGHIJKLMN C:\Users\koyamashinji\Downloads\test\test4.txt:1:ABCDEFGHIJKLMN Press Enter to exit:
我希望每个匹配项单独换行显示,效果如下:
Enter the word youre looking for: A C:\Users\koyamashinji\Downloads\test\test1.txt:1:ABCDEFGHIJKLMN C:\Users\koyamashinji\Downloads\test\test2.txt:1:ABCDEFGHIJKLMN C:\Users\koyamashinji\Downloads\test\test3.txt:1:ABCDEFGHIJKLMN C:\Users\koyamashinji\Downloads\test\test4.txt:1:ABCDEFGHIJKLMN Press Enter to exit:
修改方案
问题出在Write-output "$res"这一行——用双引号包裹数组$res时,PowerShell会强制将数组转换为单个字符串,元素默认用空格分隔。只需去掉双引号,直接输出数组即可:
$lookup = Read-Host -Prompt "Enter the word you're looking for:" $res = sls "$lookup" (dir -Recurse *.txt, *.docx, *xlsx) Write-Output $res # 移除双引号 Read-Host -Prompt "Press Enter to exit"
还可以更简洁,省略Write-Output,PowerShell默认会输出未捕获的变量:
$lookup = Read-Host -Prompt "Enter the word you're looking for:" sls "$lookup" (dir -Recurse *.txt, *.docx, *xlsx) Read-Host -Prompt "Press Enter to exit"
原理说明
sls(即Select-String)返回的是MatchInfo对象数组,直接输出数组时,PowerShell会自动为每个元素单独换行;用双引号包裹数组时,会调用数组的ToString()方法,将所有元素用空格拼接成单一字符串,导致结果挤在一行。
内容的提问来源于stack exchange,提问作者koyamashinji
相关产品推荐
相关产品推荐

