![](/img/trans.png)
[英]In C# running the PowerShell script first and then invoke() error
[英]In C# running the PowerShell script first and then invoke Get-Process returns 0 result
在我的C#代码中,我有:
PowerShell ps = PowerShell.Create();
ps.AddScript(". ...\\WindowsPowerShell\\Microsoft.PowerShell_profile.ps1");
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(result.ToString());
}
ps.AddCommand("Get-Process");
ICollection<PSObject> results = ps.Invoke();
Console.WriteLine(results.Count);
foreach (PSObject result in results)
{
Console.WriteLine("---" + result.ToString());
}
如果我在不运行脚本的情况下运行Get-Process(通过注释掉ps.AddScript部分和循环),则Get-Process确实会返回结果。 但是,我提供的代码对于Get-Process总是返回0。
知道为什么它是0吗?
每次调用之后,如果我们要启动一个新命令而不是将命令从上一个命令传递到管道中,则应该先做一个明确的操作:ps.Commands.Clear();
完整的代码是:
PowerShell ps = PowerShell.Create();
ps.AddScript(". ...\\WindowsPowerShell\\Microsoft.PowerShell_profile.ps1");
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(result.ToString());
}
ps.Commands.Clear();
ps.AddCommand("Get-Process");
ICollection<PSObject> results = ps.Invoke();
Console.WriteLine(results.Count);
foreach (PSObject result in results)
{
Console.WriteLine("---" + result.ToString());
}
现在result.count显示正确的行数和result.ToString()打印出正确的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.