4

I have got a list of 20 servers : server1, server2, server3, server4, ... server20.

I need to have an array "servers" that contains these 20 servers, something like :

$prefix = "server"
$number = "1..20"
$servers = $prefix+number

My expected output : $servers="server1","server2","server3",...,"server20"

Thanks in advance

4 Answers 4

3

The easiest way is to just spell it out directly:

$servers = 1..20 | ForEach-Object { "server$_" }
Sign up to request clarification or add additional context in comments.

Comments

1

Change your last line to:

$Servers = @()
$Number | % {$servers=$servers + "$prefix$_"}

The first line specifies $servers as an array (otherwise it would be concatenated as a long string).

The second line will go through all the digits in your $number array and make an entry for each one.

2 Comments

@Joey - feel free to post an answer. I can get by in PS but I'm not a pro, so if you have a better method I would be excited to see it.
Maybe I just have peculiar ideas of how idiomatic PowerShell code should look. But I usually find that if you write things how you'd do it in Java or C# it looks really complicated and awkward.
1

Using a format string

$prefix = "Server"
 1..20 | foreach {"$prefix{0}" -f $_}

You can also use $prefix{0:d2} if you want them to all have 2-digit (zero-filled) numbers after the prefix.

Comments

0
$null, $servers = 0..20 -join ';server' -split ';'
$servers

2 Comments

That's quite a bit convoluted. Imho it's almost always better to make your intent clear – that's not what I see here.
@Joey Just showing other ways. Simplest way is to use the replace operator: 1..20 -replace '^', 'server'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.