Variables don't persist when using persistentrunspace environment

Product: PowerShell Universal
Version: 1.5.19

Hi

My issue is that variables set in one API call don’t persist in other calls even though a persistent runspace environment is used

It’s possible I don’t quite understand how persistent runspaces are supposed to work but I feel that I have things set up correctly, please let me know what I’m doing wrong here

environments.ps1:

New-PSUEnvironment -Name "env" -path "/usr/bin/pwsh" -PersistentRunspace

settings.ps1:

Set-PSUSetting -APIEnvironment 'env'

endpoints.ps1:

New-PSUEndpoint -Url "/test1" -Endpoint {
    $x = 1
    return $x
}

New-PSUEndpoint -Url "/test2" -Endpoint {
    return $x
}

I would expect GET /test2 to return 1 here, but the variable is empty

Thanks

Persistent runspaces will persist variables but PSU is still using a runspace pool. You’re likely hitting two separate runspaces. You will want to use the cache if you want to persist information across runspaces.

Hey @ScalbyLausisJim , you can also use a global variable to persist between APIs. The persistent Runspaces switch needs to be enabled in the environment.

# API 1
$Global:xobj = "Hello"

# API 2
$xobj

2 Likes

Hi Adam
Thanks for the advice, that works to an extent, but I am having trouble properly deserializing the output of Get-PSUCache (am working with custom classes that contain other custom classes)

Are the PSUCache commands simply wrappers around Import/Export-CliXml cmdlets? Or is there anything extra going on behind the scenes? I have written a method to deserialize the cached objects which works correctly when dealing with the output of Import-CliXml but not with Get-PSUCache

I am tempted to use Export-CliXml directly instead of the PSUCache commands, unless there is some reason not to? Or alternatively use global variables as suggested above

Thanks

The PSUCache cmdlets using the PSSerializer class which serializes and deserializes CliXml.

With the introduction of the $Cache scope in PSUv2, you’ll be able to set items into memory without the CliXml serialization.

New-PSUEndpoint -Url "/test1" -Endpoint {
    $Cache:x = 1
    return $Cache:x
}

New-PSUEndpoint -Url "/test2" -Endpoint {
    return $Cache:x
}

The cache scope will go across runspaces and won’t using any type of serialization.

Thanks Adam, this works great

I will note that I didn’t need to set up a persistent environment or set an API environment for the variables in the $cache scope to persist, not sure if this is intended

Cheers

That’s intentional. Glad it’s working!

1 Like