0

Given this piece of code

$Object = @"
{
    "Item1":{
        "Subitem1":{
            "Subsubvalue":"Value"
        }
    },
    "Value1":"value1"
}

"@ | ConvertFrom-Json 

and given the following string (that I don't know at runtime, I've just got a string with an object path)

$String = "$Object.Item1.Subitem1.Subsubvalue"

I am trying to do the following - but I can't find a way to make it work

PS C:\> $Substring = $string.substring(8)
PS C:\> $Object.$Substring 
Value 

My ultimate goal is to get to modify the contents of that

PS C:\> $Object.$Substring = "something else" 

Obviously $substring approach doesn't work, nor the other approaches I've tried.

1
  • For me, its not clear what you want to achive. There are multiple outcomes that I can imagine with multiple ways to do it. Commented May 15, 2017 at 13:06

3 Answers 3

2

You can use Invoke-expression to handle this as it will parse the string passed to it as if it was a command.

So you can do the following:

Invoke-Expression -Command "$string"

This will return:

Value

So you can then do:

Invoke-Expression -Command "$String = `"Something else`""

Which will set the value to "Something else".

Sign up to request clarification or add additional context in comments.

Comments

1

Invoke-Expression is no better than eval in other languages. It's far too likely to do something undesired/unexpected because it evaluates the given string as code. I would not recommend going that route unless you know exactly what you're doing.

Try a recursive function instead:

function Get-NestedItem {
    Param(
        [Parameter(Mandatory=$true, Position=0)]
        $InputObject,

        [Parameter(Mandatory=$false, Position=1)]
        [AllowEmptyString()]
        [string]$Path = '',

        [Parameter(Mandatory=$false, Position=2)]
        [string]$Delimiter = '.'
    )

    if ($Path) {
        $child, $rest = $Path.Split($Delimiter, 2)
        Get-NestedItem $InputObject.$child $rest
    } else {
        $InputObject
    }
}

$Object = ...
$Path   = 'Item1.Subitem1.Subsubvalue'

Get-NestedItem $Object $Path

1 Comment

That's an interesting approach! I'll try it out. (and I see your point about the security risk too)
0

You might also consider using a dedicated function to do this work rather than depending on Invoke-Expression. Solutions like this are detailed in this tread.

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.