Reputation: 468
How do I write val1 in the below string? This should be really straight forward surely, but I can't find an example anywhere
$jsobj = @"
{
val1 : "test",
val2 : "test1"
}
"@ | ConvertFrom-Json
Write-Host @"
Value of val1: $jsobj.val1
"@
Upvotes: 0
Views: 397
Reputation: 25001
You will need to prevent early expansion of your variable to access its property value. The sub-expression operator $()
allows everything inside to be evaluated as an expression.
$jsobj = @"
{
val1 : "test",
val2 : "test1"
}
"@ | ConvertFrom-Json
Write-Host @"
Value of val1: $($jsobj.val1)
"@
When a variable is inside an expandable string (one with outer double quotes), the variable is substituted with its ToString()
value. Anything after that variable is treated as part of the string rather than the variable. See below for a trivial example.
$str = 'my string'
"$str.Length"
my string.Length
Upvotes: 2