Concatenar 2 variables (Powershell)

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"

Gracias por adelantado

preguntado el 01 de febrero de 12 a las 14:02

4 Respuestas

The easiest way is to just spell it out directly:

$servers = 1..20 | ForEach-Object { "server$_" }

Respondido 01 Feb 12, 21:02

Cambie su última línea a:

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

Respondido 01 Feb 12, 18:02

@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. - JNK

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

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.

Respondido 01 Feb 12, 20:02

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

Respondido 05 Feb 12, 09:02

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

@Joey Just showing other ways. Simplest way is to use the replace operator: 1..20 -replace '^', 'server' - zx38

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.