Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell equivalent of Bash Brace Expansion for generating lists/arrays

When writing a Bash script you can use brace expansion to quickly generate lists:

Bash Brace Expansion

What is the simplest way to generate a similar list in Powershell? I can use the .. or , operators to generate an array, but how can I prefix the items with a static string literal?

PS C:\Users\gb> 1..5
1
2
3
4
5

PS C:\Users\gb> "test"+1..5
test1 2 3 4 5

PS C:\Users\gb> "test","dev","prod"
test
dev
prod

PS C:\Users\gb> "asdf"+"test","dev","prod"
asdftest dev prod
like image 802
Greg Bray Avatar asked Apr 25 '13 18:04

Greg Bray


2 Answers

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.

like image 195
Bill_Stewart Avatar answered Oct 25 '22 12:10

Bill_Stewart


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.

like image 27
alroc Avatar answered Oct 25 '22 12:10

alroc