如何将参数从 C# 传递到 PowerShell 脚本文件? [英] How to pass a parameter from C# to a PowerShell script file?
本文介绍了如何将参数从 C# 传递到 PowerShell 脚本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从命令行我可以做到.
.\test.ps1 1
从 C# 执行此操作时如何传递参数?我试过了
How do I pass the parameter when doing this from C#? I've tried
.AddArgument(1)
.AddParameter("p", 1)
并且我尝试在 .Invoke() 中将值作为 IEnumerable<object> 传递,但 $p 没有得到值.
And I have tried passing values in as IEnumerable<object> in the .Invoke() but $p does not get the value.
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);
}
}
}
推荐答案
怎么样?
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());
}
这是一个类似的版本,它传递一个 DateTime 的实例
Here's a similar version that passes an instance of a 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());
}
这篇关于如何将参数从 C# 传递到 PowerShell 脚本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文