Clear all $Session: variables?

Is there a way to clear all $Session: variables at once? In the post below, it seems there is a way to do it with $Cache.

Product: PowerShell Universal
Version: 3.3.2

You can use:

$UDEndpointService.SessionManager.Sessions.Clear()

If you want to keep the sessions but remove session variables:

$UDEndpointService.SessionManager.Sessions | ForEach-Object {
     $_.SessionVariables.Clear()
}

Can this be used in a dashboard? Will this clear all session variable for all users on all dashboards, or only for the user who is visiting the dashboard that has this on it?

1 Like

This can be used in a dashboard but will only clear the sessions for the dashboard being accessed. We could implement some new functionality (like Clear-UDSession) to achieve multi-dashboard session clearing.

Just to 100% make sure, is there a way to clear the Session variables for just 1 users session?

I’m thinking this: Say you have a form show up in a Modal. Form variables are saved to $Session variables. User is able to hide the form to do some other tasks related to filling out this form, then pull it back up with their “work” saved. But they can also cancel it and clear the variables.

You can certainly do that as well. The variables are just a concurrent dictionary. You’d have to reference the session and then remove the variable. $SessionId is an automatic variable that will be in the runspace that you can reference to get the current session ID.

$UDEndpointService.SessionManager.Sessions[$SessionId].SessionVariables.Clear()
1 Like

I just tried this in a dashboard in 3.3.4 and got ‘cannot index into a null value’ error. Is the $UDEndpointService variable is exposed to dashboards or just the API stack?

Whoops. I mixed up two different variables. Try this.

New-UDDashboard -Content { 
    $Session:MyVariable = '123'
    New-UDButton -Text 'test' -OnClick {
        $EndpointService.SessionManager.Sessions[$SessionId].SessionVariables.Clear()
        Show-UDToast $Session:MyVariable
    }
}