【发布时间】:2022-03-28 05:08:57
【问题描述】:
我编写了一段代码(用 C# 编写)来使用 System.Management.Automation 执行 Powershell 脚本(特别是 Azure PowerShell)。 powershell脚本基本上是在Azure上的一个容器中上传一个vhd,当通过azure Powershell手动输入命令时,它会显示上传进度和经过的时间等。通过代码一切正常,但我想在命令执行期间(即pipeline.invoke();)获取命令的结果/输出(即上传进度、经过的时间),这是代码:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
Command myCommand = new Command(scriptPath);
foreach (var argument in arguments)
{
myCommand.Parameters.Add(new CommandParameter(argument.Key, argument.Value));
}
pipeline.Commands.Add(myCommand);
var results = pipeline.Invoke(); // i want to get results here (i.e. during command execution)
foreach (var psObject in results)
{
System.Diagnostics.Debug.Write(psObject.BaseObject.ToString());
}
如果可以从 Powershell 检索实时输出,请指导。
【问题讨论】:
-
使用
PowerShell类而不是Pipeline。然后异步调用并读取PowerShell.Streams.Progress -
你能指导更多使用一些代码吗?
-
我已经添加了答案
-
感谢我试一试..
-
明确地说,有了
DataAdded事件处理程序,您不需要异步调用它。Invoke()会很好
标签: c# powershell azure