Search code examples
c#powershellpowershell-7.2

Access SessionStateProxy of child scope


After running powershell.AddScript("code", true); how do I get access to the session (SessionStateProxy) of the child scope that was created?


Solution

  • The SessionStateProxy property belongs to the runspace hosting the execution context:

    // API will automatically create a default runspace when you don't explicitly pass one to PowerShell.Create()
    using (PowerShell ps = PowerShell.Create())
    {
      ps.Runspace.SessionStateProxy.SetVariable("targetPath", @"C:\some\path");
      // side-effect from `Set-Location` called from child scope is the same as when run in calling scope
      ps.AddScript(@"Set-Location -LiteralPath $targetPath", true);
      ps.AddStatement();
      // location change still persists in parent scope
      ps.AddScript(@"$PWD.Path");
    
      foreach(var outputItem in ps.Invoke())
        Console.WriteLine(outputItem.BaseObject);
    }
    

    The above will print C:\some\path (assuming that that directory exists).