本文介绍了什么对象适合添加成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档说明:

将用户定义的自定义成员添加到Windows PowerShell 的一个实例对象.

Windows PowerShell 对象"代表什么?

What "Windows PowerShell object" stands for?

这很好用:

$obj = new-object system.object
$obj | add-member -membertype noteproperty -name Name -value "OK"
$obj.name

但这不会:

$obj = @{}

实际上,我正在尝试向 $error[0] 添加属性.

Actually, I am trying to add property to $error[0].

推荐答案

PowerShell 具有所谓的 PSObject,它是任何 .NET 对象(或者它可以是完全自定义的对象)的包装器,当您调用 Add-Member 时,PowerShell 使用 PSObject 隐式包装真正的 .NET 对象.

PowerShell has what's called a PSObject that is a wrapper around any .NET object (or it can be a totally custom object) and when you call Add-Member, PowerShell is implicitly wrapping the real .NET object with a PSObject.

Add-Member 的工作方式取决于您是否从 PSObject 开始.如果您没有从 PSObject 开始,Add-Member 会将输入包装在 PSObject 中,您需要重新分配变量才能看到适配的对象.

The way Add-Member works depends on whether or not you started with a PSObject. If you did not start with a PSObject, Add-Member will wrap the input in a PSObject and you'll need to re-assign the variable in order to see the adapted object.

例如:

$x = [Environment]::OSVersion
$x | Add-Member NoteProperty IsVista $true
$x | Format-List   # does not show the new property

这是因为 OSVersion 没有包装成 PSObject.Add-Member 确实包装了它,但该包装器丢失了,因为您没有将 $x 重新分配给包装的对象.与此行为对比:

This is because OSVersion is not wrapped is a PSObject. Add-Member does wrap it but that wrapper is lost because you're not re-assigning $x to the wrapped object. Contrast with this behavior:

$x = New-Object OperatingSystem ('Win32NT', '6.0')
$x | Add-Member NoteProperty IsVista $true
$x | Format-List   # DOES show the new property

这是因为 New-Object 将新实例隐式包装在 PSObject 中.因此,您的 Add-Member 调用正在向现有包装器添加成员.

This is because New-Object implicitly wraps the new instance in a PSObject. So your Add-Member call is adding members to the existing wrapper.

回到第一个示例,您可以通过将其更改为:

Going back to the first example, you can make it work as expected by changing it to:

$x = [Environment]::OSVersion
$x = $x | Add-Member NoteProperty IsVista $true -PassThru
$x | Format-List   # DOES show the new property

现在毕竟,Hashtable 不能按您期望的方式工作的原因是因为 PowerShell 对 Hashtables 进行了特殊处理,并且基本上 Hashtables 的适配器使用键作为属性(有点)而 Add-Member 不会使用这种对象按预期工作.

Now after all that, the reason that the Hashtable doesn't work the way you expect is because Hashtables are treated special by PowerShell and basically the adapter for Hashtables uses the keys as properties (kinda) and Add-Member won't work as expected with this kind of object.

这篇关于什么对象适合添加成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 19:30
查看更多