Lost Crotchet
Lost Crotchet

Reputation: 1400

Correct way to add a string property to existing Powershell object?

So for example, I have a custom object for $server. I want to create a new property, $server.output to contain multi line output of varying size. What is the best approach to take? There doesn't seem to be any straight forward information on the web around how to add simple string properties to objects?

FYI I am using powershell v4, but it would be nice to have a solution for v5 too.

Upvotes: 5

Views: 3632

Answers (1)

Maximilian Burszley
Maximilian Burszley

Reputation: 19684

Outside of re-creating the object or ensuring the property exists on object initialization, you have to use Add-Member to create new properties on a pscustomobject:

# alternatively, use `-Force` on `Add-Member`
if (-not ($obj | Get-Member -Name output))
{
    $obj | Add-Member -MemberType NoteProperty -Name output -Value ''
}

Supported in v3+:

$obj | Add-Member -NotePropertyName output -NotePropertyValue '' -Force

Add multiple members:

$obj | Add-Member -NotePropertyMembers @{output = ''; output1 = ''} -Force

Add-Member

Upvotes: 7

Related Questions