我想在 c# 应用程序中添加一个工具,我可以:
1) 获取一组对象,并将其从我的 c# 应用程序内部传递给一个 powershell 脚本
2) 让 powershell 脚本对其传递的对象列表进行更改
3)将该对象列表返回给c#
我有一个名为 Message 的外部类
public class Message
{
public String name { get; set; }
public String from { get; set; }
public String to { get; set; }
public String date { get; set; }
public String subject { get; set; }
public String body { get; set; }
}
我这样填充 PSDataCollection 列表类:
PSDataCollection<Message> mlist = new PSDataCollection<Message>()
{
new Message { to="user1", from="user2", date = "1/10/2010 12:00:00 AM EST", subject = "hi there" , body = "hi again" },
new Message { to="user1", from="user3", date = "1/10/2010 12:00:00 AM EST", subject = "new messages" , body = "new messages" }
}
在 powershell 脚本中,我们希望它
1)读取每个对象
2) 通过添加 2 小时来调整日期字段
实现问题:
下面的代码是我们试图让它工作的尝试。我们遇到的第一个问题是如何从外部 DLL 导入 Message 类。
我们试过这个: Add-Type "G:\testBAL\bin\Debug\testBAL.dll"但出现错误
任何帮助,将不胜感激。
namespace TestProject
{
class Program
{
static void Main(string[] args)
{
PSDataCollection<Message> mlist = new PSDataCollection<Message>()
{
new Message { to="user1", from="user2", date = "1/10/2010 12:00:00 AM EST", subject = "hi there" , body = "hi again" },
new Message { to="user1", from="user3", date = "1/10/2010 12:00:00 AM EST", subject = "new messages" , body = "new messages" }
};
mlist.Complete();
PowerShell ps = PowerShell.Create()
.AddScript("Add-Type G:\testBAL\bin\Debug\testBAL.dll")
.AddCommand("Select-Object");
IAsyncResult async = ps.BeginInvoke<Message>(mlist);
foreach(PSObject result in ps.EndInvoke(async))
{
String to = ((Message)(result.BaseObject)).to;
Console.WriteLine("to=" + to);
}
}
}
}
最佳答案
您可以使用 PowerShell 运行空间在 .NET 应用程序中创建的 PowerShell session 中设置和获取变量。我编辑了您的日期参数并删除了 EST,以便 PowerShell 的 Get-Date cmdlet 可以轻松解析它。
HTH
道格
var mlist = new PSDataCollection<Message>()
{
new Message { to="user1", from="user2", date = "1/10/2010 12:00:00 AM", subject = "hi there" , body = "hi again" },
new Message { to="user1", from="user3", date = "1/10/2010 12:00:00 AM", subject = "new messages" , body = "new messages" }
};
var rs = RunspaceFactory.CreateRunspace();
rs.Open();
rs.SessionStateProxy.SetVariable("list", mlist);
var ps = PowerShell.Create();
ps.Runspace = rs;
ps.AddScript(@"
$list | ForEach {
$_.date = (Get-Date($_.date)).AddHours(2)
}
");
ps.Invoke();
var result = rs.SessionStateProxy.GetVariable("list") as PSDataCollection<Message>;
foreach (var item in result)
{
Console.WriteLine(item.date);
}
rs.Close();
关于powershell - 让 Powershell 处理来自 C# 程序的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5479050/