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.
Below is a sample of my code:
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?
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
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.
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.
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.
Function2 (CreateObject)
You are creating an object. The hash table is just placeholder used to define all properties before turning them into an object.
Remove the three lines starting with write-output
and you should be good. They are unnecessary and makes your function return an array and not just the object like you wanted. Use write-host
if you only want to display the values to the screen while testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With