Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand member-variables in Write-Host or double quotes?

Tags:

powershell

I have written a PS script and for diagnostic purpose am echoing messages to screen using Write-Host. This is fine as long as I have to expand normal variable like

Write-Host "Hello World, $name"

Problem starts when i try to echo some member variable as below

Write-Host "Hello World, $Person.Name" 

This does not expand as expected. The work around that am following is, to use temp variable as below

$personName  = $Person.Name Write-Host "Hello World, $personName" 

Is there an elegant way of doing this with out the use of temp variable?

like image 232
Jeevan Avatar asked May 17 '11 17:05

Jeevan


People also ask

How do you add double quotes to a variable in PowerShell?

To include the double quotes inside of the string, you have two options. You can either enclose your string in single quotes or escape the double quotes with a symbol called a backtick. You can see an example of both below of using PowerShell to escape double quotes. Notice that "string" now includes the double quotes.

How do you put a variable in a quote in PowerShell?

To prevent the substitution of a variable value in a double-quoted string, use the backtick character ( ` ), which is the PowerShell escape character. $i = 5 "The value of `$i is $i."

How do you pass a variable to 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.

How do I change a variable value in PowerShell?

In PowerShell we can use the Replace() method on any string or variable that is a string. The method needs two arguments, the text or character that you want to find and the with what you want to replace it with.


1 Answers

If you want to use property access within double-quoted strings, you need a subexpression:

"Foo $($bar.Property)" 
like image 140
Joey Avatar answered Oct 22 '22 09:10

Joey