【问题标题】:Powershell - ForEach statement - concatenate resultsPowershell - ForEach 语句 - 连接结果
【发布时间】:2020-07-21 12:44:30
【问题描述】:

我希望从这里的任何人那里获得有关 powershell 脚本的帮助。

我正在尝试查看是否有一种方法可以调用 ForEach 语句的所有结果:

ForEach ($file in $test) {
        $filepath = $path+"\"+$file
        write-host $filepath
}

ForEach 语句中的 write-host $filepath 返回以下内容:

c:\....\file1.txt
c:\....\file2.txt
c:\....\file3.txt
etc...

我正在尝试查看是否可以获得所有这些结果并将它们放入我可以在 foreach 语句之外使用的 1 行中。有点像:

c:\....\file1.txt, c:\....\file2.txt, c:\....\file3.txt etc

现在,如果我在 ForEach 语句之外使用 write-host $filepath,它只会给我 $filepath 得到的最后一个结果。

希望我说得通。

提前谢谢你。

【问题讨论】:

  • 顺便说一句:Write-Host is typically the wrong tool to use,除非意图是仅写入显示器,绕过成功输出流,并能够将输出发送到其他命令,将其捕获在变量中,将其重定向到文件。要输出一个值,请单独使用它;例如,$value 而不是 Write-Host $value(或使用 Write-Output $value,尽管这很少需要)。另见:stackoverflow.com/a/50416448/45375的底部
  • 是的,这实际上只是目的,我只是添加它以确保我获得所需的正确信息。
  • @mklement0,这对我来说至少是Write-Output 破冰船! :)

标签: powershell


【解决方案1】:

没有比这更简单的了... ;-)

$FullPathList = ForEach ($file in $test) {
    Join-Path -Path $path -ChildPath $file
}
$FullPathList -join ','

首先创建一个包含完整路径的数组,然后使用-join 语句加入它们。 ;-)

【讨论】:

  • 嗨 olaf,有没有办法从获取“,”中排除最后一条记录
  • @Ralph 我不确定我是否明白你的意思。
  • 所以它现在给了我数组的输出。 path\text1.txt,path\text2.txt, path\text3.txt 等,但最后一条记录也得到 path\text12.txt"," 我需要删除
  • 你的数组是否有一个空元素作为最后一个?
【解决方案2】:

另一种变体,

$path = $pwd.Path   # change as needed
$test = gci         # change as needed

@(ForEach ($file in $test) { 
    $path + "\" + $file 
}) -join ", "

【讨论】:

    【解决方案3】:

    您可能还想查看 Get-ChildItem 的 FullName 属性。

    如果您执行(gci).FullName(或者可能是gci | select FullName),您将直接获得完整路径。

    因此,如果 $test 是来自 C:\some\dir 的 gci,那么 $test.FullName 就是您要查找的数组。

    【讨论】:

      猜你喜欢
      • 2021-08-27
      • 1970-01-01
      • 2022-10-21
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多