4

I'm trying to run a PowerShell script from my C# application. I know how to do so with an absolute path:

    using (PowerShell pshell = PowerShell.Create())
    {
        pshell.AddScript( @"C:\Path\To\Webapp\psScript.ps1" );
        pshell.Invoke();
    }

What I don't know how to do is use a relative path. My psScript.ps1 is located in the same directory as my Visual Studio project, and I'd like to use a relative path (such as ./psScript.ps1), so that when I publish/export my project to different computers, the path to the script doesn't become invalidated

Sooo, how do I use a relative path in the PowerShell.AddScript() method? Any help would be appreciated!

I looked here but this doesn't answer my question: PowerShell: Run command from script's directory

2 Answers 2

6

Use this:

using (PowerShell pshell = PowerShell.Create())
    {
        string path=System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        pshell.AddScript( path+"\\psScript.ps1" );
        pshell.Invoke();
    }

This path is always relative to the root folder of your project.

Sign up to request clarification or add additional context in comments.

2 Comments

Is this the same as the $(ProjectDir) directory? I just printed the result of the path string in your above example and it was a very different location. Thank you, nonetheless. This puts me a lot closer to finding the solution than I was before
path in your case is the path of the executable not of the project root. It is same as pshell.AddScript( "psScript.ps1" );
3

Add your script to project and set Copy to output directory property to Copy always or Copy id newer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.