Sharing the runspace between PowerShell ASP requests


The EnableCacheRunspace configuration setting can be used to allow multiple PowerShell ASP requests to access the same runspace. This allows variables to be stored and accessed again later in a different request. For instance, creating a new PSSession for every request would add unnecessary time to each request, so it would be helpful to store the connection so it can be accessed again.

Below is an example of how to use the EnableCacheRunspace configuration setting to establish a persistent connection to Office 365 that can be accessed through multiple requests.

  1. Create a DWORD named EnableCacheRunspace in HKEY_LOCAL_MACHINE\SOFTWARE\nsoftware\PowerShell\ASP\16 and give it a value of 1.
  2. Create and store a New-PSSession object:
    $password = ConvertTo-SecureString $plaintextpassword -AsPlainText -Force
    $credentials = New-Object -typename System.Management.Automation.PSCredential ($username,$password)
    $pssession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $cred -Authentication Basic -AllowRedirection -WarningAction silentlycontinue
    
  3. The $pssession variable can now be used in multiple requests with the Invoke-Command cmdlet to run a command on the stored session:
    Invoke-Command -Session $pssession { Get-User }
    

We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.