Save return.response

Hello again,

I would like to save the result that I get in this script in a variable so I can use it later

$resultclient_full_name=return $response.client_full_name
write-host "This is the result" $resultclient_full_name

Does it make sense?

Hi,
Return keyword is used in a function to terminate the function scope and return back to the caller scope.
So in your case, you shouldn’t be using it

$resultclient_full_name = hostname
Write-host 'This is the result:' $resultclient_full_name
1 Like

Thank you DejvDzi for your reply. This is in the case there is only one return, what if I have it like this:

return $response.LicenseKey,$response.Id
How can I save in the way that you explained before in a variable only the response for the LicenseKey?

Hi,
Unfortunately it’s not enough information, can you show the whole function or script?

If you have more than one value being output, you can store in more than one variable.

$first,$second = 1,2

If there are more than two values being output, you could add more variables to catch them else you can understand the first will get the first value and the second will get the remaining values

$first,$therest = 1,2,3,4

# contains 1
$first

#contains 2,3,4
$therest

Unfortunately I can not post the script here as per it has some sensible data on it but the idea is from my script to register a machine and return the Id of this machine also the license key. That is why my return is return $response.LicenseKey,$response.Id and I need to separate the LicenseKey and the Id from each other so when I do invoke-expression -Command .\Get_machine_Key.ps1 in another script I can receive the LicenseKey and use it for my purposes. It would be good to save it separately here the answer in this script before I do the invoke in the other script .

Part of the script is:

$headers = @{
    "Content-Type" ="application/json"
    "X-UIPATH-TenantName" ="default"
    
    "Authorization" = " "
}

$json = $payload | ConvertTo-Json
$response = Invoke-RestMethod -Method 'Post' -Uri $registerMachineUrl -Body $json -Headers $headers

return $response.Id,$response.LicenseKey

Well I am not sure if my explanation makes sense but hope you can get the idea.

PowerShell is all about the objects. Your function should return an object:

function Get-Licence {
    $response = @{
        Header     = 'blah'
        User       = 'bob'
        Id         = 12345
        LicenceKey = 'ce4a11f0-c3c5-4f32-8bae-f101730a6d1d'
    }

    [PSCustomObject]@{
        Id         = $response.Id
        LicenceKey = $response.LicenceKey 
    }
}

$data = Get-Licence

Write-Host "Id is $($data.Id), Licence Key is $($data.Licencekey)"

Note: you don’t even need the return keyword unless you specifically want to exit the function at that point.

1 Like