Powershell equivalent of Bash Brace Expansion for generating lists/arrays

蹲街弑〆低调 提交于 2019-12-03 06:06:25
PS C:\> "test","dev","prod" | % { "server-$_" }
server-test
server-dev
server-prod
PS C:\> 1..5 | % { "server{0:D2}" -f $_ }
server01
server02
server03
server04
server05
PS C:\> 1..5 | % { "192.168.0.$_" }
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5

Note that % is an alias for the ForEach-Object cmdlet.

Bill

I'm hoping to be proven wrong here, but I don't believe there is a way to do it exactly like with bash, or with as few keystrokes.

You can iterate over the list by piping it through a foreach-object to achieve the same result though.

1..5 | foreach-object { "test" + $_ }

Or using the shorthand:

1..5 | %{"test$_"}

In both cases (% is an alias for foreach-object), the output is:

test1
test2
test3
test4
test5

Note: if you're building this into a script for publishing/distribution/reuse, use the more verbose foreach-object, not the shorthand % - for readability.

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