How can I join the result of `ls` as a char separated string in PowerShell?

空扰寡人 提交于 2019-12-11 11:13:30

问题


I have a folder containing the following files:

  • File_1.txt
  • File_2.txt
  • AnotherFile.txt

I want to be able to achieve an output of: File_1.txt - File_2.txt

I have tried running:

ls .\file*.txt | %{$_.Name}

which returns what I want except on separate lines, how can I join the files returned by a given character (- in this example)?

Any help is appreciated.


回答1:


You can use the -join operator:

(ls file*) -join ' - '

If you need more control about the individual items being joined here, just amend the pipeline appropriately:

(ls file* | select -Expand Basename) -join ' - '



回答2:


i'd do:

ls .\file*.txt | Foreach { $output = $output + $_ + ' - '}



来源:https://stackoverflow.com/questions/33077547/how-can-i-join-the-result-of-ls-as-a-char-separated-string-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!