0

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.

2
  • If you like to create an array you should use parenthesis for each single expression instead of curly braces for all expressions. $servers = ($env + "server1.test.com"), ($env + "server2.test.com") Commented Mar 21, 2018 at 1:41
  • Thanks Olaf. It worked Commented Mar 21, 2018 at 13:42

1 Answer 1

1
$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+'
}
Sign up to request clarification or add additional context in comments.

Comments

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.