一些 C# 代码执行带有参数的 powershell 脚本。我想从 Powershell 获取返回码和字符串,以了解 Powershell 脚本中是否一切正常。
这样做的正确方法是什么 - 在 Powershell 和 C# 中
电源外壳
# Powershell script
# --- Do stuff here ---
# Return an int and a string - how?
# In c# I would do something like this, if this was a method:
# class ReturnInfo
# {
# public int ReturnCode;
# public string ReturnText;
# }
# return new ReturnInfo(){ReturnCode =1, ReturnText = "whatever"};
C#
void RunPowershellScript(string scriptFile, List<string> parameters)
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
Command scriptCommand = new Command(scriptFile);
Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
foreach (string scriptParameter in parameters)
{
CommandParameter commandParm = new CommandParameter(null, scriptParameter);
commandParameters.Add(commandParm);
scriptCommand.Parameters.Add(commandParm);
}
pipeline.Commands.Add(scriptCommand);
Collection<PSObject> psObjects;
psObjects = pipeline.Invoke();
//What to do here?
//ReturnInfo returnInfo = pipeline.DoMagic();
}
}
class ReturnInfo
{
public int ReturnCode;
public string ReturnText;
}
通过使用 Write-Output 并依赖诸如“最后两个 psObjects 是我正在寻找的值”之类的约定,我设法做到了这一点,但它很容易破坏。