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

后端 未结 2 997
遥遥无期
遥遥无期 2021-01-06 21:24

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 Has

相关标签:
2条回答
  • 2021-01-06 22:10

    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.

    0 讨论(0)
  • 2021-01-06 22:15

    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)
    
    0 讨论(0)
提交回复
热议问题