0

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
"@

2
  • 1
    Use $($jsobj.val1) Commented Aug 5, 2020 at 3:19
  • Cheers - I was trying things like that but with curly braces - if you put this as an answer I'm happy to mark it as that Commented Aug 5, 2020 at 3:36

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.