首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用C#中的参数调用PowerShell脚本

问题:如何使用C#中的参数调用PowerShell脚本?

答案

在C#中调用PowerShell脚本,需要使用System.Management.Automation命名空间中的PowerShell类。以下是一个简单的示例:

代码语言:csharp
复制
using System.Management.Automation;

// 创建 PowerShell 引擎
PowerShell engine = PowerShell.Create();

// 设置脚本文件路径和命令参数
engine.Commands.AddScript("C:\\path\\to\\your\\script.ps1");

// 设置要传递的参数
engine.Commands[0].Parameters.Add("param1", "value1");
engine.Commands[0].Parameters.Add("param2", "value2");

// 执行脚本
engine.Invoke();

在这个示例中,我们首先创建了一个 PowerShell 引擎,然后设置了脚本文件路径和命令参数。接下来,我们使用engine.Commands.AddScript()方法添加要执行的脚本文件,并使用engine.Commands[0].Parameters.Add()方法设置参数。最后,我们使用engine.Invoke()方法执行脚本。

需要注意的是,AddScript()方法有一个参数ScriptBlock,它允许你直接编写要执行的PowerShell代码。在这种情况下,你可以使用ScriptBlock参数来调用已编写的PowerShell脚本。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券