访问子作用域的 SessionStateProxy

Access SessionStateProxy of child scope

在 运行 powershell.AddScript("code", true); 之后,如何访问已创建的子作用域的会话 (SessionStateProxy)?

SessionStateProxy 属性 属于 runspace 托管执行上下文:

// 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);
}

以上将打印C:\some\path(假设该目录存在)。