Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope vs Runspace vs Session vs AppDomain

I'm struggling to draw the boundaries in my head for PowerShell. My very limited understanding is this:

  • A Scope contains user/script defined variables and functions, and there can be a hierarchy of scopes with a PS call stack.
  • A Runspace dictates what built-in functionality a given PS instance has access to. A Runspace can cross network boundaries.
  • A Session is a specific instance of Powershell. These can cross network boundaries as well.
  • An Application Domain (or AppDomain) contains loaded assemblies. In many cases, once data has been loaded into an AppDomain, it cannot be unloaded. The AppDomain must be disposed of in favor of a new one. If PS scripts are invoked via another application, the PS instance that gets created inherits the AppDomain of the invoking application.

Can anyone explain these concepts better? Is there some sort of Venn diagram or something that fleshes this information out? The online docs haven't been extremely helpful.

like image 223
neumann1990 Avatar asked Jan 18 '17 19:01

neumann1990


1 Answers

The most convenient way to think of these is in a sort of reverse-order to the way you've listed them:

All AppDomain instances are hosted inside of a Windows Process, by the .NET Common Language Runtime (CLR). An AppDomain is like a Windows Process in that it is a security boundary. In general, code in one app domain is not allowed to directly cross over to a different app domain.

A Windows PowerShell Runspace is the location where the PowerShell runtime actually gets created. It provides some of the core infrastructure, such as the creation of pipelines. This is a .NET object, and it inherits the parent app domain. It does have remoting capabilities, but they're not really related to anything provided intrinsically by the .NET Framework. Instead, the remoting capability is provided by the Windows PowerShell product infrastructure.

A single runspace can be the host to multiple sessions. A session instance may exist as a purely local construct on the local machine, or could exist elsewhere on your network. When a command is issued against a remote session, the command itself is sent to the remote hosting provider, executed, and the results of the entire pipeline returned to the original requestor.

There are several different scopes, which are hierarchical in nature. There's the top-level scope, function scope, module scope, script scope, etc. When naming collisions occur between scopes, the most local scope wins. Scopes also give you the ability to hide data, which is a very useful feature if you're building a module. Any scope can be accessed by name, along with the variable name. An example of this is $script:myVar.

like image 158
PSGuy Avatar answered Oct 31 '22 06:10

PSGuy