user3325210
user3325210

Reputation: 163

Session Info in global variables

I have a function in PowerShell, which establishes a session and stores the info in global variables:

$global:transport = new-object Fix.ServerSocketTransport $FixHost, $FixPort

Now, within the application the $global:transport variable is used to send and receive the data.

After the script execution ends will the session be closed? Will the $global:transport value be reset? (I have commented out the part where we disconnect the session)

After the script ends, even though I do not create a new session, it sends and receives data through $global:transport variable. Why does this happen?

Upvotes: 0

Views: 1213

Answers (1)

Keith Hill
Keith Hill

Reputation: 201952

Globals are indeed global to the session. After you script executes (and creates the global) that variable and its value persists. BTW PowerShell / .NET do not automatically close objects. If the object implements a finalizer then when it is collected via garbage collection (at some indeterminate time in the future) then the finalizer will run and close or release associated native resources. If the object implements IDisposable or otherwise has a Close() or Dispose() method on it, you should call that method when you're done with the object. Also, in order to keep PowerShell from hanging onto the object forever (you did put it in a global), you can either A) set the global variable to $null or B) (and even better) remove the variable altogether using Remove-Variable.

Another option is to create a script scope variable in your outter most script (startup script). This script variable should be visible to any other scripts you execute and will go away when the script is finished. However, as in the case above, if the object implement Close() or Dispose() you should call that on the object when you're done with it.

Upvotes: 2

Related Questions