Search code examples
powershellhashtablekey-valuepscustomobject

Access multiple outputs from a script by symbolic names (keys)


I'm a beginner in powershell scripting, I want to be able to distinguish between the outputs of a script. Lets take as an example this script test.ps1:

param([System.String] $w)
$x=$w+" is correct"
$y=$w+ " is false"
$x
$y

to execute it and retrieve the values $x & $y, I'm doing this:

$a=.\test1.ps1 -w test
$a[0] #this is x
$a[1] # this is y

is there a way we can use something similar to $a.x to retrieve the $x value?

Thanks.


Solution

  • To do what you want, you will need an object that contains a key/value pair or named properties. For example, you can create an object called a with properties x and y:

    $x = "one"
    $y = "two"
    $a = [pscustomobject]@{"x"=$x;"y"=$y}
    

    Testing the Above Case:

    $a
    
    x   y
    -   -
    one two
    
    $a.x
    one
    $a.y
    two
    

    I like the link PSCustomObjects for an explanation of creating and using custom objects.

    Testing with a Function:

    function test {
    
    param([string] $w)
    
    $x = $w + "x"
    $y = $w + "y"
    
    [pscustomobject]@{"x"=$x; "y"=$y}
    }
    
    $a = test "my property "
    $a
    
    x             y
    -             -
    my property x my property y
    
    
    $a.x
    my property x
    $a.y
    my property y