program tip

객체에 특정 속성이 있는지 어떻게 테스트 할 수 있습니까?

radiobox 2020. 10. 29. 07:59
반응형

객체에 특정 속성이 있는지 어떻게 테스트 할 수 있습니까?


객체에 특정 속성이 있는지 어떻게 테스트 할 수 있습니까?

할 수있어 감사합니다 ...

$members = Get-Member -InputObject $myobject 

그런 다음을 foreach통해 $members객체에 특정 속성이 있는지 테스트하는 기능이 있습니까?

추가 정보 : 문제는 두 가지 종류의 CSV 파일을 가져 오는 것입니다. 하나에는 두 개의 열이 있고 다른 하나에는 세 개의 열이 있습니다. "Property"와 함께 작동하는 수표를 얻을 수 없었습니다. "NoteProperty"에서만 작동 합니다. 차이점이 무엇이든간에

if ( ($member.MemberType -eq "NoteProperty" ) -and ($member.Name -eq $propertyName) ) 

이렇게?

 [bool]($myObject.PSobject.Properties.name -match "myPropertyNameToTest")

당신이 사용할 수있는 Get-Member

if(Get-Member -inputobject $var -name "Property" -Membertype Properties){
#Property exists
}

이것은 간결하고 읽기 쉽습니다.

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

함수에 넣을 수 있습니다.

function HasProperty($object, $propertyName)
{
    $propertyName -in $object.PSobject.Properties.Name
}

"속성"이 존재하고 임의의 예외를 throw하지 않는 경우 를 통해 액세스 할 수 있으므로 속성 값$thing.$prop반환 하는 다음을 사용하고 있습니다 . 속성이 "존재하지 않음"(또는 null 값이 있음)이면 $null반환됩니다.이 접근 방식은 엄격 모드 에서 작동 / 유용 합니다 . 왜냐하면 Gonna Catch 'em All.

이 접근 방식 을 사용하면 PS Custom Objects, 일반 .NET 개체, PS HashTables 및 Dictionary와 같은 .NET 컬렉션을 "duck-typed equivalent"로 처리 할 수 ​​있으므로 PowerShell에 상당히 적합하다고 생각합니다.

물론, 이것은 이 질문이 명시 적으로 제한 될 수있는 "속성 있음".. 엄격한 정의를 충족하지 않습니다 . 여기서 가정 한 "속성"의 더 큰 정의를 받아들이면 부울을 반환하도록 메서드를 사소하게 수정할 수 있습니다.

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

예 :

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"

그리고이 동작은 [항상] 바람직하지 않을 수도 있습니다. 즉. x.Count를 구별 할 수 없습니다 x["Count"].


StrictMode를 사용 중이고 psobject가 비어있는 경우 오류가 발생합니다.

모든 목적을 위해 다음을 수행합니다.

    if (($json.PSobject.Properties | Foreach {$_.Name}) -contains $variable)

자바 스크립트 검사와 진짜 비슷합니다.

foreach($member in $members)
{
    if($member.PropertyName)
    {
        Write $member.PropertyName
    }
    else
    {
        Write "Nope!"
    }
}

다음 객체를 명확히하기 위해

$Object

다음 속성으로

type        : message
user        : john.doe@company.com
text        : 
ts          : 11/21/2016 8:59:30 PM

다음은 사실입니다

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

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

따라서 이름으로 속성을 명시 적으로 확인하는 이전 답변은 해당 속성이 존재하지 않는지 확인하는 가장 올바른 방법입니다.


null을 확인하십시오.

($myObject.MyProperty -ne $null)

If you have not set PowerShell to StrictMode, this works even if the property does not exist:

$obj = New-Object PSObject;                                                   
Add-Member -InputObject $obj -MemberType NoteProperty -Name Foo -Value "Bar";
$obj.Foo; # Bar                                                                  
($obj.MyProperty -ne $null);  # False, no exception

I ended up with the following function ...

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; 
    }
}

I recently switch to set strict-mode -version 2.0 and my null tests failed.

I added a function:

#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
}

Now I code

if (exists $run main) { ...

rather than

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

and we are on our way. Seems to work on objects and hashtables

As an unintended benefit it is less typing.


I just started using PowerShell with PowerShell Core 6.0 (beta) and following simply works:

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

or

if (-not $members.NoteProperty) {
   # NoteProperty does not exist
}

You could check with:

($Member.PropertyNames -contains "Name") this will check for the Named property


For identifying which of the objects in an array have a property

$HasProperty = $ArrayOfObjects | Where-Object {$_.MyProperty}

참고URL : https://stackoverflow.com/questions/26997511/how-can-you-test-if-an-object-has-a-specific-property

반응형