C#UI不打印从PowerShell命令生成的字符串?
我正在尝试使用运行PowerShell命令的C#创建一个UI可执行文件,以从Active Directory返回动态分布组的列表。这些动态分布组将进入下拉菜单。 我遇到的问题是从PowerShell脚本返回的对象无法转换为字符串。当我在UI中显示函数的结果时,它显示为“ System.Collections.ObjectModel.Collection” 1 [System.Management.automation.psobject]”。当我查找此问题时,这显然是一种powershell对象,我认为这是告诉我C#接收值但没有正确解释它。 如何将PowerShell对象中包含的值转换为可以打印到C#UI上的字符串?
这是我用来从C#程序中调用PowerShell脚本的代码:
Runspace? runningspace = RunspaceFactory.CreateRunspace();
Collection<PSObject> result = new Collection<PSObject>();
PowerShell powershell = PowerShell.Create();
runningspace.Open();
powershell.Runspace = runningspace;
System.IO.StreamReader sr = new System.IO.StreamReader("script.ps1");
powershell.AddScript(sr.ReadToEnd());
result = powershell.Invoke();
ResultBox.Text = Convert.ToString(result);
sr.Close();
sr.Dispose();
代码的此部分没有在下拉列表中生成任何项目:
foreach (PSObject obj in result)
{
DropDownMenu.Items.Add(Convert.ToString(obj));
}
这是我正在运行的PowerShell脚本(减去登录到Active Directory的代码我正在访问):
$groups = Get-DynamicDistributionGroup
return Write-Output $groups
注意:我使用WPF应用程序模板在Visual Studio上创建了UI。不确定这是否会有所帮助,但我认为我应该提供尽可能多的信息。
I'm trying to create a UI executable using C# that runs PowerShell commands to return a list of dynamic distribution groups from an active directory. These dynamic distribution groups are to go into a dropdown menu.
The problem that I'm running into is that the objects returned from the PowerShell script are unable to be converted into strings. When I display the results of the function in the UI, it shows up as "System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject]". When I looked this up, it's apparently a type of powershell object, which I think is telling me that C# receives the value but is not interpreting it correctly.
How do I convert the values contained within the powershell object into strings that can be printed onto the C# UI?
This is the code that I used to call the Powershell script from within the C# program:
Runspace? runningspace = RunspaceFactory.CreateRunspace();
Collection<PSObject> result = new Collection<PSObject>();
PowerShell powershell = PowerShell.Create();
runningspace.Open();
powershell.Runspace = runningspace;
System.IO.StreamReader sr = new System.IO.StreamReader("script.ps1");
powershell.AddScript(sr.ReadToEnd());
result = powershell.Invoke();
ResultBox.Text = Convert.ToString(result);
sr.Close();
sr.Dispose();
This part of the code is not generating any items in the DropDownMenu:
foreach (PSObject obj in result)
{
DropDownMenu.Items.Add(Convert.ToString(obj));
}
This is the Powershell script I'm running (minus code to log into the active directory I'm accessing):
$groups = Get-DynamicDistributionGroup
return Write-Output $groups
NOTE: I created the UI on Visual Studio using the WPF Application template. Not sure if that will help, but I figured I should give as much information as may be helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论