Return variable names and values from a function

This topic contains 4 replies, has 2 voices, and was last updated by  bvi1998 . 2 years, 3 months ago.

  • Author
  • #36902

    bvi1998 .

    I am calling another script, (or could be a function), which gathers data from a website, then sets variable names to the values retrieved. I want to return the variable names as well as their values to my parent script.

    Here is are the script results:

    $tag1 = ($json.os).Replace(" ","_")

    I need to have the variable names $tag1, $tag2, and $tag3 and their values returned to the parent script.

    Can someone advise me?


  • #36905

    Dave Wyatt

    It would be a better practice to return a single object. The caller can assign it to whatever variable they like:

    # in your function:
    [pscustomobject] @{
        Tag1 = ($json.os).Replace(" ","_")
        Tag2 = $json.type
        Tag3 = $json.virtual_subtype
    # Out in the calling code:
    $result = Do-Something # placeholder for the call to your function
  • #36912

    bvi1998 .

    That works perfectly thanks!

    One last part is that I need to trim the results of Tag1 further.

    $tag1 is now Microsoft_Windows_Server_2003_Standard_(32-bit)

    Sometimes $tag1 might be Microsoft_Windows_Server_2003_Enterprise_(64-bit)

    I will need to trim everything after the "_" which is following the Enterprise or Standard. This value could be different depending upon what the $tag1 ends up being. In every case, all I want is the OS (Microsoft_Windows_Server_2003_Enterprise) not anything after that string.

    Would you please help me with this?
    Thanks so much!

  • #36914

    Dave Wyatt
    Tag1 = $json.os -replace ' ','_' -replace '_\([^()]*\)$'

    It's basically hieroglyphics, but that's a regex to trim "_(Whatever)" from the end of the string.

  • #36916

    bvi1998 .

    Works perfectly thanks!

    deleting my text, things are working now...


You must be logged in to reply to this topic.