3

Most of out of the box PowerShell commands are returning "complex" objects.

for example, Get-Process returns an array of System.Diagnostics.Process.

All of the function I've ever wrote was returning either a simple type, or an existing kind of object.

If I want to return a home made objects, what are guidelines ?

For example, imagine I have an object with these attributes: Name, Age. In C# I would have wrote

public class Person {
    public string Name { get; set; }
    public uint Age { get; set; }
}

What are my options for returning such object from a PowerShell function ?

  1. As my goal is to create PowerShell module, should I move to a c# module instead of a ps1 file ?
  2. should I compile such objects in a custom DLL and reference it in my module using LoadWithPartialName ?
  3. Should I put my class in a powershell string, then dynamically compile it ?

2 Answers 2

11

you can use this syntax:

New-Object PSObject -Property @{
   Name = 'Bob'
   Age = 32
}
Sign up to request clarification or add additional context in comments.

Comments

5

There are a few options for creating your own object with custom properties. It is also possible to extend existing objects with additional properties. The most explicit method is to use the Add-Member cmdlet:

$test = New-Object PSCustomObject
Add-Member -InputObject $test -Name Name -Value 'Bob' -MemberType NoteProperty
Add-Member -InputObject $test -Name Age -Value 32 -MemberType NoteProperty

You can also use the fact that objects can be extended combined with the fact that Select-Object can implicitly add properties to objects in the pipeline:

$test = '' | Select @{n='Name'; e={'Bob'}}, @{n='Age'; e={32}}

Personally I prefer the first method since it is more explicit and less hand waving magic, but at the end of the day it's a scripting language so whatever works is the right way to do it.

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.