Remove a Member from a PowerShell Object?

假装没事ソ 提交于 2019-12-03 10:29:03

问题


I need to remove a member (specifically, a NoteProperty) from an object. How do I accomplish this?


回答1:


Select-Object with ExcludeProperty is good for removing a property from a collection of objects.

For removing a property from a single object this method might be more effective:

# 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')



回答2:


I don't think you can remove from an existing object but you can create a filtered one.

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

Or

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

This will effectively achieve the same result.




回答3:


I found the following helps if you're interested in removing just one or two properties from a large object. Convert your object into JSON then back to an object - all the properties are converted to type NoteProperty, at which point you can remove what you like.

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

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

The conversion to JSON and back creates a PSCustomObject. You'll have the original object expressed and then you can remove as desired.




回答4:


If can depend on the type of object or collection you want to remove from. Commonly its a Collection (array) of objects like you might get from 'import-csv' which you can do it pretty easily.

$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

The to remove a property from each of these:

$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


来源:https://stackoverflow.com/questions/17905060/remove-a-member-from-a-powershell-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!