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?
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.
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."
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.
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.
If you want to use property access within double-quoted strings, you need a subexpression:
"Foo $($bar.Property)"
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