arrayspowershellbrace-expansion

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

Solution

  • 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.