Root cause
Here is the background information:
- When running the same unchanged script file multiple times, the script file will not be re-parsed. Instead, the AST will be used.
- When re-using the AST, we will reuse the same .NET type generated for a powershell class.
- At compilation time,
ScriptBlockMemberMethodWrapper.InitAtRuntime will be called to bound the static method of a powershell class to the [Runspace, SessionState] where the compilation is happening.
This causes a problem -- a static method of powershell class will always execute in the [Runspace, SessionState] where the script file that defines it lastly run.
Steps to reproduce
class.ps1 -- defines a powershell class Foo
class Foo
{
static [string] GetName()
{
return (Get-Name)
}
}
test.ps1
Dot source class.ps1, create function Get-Name and run [Foo]::GetName().
Then create a new runspace, define another Get-Name and dot source class.ps1 in that runspace.
Then run [Foo]::GetName() again.
. $PSScriptRoot\class.ps1
function Get-Name
{
"Console Runspace"
}
[Foo]::GetName()
$ps = [powershell]::Create()
$ps.AddScript("function Get-Name { 'powershell instance Runspace' }").Invoke()
$ps.Commands.Clear()
$ps.AddScript(". $PSScriptRoot\class.ps1").Invoke()
[Foo]::GetName()
Then just run test.ps1 in powershell
Expected behavior
Since I'm running both [Foo]::GetName() in the default console runspace, I expect the same result.
Console Runspace
Console Runspace
Actual behavior
Console Runspace
powershell instance Runspace
Environment data
> $PSVersionTable
Name Value
---- -----
PSVersion 6.0.0-beta
PSEdition Core
CLRVersion
GitCommitId v6.0.0-beta.2-22-g7a51b446e5cc428efd634e8a8a38271156cc182b
OS Microsoft Windows 10.0.15063
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
Root cause
Here is the background information:
ScriptBlockMemberMethodWrapper.InitAtRuntimewill be called to bound the static method of a powershell class to the [Runspace, SessionState] where the compilation is happening.This causes a problem -- a static method of powershell class will always execute in the [Runspace, SessionState] where the script file that defines it lastly run.
Steps to reproduce
Expected behavior
Actual behavior
Environment data