从C#运行PowerShell脚本

10

我正在尝试使用Visual Studio构建一个图形平台。但是我不是开发人员,我想在单击按钮时运行PowerShell或批处理文件。问题是,当我尝试使用C#语法时,即使安装了PowerShell扩展,它也无法工作。

我尝试了一些在互联网上找到的代码,使用process.start或尝试创建一个命令,在所有情况下命令的名称都未定义,因此无法工作。

private void Button1_Click(object sender, EventArgs e)
{
    Process.Start("path\to\Powershell.exe",@"""ScriptwithArguments.ps1"" ""arg1"" ""arg2""");
}

我想运行我的 .ps1 脚本,但是出现了错误。

名称“process”未定义


1
“name process is not defined”是编译错误还是运行时错误? - harper
File.Exists("U:\\folder1\\folder2\\Test.ps1") 是否存在? - xdtTransform
当然,该文件存在。 - Rhon Yz
您可以通过使用System.Management.Automation中的PowerShell类直接从C#代码中使用PowerShell。这里是一个链接到msdn博客,展示了如何实现此功能。 - MadKarel
1
我认为这个链接 https://dev59.com/MnRB5IYBdhLWcg3wv5o_ 可能会有帮助。 - techguy1029
显示剩余4条评论
3个回答

6

在Powershell中调用C#代码,反之亦然

Powershell中的C#

$MyCode = @"
public class Calc
{
    public int Add(int a,int b)
    {
        return a+b;
    }
    
    public int Mul(int a,int b)
    {
        return a*b;
    }
    public static float Divide(int a,int b)
    {
        return a/b;
    }
}
"@

Add-Type -TypeDefinition $MyCode
$CalcInstance = New-Object -TypeName Calc
$CalcInstance.Add(20,30)

Powershell在C#中
所有与Powershell相关的函数都位于System.Management.Automation命名空间中,...在您的项目中引用它。
 static void Main(string[] args)
        {
            var script = "Get-Process | select -Property @{N='Name';E={$_.Name}},@{N='CPU';E={$_.CPU}}";

            var powerShell = PowerShell.Create().AddScript(script);

            foreach (dynamic item in powerShell.Invoke().ToList())
            {
                //check if the CPU usage is greater than 10
                if (item.CPU > 10)
                {
                    Console.WriteLine("The process greater than 10 CPU counts is : " + item.Name);
                }
            }

            Console.Read();
        }

所以,你的问题实际上也是stackoverflow上许多类似帖子的重复。
Powershell命令在C#中的链接:Powershell Command in C#

2
string path = @"C:\1.ps1";

Process.Start(new ProcessStartInfo("Powershell.exe",path) { UseShellExecute = true })

这并没有回答问题。一旦您拥有足够的声望,您将能够评论任何帖子;相反,提供不需要询问者澄清的答案。- 来自审核 - MD. RAKIB HASAN

1

以下是对我有效的方法,包括参数包含空格的情况:

using (PowerShell PowerShellInst = PowerShell.Create())
        {

            PowerShell ps = PowerShell.Create();
            
            string param1= "my param";
            string param2= "another param";
            string scriptPath = <path to script>;

            ps.AddScript(File.ReadAllText(scriptPath));

            ps.AddArgument(param1);
            ps.AddArgument(param2);

            ps.Invoke();
         
        }

这个.ps1文件应该长成这样(确保在.ps1脚本中声明了参数):

Param($param1, $param2)

$message = $param1 + " & " + $param2"
[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
[System.Windows.Forms.MessageBox]::Show($message)

我觉得这种方法很容易理解,非常清晰。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接