¿Cómo se puede probar si un objeto tiene una propiedad específica?


¿Cómo se puede probar si un objeto tiene una propiedad específica?

Aprecio que puedo hacer ...

$members = Get-Member -InputObject $myobject 

Y luego foreach a través de $members, pero ¿hay una función para probar si el objeto tiene una propiedad específica?

Información Adicional: El problema es que estoy importando dos tipos diferentes de archivo CSV, uno con dos columnas, el otro con tres. No pude conseguir que el cheque funcionara con "Propiedad", solo con" NoteProperty"... cualquiera que sea la diferencia

if ( ($member.MemberType -eq "NoteProperty" ) -and ($member.Name -eq $propertyName) ) 
Author: SteveC, 2014-11-18

12 answers

¿Así?

 [bool]($myObject.PSobject.Properties.name -match "myPropertyNameToTest")
 62
Author: CB.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-18 15:42:28

Puedes usar Get-Member

if(Get-Member -inputobject $var -name "Property" -Membertype Properties){
#Property exists
}
 37
Author: Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-21 13:12:58

Esto es sucinto y legible:

"MyProperty" -in $MyObject.PSobject.Properties.Name

Podemos ponerlo en una función:

function HasProperty($object, $propertyName)
{
    $propertyName -in $object.PSobject.Properties.Name
}
 6
Author: dan-gph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-26 06:52:55

Real similar a una comprobación de javascript:

foreach($member in $members)
{
    if($member.PropertyName)
    {
        Write $member.PropertyName
    }
    else
    {
        Write "Nope!"
    }
}
 2
Author: YtramX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-18 15:13:57

Si está utilizando StrictMode y el psobject puede estar vacío, le dará un error.

Para todos los propósitos esto servirá:

    if (($json.PSobject.Properties | Foreach {$_.Name}) -contains $variable)
 2
Author: Ádám Kovács,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-20 14:29:04

He estado usando lo siguiente que devuelve el valor de la propiedad, ya que se accedería a través de $thing.$prop, si la" propiedad " sería existir y no lanzar una excepción aleatoria. Si la propiedad "no existe" (o tiene un valor nulo) entonces se devuelve $null: este enfoque funciona en/es útil para modo estricto, porque, bueno, va a atraparlos a Todos.

Encuentro útil este enfoque porque permite Objetos personalizados de PS, objetos normales. NET, HashTables de PS y. NET las colecciones como Dictionary deben ser tratadas como"duck-typed equivalent" , lo que me parece un ajuste bastante bueno para PowerShell.

Por supuesto, esto no cumple con la definición estricta de "tiene una propiedad".. a los que esta pregunta puede limitarse explícitamente. Si se acepta la definición más amplia de "propiedad" asumida aquí, el método se puede modificar trivialmente para devolver un booleano.

Function Get-PropOrNull {
    param($thing, [string]$prop)
    Try {
        $thing.$prop
    } Catch {
    }
}

Ejemplos:

Get-PropOrNull (Get-Date) "Date"                   # => Monday, February 05, 2018 12:00:00 AM
Get-PropOrNull (Get-Date) "flub"                   # => $null
Get-PropOrNull (@{x="HashTable"}) "x"              # => "HashTable"
Get-PropOrNull ([PSCustomObject]@{x="Custom"}) "x" # => "Custom"
$oldDict = New-Object "System.Collections.HashTable"
$oldDict["x"] = "OldDict"
Get-PropOrNull $d "x"                              # => "OldDict"

Y, este comportamiento podría no ser deseado [siempre].. IE. no es posible distinguir entre x.Count y x["Count"].

 2
Author: user2864740,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-18 17:36:12

Simplemente marque con null.

($myObject.MyProperty -ne $null)

Si no ha establecido PowerShell en StrictMode , esto funciona incluso si la propiedad no existe:

$obj = New-Object PSObject;                                                   
Add-Member -InputObject $obj -MemberType NoteProperty -Name Foo -Value "Bar";
$obj.Foo; # Bar                                                                  
($obj.MyProperty -ne $null);  # False, no exception
 1
Author: Shaun Luttin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-28 16:53:05

Terminé con la siguiente función ...

function HasNoteProperty(
    [object]$testObject,
    [string]$propertyName
)
{
    $members = Get-Member -InputObject $testObject 
    if ($members -ne $null -and $members.count -gt 0) 
    { 
        foreach($member in $members) 
        { 
            if ( ($member.MemberType -eq "NoteProperty" )  -and `
                 ($member.Name       -eq $propertyName) ) 
            { 
                return $true 
            } 
        } 
        return $false 
    } 
    else 
    { 
        return $false; 
    }
}
 0
Author: SteveC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-19 10:01:59

Solo para aclarar dado el siguiente objeto

$Object

Con las siguientes propiedades

type        : message
user        : [email protected]
text        : 
ts          : 11/21/2016 8:59:30 PM

Lo siguiente es cierto

$Object.text -eq $NULL
$Object.NotPresent -eq $NULL

-not $Object.text
-not $Object.NotPresent

Así que las respuestas anteriores que comprueban explícitamente la propiedad por nombre es la forma más correcta de verificar que esa propiedad no está presente.

 0
Author: John Mello,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-22 14:59:58

Acabo de empezar a usar PowerShell con PowerShell Core 6.0 (beta) y lo siguiente simplemente funciona:

if ($members.NoteProperty) {
   # NoteProperty exist
}

O

if (-not $members.NoteProperty) {
   # NoteProperty does not exist
}
 0
Author: hshib,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-10 21:33:44

Recientemente cambié a set strict-mode-version 2.0 y mis pruebas null fallaron.

He añadido una función:

#use in strict mode to validate property exists before using
function exists {
  param($obj,$prop)
  try {
    if ($null -ne $obj[$prop]) {return $true}
    return $false
  } catch {
    return $false
  }
  return $false
}

Ahora codigo

if (exists $run main) { ...

En lugar de

if ($run.main -ne $null) { ...

Y estamos en camino. Parece funcionar en objetos y hashtables

Como un beneficio no deseado es menos escribir.

 0
Author: Steve Pritchard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-29 23:03:48

Usted podría comprobar con:

($Member.PropertyNames -contains "Name") esto comprobará la propiedad nombrada

 -1
Author: Tom Stryhn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-10 08:31:05