jks
jks

Reputation: 129

Concatenating a variable and a string literal without a space to an array using PowerShell

I'm trying add to a variable and a string in an array dynamically but i'm not getting expected output.

(1) I'm getting env name (2) Concatinating the string and variable in an array

Code is as follows.

$env = $env:COMPUTERNAME.Substring(0,2)
$servers = { $env+"server1.test.com",$env+"server2.test.com" }
$serverCount = $servers -split(",") | measure | % { $_.Count }

For ($i=0; $i -lt $serverCount; $i++) 
{
   $ServerName = $servers -split(',')  -replace '\[\d+\]'
   $server = $ServerName[$i]
   Write-Host $server
}

output i'm getting as

$env+"server1.test.com" $env+"server2.test.com"

Values are not getting concatenated properly and variable value is not getting displayed. Any help.

Upvotes: 0

Views: 1964

Answers (1)

TessellatingHeckler
TessellatingHeckler

Reputation: 29048

$servers = { $env+"server1.test.com",$env+"server2.test.com" }

This is a scriptblock, not an array. {} is like a function, you have to run it for it to do anything (such as evaluating $env).

When you force it into a string using -split(",") what you get is text representation of the source code in the scriptblock, including the variable names.

As @Olaf comments, the right way to create an array of names is

$servers = ($env + "server1.test.com"), ($env + "server2.test.com")

This might be how I'd write it:

$env = $env:COMPUTERNAME.Substring(0,2)

"server1.test.com", "server2.test.com" | foreach-object {
    "$env$_" -replace '\d+'
}

Upvotes: 1

Related Questions