Skip to content

PowerShell class static method has inconsistent behavior when the .ps1 file is dot sourced into multiple Runspace's #4001

@daxian-dbw

Description

@daxian-dbw

Root cause

Here is the background information:

  1. When running the same unchanged script file multiple times, the script file will not be re-parsed. Instead, the AST will be used.
  2. When re-using the AST, we will reuse the same .NET type generated for a powershell class.
  3. 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

.\test.ps1

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

Metadata

Metadata

Assignees

Labels

Resolution-FixedThe issue is fixed.WG-Enginecore PowerShell engine, interpreter, and runtime

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions