更新物件

新增屬性

如果要向現有物件新增屬性,可以使用 Add-Member cmdlet。使用 PSObjects,值儲存在註釋屬性型別中

$object = New-Object -TypeName PSObject -Property @{
        Name = $env:username
        ID = 12
        Address = $null
    }

Add-Member -InputObject $object -Name "SomeNewProp" -Value "A value" -MemberType NoteProperty

# Returns
PS> $Object
Name ID Address SomeNewProp
---- -- ------- -----------
nem  12         A value

你還可以使用 Select-Object Cmdlet 新增屬性(所謂的計算屬性):

$newObject = $Object | Select-Object *, @{label='SomeOtherProp'; expression={'Another value'}}

# Returns
PS> $newObject
Name ID Address SomeNewProp SomeOtherProp
---- -- ------- ----------- -------------
nem  12         A value     Another value

上面的命令可以縮短為:

$newObject = $Object | Select *,@{l='SomeOtherProp';e={'Another value'}}

刪除屬性

你可以使用 Select-Object Cmdlet 從物件中刪除屬性:

$object = $newObject | Select-Object * -ExcludeProperty ID, Address

# Returns
PS> $object
Name SomeNewProp SomeOtherProp
---- ----------- -------------
nem  A value     Another value