Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate strings and variables in PowerShell?

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?

like image 595
Ninja Cowgirl Avatar asked Feb 27 '13 13:02

Ninja Cowgirl


People also ask

How do you concatenate strings and variables?

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.

How do you concatenate strings and numbers?

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.

How do you assign a string value to a variable in PowerShell?

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.

How do you call a variable in a string in PowerShell?

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.


1 Answers

Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)" 

See the Windows PowerShell Language Specification Version 3.0, p34, sub-expressions expansion.

like image 185
David Brabant Avatar answered Sep 27 '22 23:09

David Brabant