访问嵌套属性

时间:2018-07-10 13:49:29

标签: powershell object properties

是否可以通过使用变量名来访问嵌套属性?

一些代码需要澄清:

$MyObject = [PSCustomObject]@{
    Name = 'Object name'
    Input = @{
        Error = @{
            Terminating = @(
                [PSCustomObject]@{
                    Type = 'Error.Terminating'
                    Name = 'MissingParameter'
                    Description = $null
                    Value = @($null)
                }
            )
            NonTerminating = @(
                [PSCustomObject]@{
                    Type = 'Error.NonTerminating'
                    Name = 'FileNotMoved'
                    Description = $null
                    Value = @($null)
                }
            )
        }
        Warning = @(
            [PSCustomObject]@{
                Type = 'Warning'
                Name = 'ADObjectConflict'
                Description = $null
                Value = @($null)
            }
        )
    }
}
# Correct result    
$MyObject.Input.Error.Terminating

# Incorrect result    
$string = 'Error.Terminating'
$MyObject.Input.$string

# Incorrect result        
$MyObject.Input.($MyObject.Input.Error.Terminating[0].Type)

最后两个语句不返回有问题的对象。如果可以使用变量来解决它们,那就太好了。

1 个答案:

答案 0 :(得分:0)

就像@TheIncorregible指出的那样,Error and Terminating are two different objects。您可以执行类似的解决方法,以获得所需的结果:

# Correct result    
$property1 = 'Error'
$property2 = 'Terminating'

$MyObject.Input.($property1).($property2)

这样,我们得到以下输出:

Type              Name             Description Value  
----              ----             ----------- -----  
Error.Terminating MissingParameter             {$null}