tags:

views:

347

answers:

3

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();
}
+1  A: 

Anything wrong with doing:

pipeline.Commands.AddScript(@"set-location c:\scripts;.\foo.ps1")

?

-Oisin

x0n
+1  A: 

You can set the working directory in powershell with the following command

set-location c:\mydirectory

You can also try your PowerShell startup script ($profile). C:....\MyDocs\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 But only if this directory is fixed and does not change

Binoj Antony
+3  A: 

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.

Jaykul