powershell2.0 使用腳本建立exchange2010的用戶帳號及郵箱

建立一個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 "test1" -UserPrincipalName $user"@test.com.cn" -GivenName "test1" -DisplayName "測試一" -path "ou=group1,dc=test,dc=com,dc=cn" -AccountPassword $spwd -Enabled $true -CannotChangePassword $false -ChangePasswordAtLogon $false -EmailAddress "
[email protected]" -PasswordNeverExpires $true
         EnableMailBox $user
         return "增加用戶:" + $user +"成功。"
     }
     catch
     {   $r =  EnableMailBox $user    
         return "出現錯誤,錯誤原因:"+$error[0] + $r
     }
}

#啓用郵箱

function EnableMailBox($user)
{
   try {

#建立遠程連接
        $a =  'test.com.cn/group1/'+$user
        $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri
http://test.com.cn/PowerShell -Authentication Kerberos
        Import-PSSession $Session

#使郵箱啓用
        Enable-mailbox -Identity $a -Alias $user
        Remove-PSSession $Session
        return "郵箱已經可用。"
   }
   catch
   {
       return $error[0]
   }
}

#刪除用戶

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 = "不識別參數。"}
}
write-host $result

 

打開powershell2.0控制檯

建立一個test1用戶,並啓用郵箱

輸入.\ManagementUser.ps1 -what "adduser" -user "test1" -pwd "test-1"

刪除用戶test1

輸入.\ManagementUser.ps1 -what "removeuser" -user "test1" -pwd ""

 

不直接使用new-mailbox,是因爲沒有密碼永不過期的參數,而使用AD建立用戶可以設置密碼永不過期:-PasswordNeverExpires $true

要點:

1、PowerShell要支持ActiveDirectory下的cmdlet,需先使用import-module activedirectory

2、如果ChangePasswordAtLogon設置爲$true,則PasswordNeverExpires不能使之爲$true

3、Exchange2010不支持本地命令程序,所以需先連接到Exchange2010服務器,如果是使用Exchange Management Shell,則打開控制檯後就會連接到服務器上。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章