source

PowerShell 개체에서 멤버를 제거하시겠습니까?

nicesource 2023. 10. 21. 10:32
반응형

PowerShell 개체에서 멤버를 제거하시겠습니까?

개체에서 멤버(특히 노트 속성)를 제거해야 합니다.어떻게 하면 이것을 해낼 수 있을까요?

Select-Object와 함께ExcludeProperty객체 집합에서 속성을 제거하는 데 좋습니다.

단일 개체에서 속성을 제거하려면 다음 방법이 더 효과적일 수 있습니다.

# new object with properties Test and Foo
$obj = New-Object -TypeName PSObject -Property @{ Test = 1; Foo = 2 }

# remove a property from PSObject.Properties
$obj.PSObject.Properties.Remove('Foo')

기존 개체에서는 제거할 수 없지만 필터링된 개체는 생성할 수 있다고 생각합니다.

$obj = New-Object -TypeName PsObject -Property @{ Test = 1}
$obj | Add-Member -MemberType NoteProperty -Name Foo -Value Bar
$new_obj = $obj | Select-Object -Property Test

아니면

$obj | Select-Object -Property * -ExcludeProperty Foo

이렇게 하면 효과적으로 같은 결과를 얻을 수 있습니다.

큰 개체에서 한두 개의 속성만 제거하고 싶다면 다음과 같은 도움이 필요합니다.개체를 JSON으로 변환한 다음 개체로 다시 변환합니다. 모든 속성이 NoteProperty 유형으로 변환되어 원하는 항목을 제거할 수 있습니다.

   $mycomplexobject = $mycomplexobject | ConvertTo-Json | ConvertFrom-Json

    $mycomplexobject.PSObject.Properties.Remove('myprop')

JSON과 back으로 변환하면 PSCustomObject가 생성됩니다.원래 개체를 표현한 다음 원하는 대로 제거할 수 있습니다.

제거할 개체 또는 컬렉션의 유형에 따라 달라질 수 있습니다.일반적으로 꽤 쉽게 할 수 있는 'import-csv'에서 얻을 수 있는 것과 같은 객체의 모음(array)입니다.

$MyDataCollection = Import-CSV c:\datafiles\ADComputersData.csv
$MyDataCollection
Windows Server : lax2012sql01
IP             : 10.101.77.69
Site           : LAX
OS             : 2012 R2
Notes           : V

Windows Server : sfo2016iis01
IP             : 10.102.203.99
Site           : SFO
OS             : 2012 R2
Notes           : X

다음 각 항목에서 속성을 제거하는 방법:

$MyDataCollection | ForEach { $_.PSObject.Properties.Remove('Notes') }

Windows Server : lax2012sql01
IP             : 10.101.77.69
Site           : LAX
OS             : 2012 R2

Windows Server : sfo2016iis01
IP             : 10.102.203.99
Site           : SFO
OS             : 2012 R2

언급URL : https://stackoverflow.com/questions/17905060/remove-a-member-from-a-powershell-object

반응형