从命令行我可以做到.
.\test.ps1 1
Run Code Online (Sandbox Code Playgroud)
从C#执行此操作时如何传递参数?我试过了
.AddArgument(1)
.AddParameter("p", 1)
Run Code Online (Sandbox Code Playgroud)
我已经尝试在.Invoke()中传递值为IEnumerable <object>,但$ p没有获取值.
namespace ConsoleApplication1
{
using System;
using System.Linq;
using System.Management.Automation;
class Program
{
static void Main()
{
// Contents of ps1 file
// param($p)
// "Hello World ${p}"
var script = @".\test.ps1";
PowerShell
.Create()
.AddScript(script)
.Invoke().ToList()
.ForEach(Console.WriteLine);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个怎么样?
static void Main()
{
string script = @"C:\test.ps1 -arg 'hello world!'";
StringBuilder sb = new StringBuilder();
PowerShell psExec = PowerShell.Create();
psExec.AddScript(script);
psExec.AddCommand("out-string");
Collection<PSObject> results;
Collection<ErrorRecord> errors;
results = psExec.Invoke();
errors = psExec.Streams.Error.ReadAll();
if (errors.Count > 0)
{
foreach (ErrorRecord error in errors)
{
sb.AppendLine(error.ToString());
}
}
else
{
foreach (PSObject result in results)
{
sb.AppendLine(result.ToString());
}
}
Console.WriteLine(sb.ToString());
}
Run Code Online (Sandbox Code Playgroud)
这是传递DateTime实例的类似版本
static void Main()
{
StringBuilder sb = new StringBuilder();
PowerShell psExec = PowerShell.Create();
psExec.AddCommand(@"C:\Users\d92495j\Desktop\test.ps1");
psExec.AddArgument(DateTime.Now);
Collection<PSObject> results;
Collection<ErrorRecord> errors;
results = psExec.Invoke();
errors = psExec.Streams.Error.ReadAll();
if (errors.Count > 0)
{
foreach (ErrorRecord error in errors)
{
sb.AppendLine(error.ToString());
}
}
else
{
foreach (PSObject result in results)
{
sb.AppendLine(result.ToString());
}
}
Console.WriteLine(sb.ToString());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16806 次 |
| 最近记录: |