c# 访问Exchange初始化时报错

RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create();

            PSSnapInException snapEX = null;
            PSSnapInInfo snampInfo = runspaceConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEX);

            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfig);

            runspace.Open();
                            这段代码可执行,不报错
                            但是接下来我需要获取一个信息,代码如下:
                             foreach (PSObject obj in results)
                {
                    foreach (PSMemberInfo mi in obj.Members)
                    {
                        File.AppendAllText("D:\\log.txt", "id:" + mi.Name.Trim() + "\r\n");
                        if (mi.Name == "ActiveSyncAllowedDeviceIDs")
                        {
                            Microsoft.Exchange.Data.MultiValuedProperty<string> mvp = (Microsoft.Exchange.Data.MultiValuedProperty<string>)mi.Value;
                            foreach (string item in mvp)
                            {
                                File.AppendAllText("D:\\log.txt", "id:" + o + "\r\n");
                           }
                            //MultiValuedProperty

                        }
                    }

                }
                                    要有Microsoft.Exchange.Data.MultiValuedProperty这个类型,必须引用Microsoft.Exchange.Data,如果引用了这个类型,最上面那段代码就会报错,错误信息如下:
                                    The type initializer for 'Microsoft.Exchange.Management.PowerShell.CmdletConfigurationEntries' threw an exception.

at Microsoft.Exchange.Management.PowerShell.CmdletConfigurationEntries.get_ExchangeCmdletConfigurationEntries()
at Microsoft.Exchange.Management.PowerShell.AdminPSSnapIn.get_Cmdlets()
at System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.MergeCustomPSSnapIn(PSSnapInInfo mshsnapinInfo, CustomPSSnapIn customPSSnapIn)
at System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadCustomPSSnapIn(PSSnapInInfo mshsnapinInfo)
at System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadPSSnapIn(PSSnapInInfo mshsnapinInfo)
at System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadPSSnapIn(PSSnapInInfo mshsnapinInfo, PSSnapInException& warning)
at System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.DoAddPSSnapIn(String name, PSSnapInException& warning)
at PowerShell.PowerShellManage.LiftBan(String user) in E:\AnyOffice\PowerShell\PowerShellManage.cs:line 282

1个回答

应该是
Microsoft.Exchange.Data.MultiValuedProperty<string> mvp = (Microsoft.Exchange.Data.MultiValuedProperty<string>)mi.Value;
这里强制类型转换错误。
你可以反射看下这个属性具体的类型

T63zengyu
取名字真难null 不是,引用Microsoft.Exchange.Data这个程序集后,初始化就报错了,还没到强转,去掉这个程序集又好了,但是获取不到下面那个类型了
接近 5 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问