0

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

4

1 回答 1

1

SessionStateProxy属性属于托管执行上下文的运行空间:

// 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(假设该目录存在)。

于 2022-01-25T12:25:24.823 回答