Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate variable expansion to create a string in Powershell

Tags:

powershell

How do I tell powershell the end of a variable to be expanded into a string when it sits next to other alphabetic characters?

$StringToAdd = "iss"
$CompeteString = "Miss$StringToAddippi"

Thanks!

like image 529
Brian Wochele Avatar asked Jul 18 '13 18:07

Brian Wochele


People also ask

How do I create a string 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 I unset a variable in PowerShell?

The Clear-Variable cmdlet deletes the data stored in a variable, but it does not delete the variable. As a result, the value of the variable is NULL (empty). If the variable has a specified data or object type, this cmdlet preserves the type of the object stored in the variable.

How do I expand a string in PowerShell?

So, you can use $ExecutionContext. InvokeCommand. ExpandString("$Domain\$User") and voila! You've expanded your string.

Does PowerShell have string interpolation?

Using PowerShell, you can interpolate a literal string containing one or more placeholders. The output of that command replaces the placeholder with the value it contains. Many programming languages make use of string interpolation or variable interpolation.


2 Answers

Use curly braces, { and }, to delimit the variable expansion. For example:

PS C:\> $StringToAdd = "iss"
PS C:\> $CompeteString = "Miss${StringToAdd}ippi"
PS C:\> $CompeteString
Mississippi
like image 138
Don Cruickshank Avatar answered Oct 20 '22 15:10

Don Cruickshank


You can use $()

PS C:\> $StringToAdd = "iss"
PS C:\> $CompeteString = "Miss$($StringToAdd)ippi"
PS C:\> $CompeteString
Mississippi

The sub-expression operator for double-quoted strings is described here. Whatever is in the brackets should be evaluated first. This can be a variable or even an expression.

PS C:\> $CompeteString = "Miss$($StringToAdd.length * 2)ippi"
PS C:\> $CompeteString
Miss6ippi
like image 3
bouvierr Avatar answered Oct 20 '22 14:10

bouvierr