C# 启用Lync用户

来源:互联网 发布:新倩女幽魂网游mac 编辑:程序博客网 时间:2024/05/20 19:49
                PowerShell ps;                ps = PowerShell.Create();                ps.AddScript("Set-ExecutionPolicy Unrestricted");                ps.Invoke();                ps.AddScript(@"import-module Lync");                ps.Invoke();                 ps.AddScript("Enable-CsUser  -Identity {0}@domain.com -RegistrarPool lyncpool.domain.com -SipAddressType UserPrincipalName");                ps.Commands.AddCommand("Out-String");
 
                Collection<PSObject> results = ps.Invoke();;                foreach (PSObject obj in results)                {                    stringBuilder.Append(obj.ToString());                }                               foreach (ErrorRecord error in ps.Streams.Error)                {                    stringBuilder.Append(error.ToString());                }

通过C#执行powershell命令,需要导入System.Management.Automation.dll。该组件在powershell的安装目录。

1、首先需要powershell的执行环境

2、导入Lync模块

3、执行启用Lync用户的命令

以上代码在控制台程序中运行通过,但放在IIS运行,就会出现权限不足的情况。

如果执行成功就不会有任何的返回值。如果失败就会返回错误信息。

 

第二种方式

                RunspaceConfiguration config = RunspaceConfiguration.Create();                 Runspace myRs = RunspaceFactory.CreateRunspace(config);                myRs.ApartmentState = System.Threading.ApartmentState.STA;                myRs.ThreadOptions = PSThreadOptions.UseCurrentThread;                myRs.Open();                 RunspaceInvoke scriptInvoker = new RunspaceInvoke(myRs);                 scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");                scriptInvoker.Invoke(@"Import-Module Lync");                Pipeline pipeline = myRs.CreatePipeline();                 pipeline.Commands.AddScript("Enable-CsUser  -Identity {0}@domain.com -RegistrarPool lyncpool.domain.com -SipAddressType UserPrincipalName");                Collection<PSObject> results = pipeline.Invoke();;                foreach (PSObject obj in results)                {                    stringBuilder.Append(obj.ToString());                }                              

这种方式可以在IIS中运行。

 

参考文档

http://stackoverflow.com/questions/6266108/powershell-how-to-import-module-in-a-runspace

http://gotspeech.net/blogs/marshallharrison/archive/2011/01/07/calling-powershell-from-c.aspx

http://stackoverflow.com/questions/6568160/error-executing-powershell-commandlets-using-c-sharp/6568919#6568919

 

	
				
		
原创粉丝点击