如何使用变量名从对象访问属性?

jot*_*t19 5 powershell object powershell-5.0

这有效:

$psISE.Options.DebugBackgroundColor = '#FFC86400'
Run Code Online (Sandbox Code Playgroud)

这不会:

$attribute = 'DebugBackgroundColor' 
($psISE.Options)[$attribute] = '#FFC86400'
Run Code Online (Sandbox Code Playgroud)

错误:无法索引 Microsoft.PowerShell.Host.ISE.ISEOptions 类型的对象

我想foreach使用$attribute变量在循环中设置选项属性。

有没有办法做到这一点?

Mar*_*ndl 7

只需在点后使用双引号即可:

$attribute = 'DebugBackgroundColor'
$psISE.Options."$attribute"
Run Code Online (Sandbox Code Playgroud)

  • 不需要双引号。这个工作得很好:`$psISE.Options.$attribute`。 (6认同)