网上找了一个操作powershell的com+组件源码,配置好后,发现启用邮箱不稳定。因此在代码中用log4net加入异常日志记录。如下:
private static readonly ILog log = LogManager.GetLogger("ErrorLog"); public bool IsExistMailBox(string identity) { try { PSSnapInException PSException = null; RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create(); runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out PSException); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); string errors = string.Empty; using (pipeline) { Command command = new Command("Get-Mailbox"); command.Parameters.Add("identity", identity); //command.Parameters.Add("DomainController", "XX"); pipeline.Commands.Add(command); Collectionresult = pipeline.Invoke(); if ((pipeline.Error != null) && (pipeline.Error.Count > 0)) { foreach (object obj2 in pipeline.Error.ReadToEnd()) { errors = errors + obj2.ToString() + "|"; } //记录log信息 log.Info(identity + "PipeLine[Get-Mailbox]错误信息:" + errors); throw new Exception(errors);//记录log信息 } } pipeline = null; runspace.Close(); runspace = null; //return (result != null && result.Count > 0); return string.IsNullOrEmpty(errors); } catch (System.Exception ex) { log.Info(identity + "账户Get-Mailbox调用异常:" + ex.Message); throw ex; } }
log4Net配置节:
AssemblyInfo.cs顶部加入如下代码:
[assembly: log4net.Config.Repository("PowerShellExInfo")][assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
以上都做好后,创建com组件。将log4Net配置文件放到引用组件同目录下。本来以为这样就可以了,可是操作过程中发现并没有记录异常日志信息,网上找了三天,皇天不负有心人啊,终于在国外论坛找到解决方法。log4net配置文件应放到在system32目录下,这样日志就能记录了。OK