使用命令行参数从 C# 执行文件的 PowerShell 脚本

Execute PowerShell Script of flie from C# with Commandline Arguments

我尝试使用来自 c# 程序的参数文件启动 ps1。但是在这之前,我试着把它做得更小,运行一个"ls ."但是它不起作用,我认为我的代码是可以的。

pipeline.Commands.Add("ls ."); //in future here path of .ps1 file + arguments
Collection<PSObject> results;
// Execute PowerShell script
results = pipeline.Invoke();
//print it in a textbox
AppendLine(results.ToString());

我作为参考使用Execute PowerShell Script from C# with Commandline Arguments

错误是“System.Management.Automation.CommandNotFoundException:'ls .' 不是 cmdlet、函数或 bat 文件。

您的表达式 ls . 包含一个命令(或者更确切地说,一个别名)ls 一个参数参数 .

构建该表达式的正确方法是:

Command lsCmd = new Command("ls");
lsCmd.Parameters.Add("Path",".");
Pipeline.Commands.Add(lsCmd);