Powershell: How to create custom object and pass it to function in powershell?

Question:

I want to create a custom object with properties in PowerShell and then pass that object to a function. I found the online example to create custom object, but its using HashTable. However, I have single object with properties, not an array of objects.

  1. If possible, I would like to create single object instead of
    HashTable.
  2. If HashTables are the way to go, how do I retrieve the
    object and pass it to a function?

Below is a sample of my code:

EDIT 1
Thanks @Frode and @Matt. I didn’t know that ‘return’ statement would return other results also. Will the following work?

Answer:

From about_return Its important to know that

In Windows PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword.

So as Frode said you are going to be getting a string array. You want to be returning your object as a whole and not its parts. If the purpose of your function is just to return that custom object then you can reduce that statement to a single line.

If you have at least PowerShell 3.0 then you can use the [pscustomobject] type cast to accomplish the same thing.

Note that in both cases the return keyword is optional but know that it does still serve a purpose as a logical exit of a function (all output until that point is still returned).

If you don’t need to save the results of the function in a variable you can also just chain that into your next function.

Source:

Powershell: How to create custom object and pass it to function in powershell? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply