I'm using the System.Management.Automation API to call PowerShell scripts a C# WPF app. In the following example, how would you change the start directory ($PWD) so it executes foo.ps1 from C:\scripts\ instead of the location of the .exe it was called from?
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline())
{
pipeline.Commands.Add(@"C:\scripts\foo.ps1");
pipeline.Invoke();
}
runspace.Close();
}
You don't need to change the System.Environment.CurrentDirectory
to change the working path for your PowerShell scripts. It can be quite dangerous to do this because this may have unintentional side effects if you're running other code that is sensitive to your current directory.
Since you're providing a Runspace
, all you need to do is set the Path
properties on the SessionStateProxy
:
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
runspace.SessionStateProxy.Path.SetLocation(directory);
using (Pipeline pipeline = runspace.CreatePipeline())
{
pipeline.Commands.Add(@"C:\scripts\foo.ps1");
pipeline.Invoke();
}
runspace.Close();
}
Setting System.Environment.CurrentDirectory
ahead of time will do what you want.
Rather than adding Set-Location
to your scrip, you should set System.Environment.CurrentDirectory
any time before opening the Runspace. It will inherit whatever the CurrentDirectory is when it's opened:
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
System.Environment.CurrentDirectory = "C:\\scripts";
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline())
{
pipeline.Commands.Add(@".\foo.ps1");
pipeline.Invoke();
}
runspace.Close();
}
And remember, Set-Location
doesn't set the .net framework's CurrentDirectory
so if you're calling .Net methods which work on the "current" location, you need to set it yourself.
Anything wrong with doing:
pipeline.Commands.AddScript(@"set-location c:\scripts;.\foo.ps1")
?
-Oisin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With