简体   繁体   中英

Powershell: difference between assignment and parameter for cmdlet (parsing)

I am new to powershell language and I have problems understanding some basic concepts regarding string concatenation.

I tried to concat a string with the + char as I knew it from other programming languages ie Java.

line 1: $result = 7
line 2: Write-Host "Result: " + $result + "!" # Result:  + 7 + !

I then realized (ie in this question How do I concatenate strings and variables in PowerShell? ) that I need to do it (in one of) the powershell way(s); for example like this.

line 3: Write-Host "Result: $result!" # Result: 7!

As I experimented a little I found out that if I assign the expression in line 2 to a variable it somehow works as I anticipated it in the first place.

line 4: $str = "Result: " + $result + "!"
line 5: Write-Host $str # Result: 7!

So my question is, why is there a difference if I pass a Java-style concatenated string to Write-Output cmdlet or if I assign the same string to a variable?

String concatenation and expansion is a bit different in PowerShell, here are several ways to accomplish it-


Format operator:

PS C:\> 'This exhibits {0} string expansions! {1} {0}!' -f @(2,'Wow!')
This exhibits 2 string expansions! Wow! 2!

Each item in the array is accessed by the number in the braces.

Subexpression:

PS C:\> "Sometimes you need calculations in a string. 5 + 3 = $(5 + 3)"
Sometimes you need calculations in a string. 5 + 3 = 8

An explanation here: this will not work with string literals, ie, '' . Everything contained in the subexpression will be evaluated and converted to a string if possible utilizing an object's ToString() method.

String Expansion:

 PS C:\> $Var = 'This string'
 PS C:\> "$Var is amazing!"
 This string is amazing!

This will also not work with string literals, ie, '' . If you need to concatenate a variable-qualifying character next to the variable call, you can use curly braces to avoid a null value, ie, ${Var}_notattached

String Concatenation:

Tried and true:

PS C:\> 'Sometimes you just ' + 'need to add. 8 = ' + 8
Sometimes you just need to add. 8 = 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM