Powershell Bash Equivalent Bracket Extension for List / Array Generation

When writing a Bash script, you can use the bracket extension to quickly create lists:

Bash brace expansion

What is the easiest way to create a similar list in Powershell? I can use .. or, the operators generate an array , but how can I prefix the elements 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 
+6
source share
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 .

Bill

+7
source

I hope that turns out to be wrong here, but I do not believe that there is a way to do this in the same way as with bash or with a few keystrokes.

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

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

Or using the shortened version:

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

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

 test1 test2 test3 test4 test5 

Note. If you create this in a script for publishing / distribution / reuse, use a more detailed foreach-object rather than the abbreviated % - for readability.

+8
source

Source: https://habr.com/ru/post/943643/


All Articles