In the new version of Universal Dashboard, two new variables scopes have been added to allow for scoping variables that make sense within a web application. Cache scope can be used to define and use variables stored within the ASP.NET Core Memory Cache and Session scope can be used to store session specific values.

The first implementation of these used a cmdlet to get and set these values but it became very cumbersome and made scripts very messy. After doing some investigation, I found that you could define what appear to be different variable scopes in PowerShell using a custom provider.

The end result is a lot prettier.

In UD, you can now just assign values to variables with the Cache or Session prefix. Those variables are then accessible during other requests to the dashboard.

Creating your own variable scope

In order to expose a similar functionality in your modules you’ll need to create a custom provider. The cache provider defines a type that extends from ContainerCmdletProvider and implements IContentCmdletProvider.

In order to offer a scope without having the user to do anything, you need to define a default drive. Override the InitializeDefaultDrives method and create a drive. This will serve as the name of the scope that you are defining.

Next, you’ll need to override some additional methods to allow for item cmdlet support. This enables the ability to create new variables, clear variables and test whether variables exist.

In order to read and write the value of your variables, you need to create a IContentReader and IContentWriter. This can be one class that just implements the reading and writing of variables. In my implementation, I’m reading and writing values to the memory cache.

The last step is to expose your content reader and writer from the provider class.

Once you’ve completed all these steps, you’ll have your very own variable scope! You can store your data however you see fit. I’m using the memory cache but you could easily store it to disk or into a database. It’s a nifty little trick that made Universal Dashboard scripts a lot more readable.

If you want to play with the new variable scopes in Universal Dashboard, download the latest on the PSGallery.