如何从相对路径在C#中运行PowerShell脚本?

tou*_*ody 3 c# powershell

我正在尝试从C#应用程序运行PowerShell脚本。我知道如何使用绝对路径:

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

我不知道该怎么做是使用相对路径。我psScript.ps1的目录与Visual Studio项目位于同一目录中,并且我想使用相对路径(例如./psScript.ps1),这样当我将项目发布/导出到不同的计算机时,脚本的路径就不会变成无效

那么,如何在PowerShell.AddScript()方法中使用相对路径?任何帮助,将不胜感激!

我在这里看了一下,但这没有回答我的问题: PowerShell:从脚本目录运行命令

Tom*_*lav 5

用这个:

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

此路径始终相对于项目的根文件夹。