After running powershell.AddScript("code", true);
how do I get access to the session (SessionStateProxy
) of the child scope that was created?
CodePudding user response:
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).