建立一個腳本文件,即可以在powershell控制檯執行,也可以用C#來執行,腳本中在使用AD增加用戶帳號沒有問題,但在使用戶郵箱啓用時有問題,在powershell控制檯使用需要遠程連接命令,而在C#中通過管道不能執行,而屏蔽腳本中的遠程連接即可執行,不明白爲什麼。
windows2008 r2 + exchang2010 sp2
C#代碼:
RunspaceConfiguration runspanceconf = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspanceconf);
runspace.Open();
Pipeline pipline = runspace.CreatePipeline();
String sScript = "f:\\webmail\\ManagementUser.ps1 -what \"adduser\" -user \""+uAlias+"\" -pwd \""+uPwd+"\"";
pipline.Commands.AddScript(sScript);
try
{
Collection<PSObject> results = pipline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{ stringBuilder.AppendLine(obj.ToString()); }
MessageBox.Show(stringBuilder.ToString());
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message.ToString());
finally
{
pipline.Dispose();
runspace.Close();
}
PowerShell腳本 ManagementUser.ps1
param([string] $what,[string] $user,[string] $pwd)
function script:AddUser_ps($user,$pwd)
{
$spwd = ConvertTo-SecureString $pwd -AsPlainText -Force
import-module activedirectory
try
{
New-ADUser -Name $user -SamAccountName $user -UserPrincipalName $user"@test.com.cn" -GivenName $user -DisplayName "測試" -path "ou=sdkj,dc=test,dc=com,dc=cn" -AccountPassword $spwd -Enabled $true -CannotChangePassword $false -ChangePasswordAtLogon $false
-PasswordNeverExpires $true
$s = EnableMailBox $user
if ($s -eq "ok")
{ return "增加用戶:" + $user +"成功,郵箱啓用成功。" }
else
{ return "增加用戶:" + $user +"成功,郵箱啓用失敗。" }
}
catch
{ $s = EnableMailBox $user
if ($s -eq "ok")
{ return "出現錯誤,錯誤原因:"+$error[0] +",郵箱啓用成功。" }
else
{
return "出現錯誤,錯誤原因:"+$error[0] + $s
}
}
}
function script:EnableMailBox($user)
{ $a = "test.com.cn/sdkj/"+$user
#使用powershell控制檯執行,而在C#調用的時候執行出錯。
try {
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUrihttp://dc.test.com.cn/PowerShell -Authentication Kerberos
Import-PSSession $Session
}
catch
{
# return $error[0]
}
Enable-mailbox -Identity $a -Alias $user
Remove-PSSession $Session
return "ok"
}
function script:RemoveUser_ps($user)
{ #import-module activedirectory
try
{
Remove-ADUser $user -confirm:$false
return "刪除帳號: $user ,成功。"
}
catch
{ return "出現錯誤,錯誤原因:"+$error[0] }
}
$script:result=""
switch($what)
{
"removeuser" { $result = RemoveUser_ps $user }
"adduser" { $result = AddUser_ps $user $pwd}
default {$result = "error"}
}
return $result