Suppose I have the following snippet:
$assoc = New-Object PSObject -Property @{ Id = 42 Name = "Slim Shady" Owner = "Eminem" } Write-Host $assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner
I'd expect this snippet to show:
42 - Slim Shady - Eminem
But instead it shows:
42 + - + Slim Shady + - + Eminem
Which makes me think the +
operator isn't appropriate for concatenating strings and variables.
How should you approach this with PowerShell?
In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect. let myPet = 'seahorse'; console.
To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.
You can create a variable by simply assigning it a value. For example, the command $var4 = “variableexample” creates a variable named $var4 and assigns it a string value. The double quotes (” “) indicate that a string value is being assigned to the variable.
PowerShell has another option that is easier. You can specify your variables directly in the strings. $message = "Hello, $first $last." The type of quotes you use around the string makes a difference.
Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"
See the Windows PowerShell Language Specification Version 3.0, p34, sub-expressions expansion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With