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

Viewed 20044

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:

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
2 Answers
Related