我想在c#应用程序中添加一个工具,我可以:
1)获取一组对象,并将其传递给我的c#application
中的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);
}
}
}
}
答案 0 :(得分:6)
您可以使用PowerShell Runspace在.NET应用程序中创建的PowerShell会话中设置和获取变量。我编辑了您的日期参数并删除了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();
答案 1 :(得分:0)
根据您的描述,您似乎缺少-Path开关。
直接传递DLL时必须指定-Path。请参阅此处的参考文档...... http://technet.microsoft.com/en-us/library/dd315241.aspx
答案 2 :(得分:0)
我已经将一个C#程序集加载到PowerShell脚本中并像这样使用它:
$dllPath = "C:\path\library.dll"
$tmp = [Reflection.Assembly]::LoadFile($dllPath)
$obj = new-object Namespace.LibraryClass()