When writing a Bash script you can use brace expansion to quickly generate lists:
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With