Using Session State Variables in a Module

I just had the opportunity to watch a great Pluralsight course called PowerShell Cmdlet Development in C# - The Ins and Outs.  One feature that Nathan went over was how to use session state in a Cmdlet.

Here is how session state can help you. His example was a Cmdlet called “Invoke-SQLQuery.” As you can imagine, this cmdlet would likely have several parameters, such as “Query”, “Server”, and “Database.” He had several more as well in his course but they are not relevant for this discussion.

As a user of this cmdlet, chances are you are going to be running queries against the same server and database multiple times. It is really annoying to have to type in  values for –server and –database all the time. As an end user of the cmdlet, one way to solve this is using PowerShell’s $PSDefaultParameterValues variable.  But as the author of the cmdlet, we can help the user out as well. In fact, we don’t even need to use C# to get this functionality in our own Script Cmdlets.

If you have written advanced functions, you have probably come across the [CmdletBinding] attribute that you can use to decorate your function. Most of the time, this is used to support “ShouldProcess” to give users the –confirm and –whatif options using the automatic variable PSCmdlet.

Well, it turns out there is a lot more available to us in the $PSCmdlet variable.   Just looking at intellisense, we can see a bunch of properties and methods in there.

image

Highlighted in the screenshot, you can see SessionState. If we continue to dig into this object, we find that it has a property called PSVariable, which is another object. There are several methods on this object that we can use to set and get values.

 

This allows us to set a value of a variable for as long as the session is available. When the session is gone, so is the variable and its value. We can write a bit of code so that once you use it the first time and specify the Server, you wouldn’t have to type it in the second time. I also threw in a Try / Catch to ensure that if there is no session state variable and the user doesn’t specify a server, than we let the user know that they need to specify the server parameter. We cannot use the “Mandatory” attribute on the [Parameter()] attribute because we would get prompted every time we want to use the cached session state variable.