温馨提示×

如何使用C#编写PowerShell脚本

c#
小樊
98
2024-08-10 11:42:47
栏目: 编程语言

要在C#中编写PowerShell脚本,可以使用System.Management.Automation命名空间中的类和方法。以下是一个简单的示例代码,演示如何在C#中编写一个PowerShell脚本:

using System;
using System.Management.Automation;

class Program
{
    static void Main(string[] args)
    {
        // 创建PowerShell对象
        using (PowerShell ps = PowerShell.Create())
        {
            // 添加脚本命令
            ps.AddScript("Get-Process");

            // 执行脚本
            var results = ps.Invoke();

            // 处理脚本执行结果
            foreach (var result in results)
            {
                Console.WriteLine(result.ToString());
            }
        }
    }
}

在上面的示例中,我们首先创建一个PowerShell对象,然后添加要执行的脚本命令(这里是"Get-Process",用于获取当前正在运行的进程)。然后调用Invoke方法执行脚本,并处理脚本执行结果。

需要注意的是,编写PowerShell脚本时需要引用System.Management.Automation程序集,可以在项目中添加引用。另外,需要在程序中使用using指令引入System.Management.Automation命名空间。

0