Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

powershell - Access PSObject property indirectly with variable

Say I have JSON like:

  {
    "a" : {
        "b" : 1,
        "c" : 2
        }
  }

Now ConvertTo-Json will happily create PSObjects out of that. I want to access an item I could do $json.a.b and get 1 - nicely nested properties.

Now if I have the string "a.b" the question is how to use that string to access the same item in that structure? Seems like there should be some special syntax I'm missing like & for dynamic function calls because otherwise you have to interpret the string yourself using Get-Member repeatedly I expect.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, there is no special syntax, but there is a simple workaround, using iex, the built-in alias[1] for the Invoke-Expression cmdlet:

$propertyPath = 'a.b'

# Note the ` (backtick) before $json, to prevent premature expansion.
iex "`$json.$propertyPath" # Same as: $json.a.b

# You can use the same approach for *setting* a property value:
$newValue = 'foo'
iex "`$json.$propertyPath = `$newValue" # Same as: $json.a.b = $newValue

Caveat: Do this only if you fully control or implicitly trust the value of $propertyPath.
Only in rare situation is Invoke-Expression truly needed, and it should generally be avoided, because it can be a security risk.

Note that if the target property contains an instance of a specific collection type and you want to preserve it as-is (which is not common) (e.g., if the property value is a strongly typed array such as [int[]], or an instance of a list type such as [System.Collections.Generic.List`1]), use the following:

# "," constructs an aux., transient array that is enumerated by
# Invoke-Expression and therefore returns the original property value as-is.
iex ", `$json.$propertyPath"

Without the , technique, Invoke-Expression enumerates the elements of a collection-valued property and you'll end up with a regular PowerShell array, which is of type [object[]] - typically, however, this distinction won't matter.

Note: If you were to send the result of the , technique directly through the pipeline, a collection-valued property value would be sent as a single object instead of getting enumerated, as usual. (By contrast, if you save the result in a variable first and the send it through the pipeline, the usual enumeration occurs). While you can force enumeration simply by enclosing the Invoke-Expression call in (...), there is no reason to use the , technique to begin with in this case, given that enumeration invariably entails loss of the information about the type of the collection whose elements are being enumerated.

Read on for packaged solutions.


Note:

  • The following packaged solutions originally used Invoke-Expression combined with sanitizing the specified property paths in order to prevent inadvertent/malicious injection of commands. However, the solutions now use a different approach, namely splitting the property path into individual property names and iteratively drilling down into the object, as shown in Gyula Kokas's helpful answer. This not only obviates the need for sanitizing, but turns out to be faster than use of Invoke-Expression (the latter is still worth considering for one-off use).

    • The no-frills, get-only, always-enumerate version of this technique would be the following function:

      # Sample call: propByPath $json 'a.b'
      function propByPath { param($obj, $propPath) foreach ($prop in $propPath.Split('.')) { $obj = $obj.$prop }; $obj }
      
    • What the more elaborate solutions below offer: parameter validation, the ability to also set a property value by path, and - in the case of the propByPath function - the option to prevent enumeration of property values that are collections (see next point).

  • The propByPath function offers a -NoEnumerate switch to optionally request preserving a property value's specific collection type.

  • By contrast, this feature is omitted from the .PropByPath() method, because there is no syntactically convenient way to request it (methods only support positional arguments). A possible solution is to create a second method, say .PropByPathNoEnumerate(), that applies the , technique discussed above.

Helper function propByPath:

function propByPath {

  param(
    [Parameter(Mandatory)] $Object,
    [Parameter(Mandatory)] [string] $PropertyPath,
    $Value,               # optional value to SET
    [switch] $NoEnumerate # only applies to GET
  )

  Set-StrictMode -Version 1

  # Note: Iteratively drilling down into the object turns out to be *faster*
  #       than using Invoke-Expression; it also obviates the need to sanitize
  #       the property-path string.
  
  $props = $PropertyPath.Split('.') # Split the path into an array of property names.
  if ($PSBoundParameters.ContainsKey('Value')) { # SET
    $parentObject = $Object
    if ($props.Count -gt 1) {
      foreach ($prop in $props[0..($props.Count-2)]) { $parentObject = $parentObject.$prop }
    }
    $parentObject.($props[-1]) = $Value
  }
  else { # GET
    $value = $Object
    foreach ($prop in $props) { $value = $value.$prop }
    if ($NoEnumerate) {
      , $value
    } else {
      $value
    }
  }

}

Instead of the Invoke-Expression call you would then use:

# GET
propByPath $obj $propertyPath

# GET, with preservation of the property value's specific collection type.
propByPath $obj $propertyPath -NoEnumerate


# SET
propByPath $obj $propertyPath 'new value'

You could even use PowerShell's ETS (extended type system) to attach a .PropByPath() method to all [pscustomobject] instances (PSv3+ syntax; in PSv2 you'd have to create a *.types.ps1xml file and load it with Update-TypeData -PrependPath):

'System.Management.Automation.PSCustomObject',
'Deserialized.System.Management.Automation.PSCustomObject' |
  Update-TypeData -TypeName { $_ } `
                  -MemberType ScriptMethod -MemberName PropByPath -Value  {                  #`

                    param(
                      [Parameter(Mandatory)] [string] $PropertyPath,
                      $Value
                    )
                    Set-StrictMode -Version 1

                    
                    $props = $PropertyPath.Split('.') # Split the path into an array of property names.
                    if ($PSBoundParameters.ContainsKey('Value')) { # SET
                        $parentObject = $this
                        if ($props.Count -gt 1) {
                          foreach ($prop in $props[0..($props.Count-2)]) { $parentObject = $parentObject.$prop }
                        }
                        $parentObject.($props[-1]) = $Value
                    }
                    else { # GET
                      # Note: Iteratively drilling down into the object turns out to be *faster*
                      #       than using Invoke-Expression; it also obviates the need to sanitize
                      #       the property-path string.
                      $value = $this
                      foreach ($prop in $PropertyPath.Split('.')) { $value = $value.$prop }
                      $value
                    }

                  }

You could then call $obj.PropByPath('a.b') or $obj.PropByPath('a.b', 'new value')

Note: Type Deserialized.System.Management.Automation.PSCustomObject is targeted in addition to System.Management.Automation.PSCustomObject in order to also cover deserialized custom objects, which are returned in a number of scenarios, such as using Import-CliXml, receiving output from background jobs, and using remoting.

.PropByPath() will be available on any [pscustomobject] instance in the remainder of the session (even on instances created prior to the Update-TypeData call [2]); place the Update-TypeData call in your $PROFILE (profile file) to make the method available by default.


[1] Note: While it is generally advisable to limit aliases to interactive use and use full cmdlet names in scripts, use of iex to me is acceptable, because it is a built-in alias and enables a concise solution.

[2] Verify with (all on one line) $co = New-Object PSCustomObject; Update-TypeData -TypeName System.Management.Automation.PSCustomObject -MemberType ScriptMethod -MemberName GetFoo -Value { 'foo' }; $co.GetFoo(), which outputs foo even though $co was created before Update-TypeData was called.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...