Return variable names and values from a function

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of bvi1998 . bvi1998 . 8 months, 3 weeks ago.

  • Author
    Posts
  • #36902
    Profile photo of bvi1998 .
    bvi1998 .
    Participant

    Hi,
    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(" ","_")
    $tag2=$json.type
    $tag3=$json.virtual_subtype

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

    Can someone advise me?

    Thanks!

  • #36905
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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
    
    $result.Tag1
    $result.Tag2
    $result.Tag3
    
  • #36912
    Profile photo of bvi1998 .
    bvi1998 .
    Participant

    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
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator
    Tag1 = $json.os -replace ' ','_' -replace '_\([^()]*\)$'
    

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

  • #36916
    Profile photo of bvi1998 .
    bvi1998 .
    Participant

    Works perfectly thanks!

    deleting my text, things are working now...

    Thanks!

You must be logged in to reply to this topic.