5

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.

1
  • 3
    Take a look at the Add-Member cmdlet. Commented Nov 5, 2018 at 18:22

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.