gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:16:04 25 4
gpt4 key购买 nike

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

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

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

(使用别名,字符串变量插值以及字符串刚从管道流到宿主的事实)

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com