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.
- If possible, I would like to create single object instead of
HashTable. - 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
function CreateObject() { $properties = @{ 'TargetServer' = “ServerName”; 'ScriptPath' = “SomePath”; 'ServiceName' = "ServiceName" } $obj = New-Object -TypeName PSObject -Property $properties Write-Output $obj.TargetServer Write-Output $obj.ScriptPath Write-Output $obj.ServiceName return $obj } function Function2([PSObject] $obj) { Do something here with $obj } $myObj = CreateObject Function2 $myObj |
EDIT 1
Thanks @Frode and @Matt. I didn’t know that ‘return’ statement would return other results also. Will the following work?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
function CreateObject() { return New-Object -TypeName PSObject -Property @{ 'TargetServer' = "ServerName" 'ScriptPath' = "SomePath" 'ServiceName' = "ServiceName" } } function Init() { // Do something here $myObject = CreateObject() // Do something here with $myObject return $myObject } function Funcntion2([PSObject] $obj) { //Do somthing with $obj } $obj = Init Function2 $obj |
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.
1 2 3 4 5 6 7 8 9 |
function CreateObject() { return New-Object -TypeName PSObject -Property @{ 'TargetServer' = "ServerName" 'ScriptPath' = "SomePath" 'ServiceName' = "ServiceName" } } |
If you have at least PowerShell 3.0 then you can use the [pscustomobject]
type cast to accomplish the same thing.
1 2 3 4 5 6 7 8 9 |
function CreateObject() { return [pscustomobject] @{ 'TargetServer' = "ServerName" 'ScriptPath' = "SomePath" 'ServiceName' = "ServiceName" } } |
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.
1 2 |
Function2 (CreateObject) |