0

How to I add variables data inside the string element of an array? If I do $s.Length, the output is 1 instead of 2.

$IPAddress = '192.168.1.1'
[string[]]$s = (
    'https://google.com/' + $IPAddress + '/hostname',
    'https://google.com/' + $IPAddress + '/DNS'
)
foreach ($element in $s) {
    Write-Host $element
}

3 Answers 3

2

The simplest way to accomplish what you are trying (string expansion) is:

$s = "https://google.com/$IPAddress/hostname",
        "https://google.com/$IPAddress/DNS"

By using double quotes it will automatically expand $IPAddress within the strings. This works best when the variable is a string, as more complex objects may not perform as expected. If you need to reference a property of an object in this manner you will need to wrap it in $(), for example "Hello $($User.Name)!" to expand the Name property of the $User object.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was very helpful!
2

$s contains a single string because of the way you define the array. The concatenation operator (+) has a weaker precedence than the array construction operator (,). Because of that a statement

'foo' + $v + 'bar', 'foo' + $v + 'baz'

actually works like this:

'foo' + $v + @('bar', 'foo') + $v + 'baz'

Due to the string concatenation operation the array is mangled into a space-separated string (the separator is defined in the automatic variable $OFS), resulting in this:

'foo' + $v + 'bar foo' + $v + 'baz'

To avoid this behavior you need to either put the concatenation operations in grouping expressions:

$s = ('https://google.com/' + $IPAddress + '/hostname'),
     ('https://google.com/' + $IPAddress + '/DNS')

or inline the variables (requires double-quoted strings):

$s = "https://google.com/${IPAddress}/hostname",
     "https://google.com/${IPAddress}/DNS"

You could also use the format operator, but that requires grouping expressions as well:

$s = ('https://google.com/{0}/hostname' -f $IPAddress),
     ('https://google.com/{0}/DNS' -f $IPAddress)

Side note: Casting the variable to [string[]] is optional. Using the comma operator will give you an array even without an explicit cast.

Comments

1

TheMadTechnician beat me to it by a few seconds, but if you prefer to construct the string expressions explicitly, wrap them in parens:

$IPAddress = '192.168.1.1'
[string[]]$s = (
        ('https://google.com/'+$IPAddress+'/hostname'),
        ('https://google.com/'+$IPAddress+'/DNS'))
foreach ($element in $s) 
{
Write-Host $element
}

The parens force the expressions inside to be evaluated first.

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.