powershell - 在powershell中格式化每行命令输出

标签 powershell

如何格式化 Get-ChildItem 输出的每一行?例如,我想用我自己的字符串包围它,以获得以下输出(简单 - 没有表格或其他内容):

My string: C:\File.txt my string2
My string: C:\Program Files my string2
My string: C:\Windows my string2

以下内容无效:

Get-ChildItem | Write-Host "My string " + $_ + " my string2"

最佳答案

这里需要ForEach-Object:

Get-ChildItem | ForEach-Object { Write-Host My string $_.FullName my string2 }

否则就没有$_。作为一般规则,$_ 仅存在于脚本 block 中,而不直接存在于管道中。另外,Write-Host 对多个参数进行操作,并且您无法在命令模式下连接字符串,因此您需要添加括号以在表达式模式下获取一个参数,或者省略引号和 +(就像我在这里所做的那样)。

较短:

gci | % { "My string $($_.FullName) my string2" }

(使用别名、字符串变量插值以及字符串刚刚从管道中掉出到主机的事实)

关于powershell - 在powershell中格式化每行命令输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7697670/

相关文章:

powershell - 在Windows中从 `netstat`命令获取特定值

windows - 如何检测调用powershell脚本的批处理文件是否由Windows启动事件运行

powershell - powershell 中找不到位置参数错误

Powershell - 与可执行文件的命令行提示交互?

powershell - 将 Powershell 创建的文件的编码更改为 UTF8 而不是 UCS-2 LE

arrays - 显示数组中的重复值

PowerShell 将 blob 文本上传到 Azure 时出错 : UploadText(string)

excel - 如何使用powershell将行添加到带有公式的excel文档

powershell - Powershell:意外 token

powershell - 位置等于1或无参数值的单参数参数?