[英]How to run PowerShell script in C# from relative path?
我正在尝试从我的C#应用程序运行PowerShell脚本。 我知道如何用绝对路径这样做:
using (PowerShell pshell = PowerShell.Create())
{
pshell.AddScript( @"C:\Path\To\Webapp\psScript.ps1" );
pshell.Invoke();
}
我不知道该怎么做是使用相对路径。 我的psScript.ps1
与我的Visual Studio项目位于同一目录中,我想使用相对路径(例如./psScript.ps1
),这样当我将项目发布/导出到不同的计算机时,脚本的路径不会失效
那么,如何在PowerShell.AddScript()方法中使用相对路径? 任何帮助,将不胜感激!
我看了这里,但这不回答我的问题: PowerShell:从脚本的目录运行命令
用这个:
using (PowerShell pshell = PowerShell.Create())
{
string path=System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
pshell.AddScript( path+"\\psScript.ps1" );
pshell.Invoke();
}
此路径始终相对于项目的根文件夹。
将您的脚本添加到项目并将Copy to output directory
属性设置为Copy always
或Copy id newer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.