C# 调用powershell
时间: 2023-11-22 07:45:16 浏览: 64
C#可以通过System.Management.Automation命名空间中的类来调用PowerShell命令。有两种方法可以实现这一点:一种是在运行的过程中打开PowerShell界面,另一种是不打开界面,直接运行命令。
以下是在运行的过程中打开PowerShell界面的示例代码:
```
using System.Diagnostics;
Process p = Process.Start("powershell.exe");
p.Start();
```
以下是不打开界面,直接运行命令的示例代码:
```
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading.Tasks;
namespace testCentennial
{
class Program
{
static void Main(string[] args)
{
var command = "Get-Process";
using (PowerShell ps = PowerShell.Create())
{
ps.AddScript(command);
var results = ps.Invoke();
foreach (var result in results)
{
Console.WriteLine(result.ToString());
}
}
}
}
}
```
需要注意的是,使用PowerShell命令需要管理员权限。如果没有管理员权限,可以使用以下代码来获取管理员权限:
```
var process = new Process();
process.StartInfo.FileName = "powershell.exe";
process.StartInfo.Arguments = "-Command \"Start-Process powershell -Verb RunAs\"";
process.Start();
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)