如何格式化 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/