I'm running a PowerShell script from a .NET application, but it's failing because $PSScriptRoot
is not set. How can I set it?
Code:
var ps = PowerShell.Create();
ps.Runspace.SessionStateProxy.Path.SetLocation(dir);
var withScript = ps.AddScript(File.ReadAllText(Path));
var results = ps.Invoke();
I have also attempted to set it using:
ps.Runspace.SessionStateProxy.SetVariable("PSScriptRoot", dir, "Script root");
but it remains empty in the script.
This also didn't work:
ps.Runspace.SessionStateProxy.SetVariable("PSScriptRoot", dir, "Script root", ScopedItemOptions.AllScope);
I tried using a different name to see if it's somehow reserved, or being overwritten, but it was also empty.
The following fails with an error that PSScriptRoot cannot be replaced because it has been optimized:
var test = new PSVariable("PSScriptRoot", dir, ScopedItemOptions.AllScope);
runspace.SessionStateProxy.PSVariable.Set(test);