Share via


about_PSCustomObject

Descripción breve

Explica las diferencias entre los aceleradores de [psobject] tipos y [pscustomobject] .

Descripción larga

El [pscustomobject] acelerador de tipos se agregó en PowerShell 3.0.

Antes de agregar este acelerador de tipos, la creación de un objeto con propiedades y valores de miembro era más complicado. Originalmente, tenía que usar New-Object para crear el objeto y Add-Member agregar propiedades. Por ejemplo:

PS> $object1 = New-Object -TypeName PSObject
PS> Add-Member -InputObject $object1 -MemberType NoteProperty -Name one -Value 1
PS> Add-Member -InputObject $object1 -MemberType NoteProperty -Name two -Value 2
PS> $object1 | Get-Member

   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
one         NoteProperty int one=1
two         NoteProperty int two=2

PS> $object1

one two
--- ---
  1   2

Más adelante, puede usar el parámetro Property de New-Object para pasar una tabla Hash que contenga los miembros y los valores. Por ejemplo:

PS> $object2 = New-Object -TypeName PSObject -Property @{one=1; two=2}
PS> $object2 | Get-Member

   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
one         NoteProperty int one=1
two         NoteProperty int two=2

PS> $object2

one two
--- ---
  1   2

Desde PowerShell 3.0, la conversión de una tabla Hash para [pscustomobject] lograr el mismo resultado.

PS> $object3 = [pscustomobject]@{one=1; two=2}
PS> $object3 | Get-Member

   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
one         NoteProperty int one=1
two         NoteProperty int two=2

PS> $object3

one two
--- ---
  1   2

Los objetos de tipo PSObject mantienen la lista de miembros en el orden en que los miembros se agregaron al objeto . Aunque los objetos Hashtable no garantizan el orden de los pares clave-valor, convierta una tabla hash literal para [pscustomobject] mantener el orden.

La tabla hash debe ser un literal. Si encapsula la tabla hash entre paréntesis o si convierte una variable que contiene una tabla hash, no hay ninguna garantía de que se conserve el orden.

$hash = @{
    Name      = "Server30"
    System    = "Server Core"
    PSVersion = "4.0"
}
$Asset = [pscustomobject]$hash
$Asset
System      Name     PSVersion
------      ----     ---------
Server Core Server30 4.0

Descripción de los aceleradores de tipos

[psobject] y [pscustomobject] son aceleradores de tipos.

Para obtener más información, consulte about_Type_Accelerators.

Aunque podría pensar que [pscustomobject] debería asignarse a System.Management.Automation.PSCustomObject, los tipos son diferentes.

PS> [pscustomobject] -eq [System.Management.Automation.PSCustomObject]
False

Ambos aceleradores de tipos se asignan a la misma clase, PSObject:

PS> [pscustomobject]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     PSObject                                 System.Object

PS> [psobject]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     PSObject                                 System.Object

Cuando se agregó el [pscustomobject] acelerador de tipos a PowerShell, incluía código adicional para controlar la conversión de una tabla Hash a un tipo PSObject . Este código adicional solo se invoca cuando se crea un nuevo objeto. Por lo tanto, no se puede usar [pscustomobject] para la coerción de tipos o la comparación de tipos, ya que todos los objetos se tratan como tipos PSObject .

Por ejemplo, usar el -is operador para comprobar que un objeto devuelto por un cmdlet es [pscustomobject] el mismo que compararlo con [psobject].

PS> (Get-Item /) -is [pscustomobject]
True

PS> (Get-Item /) -is [psobject]
True

Al convertir cualquier objeto a [psobject] obtener el tipo del objeto original. Por lo tanto, la conversión de cualquier cosa que no sea una tabla hash para [pscustomobject] dar como resultado el mismo tipo.

PS> ([psobject]@{Property = 'Value'}).GetType().FullName
System.Collections.Hashtable

PS> ([pscustomobject]123).GetType().Name
Int32

PS> ([pscustomobject]@{Property = 'Value'}).GetType().FullName
System.Management.Automation.PSCustomObject

Aunque la conversión de un objeto a [psobject] parece no tener ningún efecto en el tipo, PowerShell agrega un contenedor invisible[psobject] alrededor del objeto. Esto puede tener efectos secundarios sutiles.

  • Los objetos ajustados coincidirán con su tipo original y el [psobject] tipo .

    PS> 1 -is [Int32]
    True
    PS> 1 -is [psobject]
    False
    PS> ([psobject] 1) -is [Int32]
    True
    PS> ([psobject] 1) -is [psobject]
    True
    
  • El operador de formato (-f) no reconoce una matriz ajustada por [psobject].

    PS> '{0} {1}' -f (1, 2)
    1 2
    PS> '{0} {1}' -f ([psobject] (1, 2))
    Error formatting a string: Index (zero based) must be greater than or equal
    to zero and less than the size of the argument list..
    

Notas

En Windows PowerShell, los objetos creados mediante la conversión de una tabla Hash para [pscustomobject] no tener las propiedades Length o Count. Al intentar acceder a estos miembros, se devuelve $null.

Por ejemplo:

PS> $object = [PSCustomObject]@{key = 'value'}
PS> $object

key
---
value

PS> $object.Count
PS> $object.Length

A partir de PowerShell 6, los objetos creados mediante la conversión de una tabla Hash siempre [pscustomobject] tienen un valor de 1 para las propiedades Length y Count.

Consulte también