Monday, September 21, 2015

PowerShell - SessionState

SessionState is an object that reflects the current state of your PowerShell environment. You can find this object in the $ExecutionContext automatic variable:

$executioncontext.SessionState

Drive                         : System.Management.Automation.DriveManagementIntrinsics
Provider                    : System.Management.Automation.CmdletProviderManagementIntrinsics
Path                         : System.Management.Automation.PathIntrinsics
PSVariable                : System.Management.Automation.PSVariableIntrinsics
LanguageMode          : FullLanguage
UseFullLanguageModeInDebugger : False
Scripts                      : {*}
Applications              : {*}
Module                     :
InvokeProvider           : System.Management.Automation.ProviderIntrinsics
InvokeCommand       : System.Management.Automation.CommandInvocationIntrinsics


PSVariable sub-object will retrieve the value of any variable and can also be used to modify variables:
$value = "Test"

Lets retrieve variable contents by using PSVariable:
$executioncontext.SessionState.PSVariable.GetValue("value")
Test

Similarly use Set method to modify variable contents:
$executioncontext.SessionState.PSVariable.Set("value", 100)

$value
100

Remove method will simply remove the variable:
$executioncontext.SessionState.PSVariable.remove("value")
Now if you try to get the contents of variable you will get nothing:
$executioncontext.SessionState.PSVariable.GetValue("value")

You can list down all the available methods in PSVariable object by following cmdlet:
$executioncontext.SessionState.PSVariable | Get-Member -MemberType Methods

Drive subobject lets you manage drives in PowerShell. You could retrieve the current drive by Current property:
$executioncontext.SessionState.Drive.Current

GetAll() lists all available drives and is equivalent to the Get-PSDrive cmdlet:
$executioncontext.SessionState.Drive.GetAll()

No comments:

Post a Comment