Powershell 修改Office365和AD賬戶

這段時間需要大量地修改AD用戶的一些屬性,例如郵件,UPN,登錄名等等,以便和Office365的登錄賬號保持一致。寫了個簡單腳本進行批量修改。


腳本執行的前提是在本地安裝了AD和Office365必要的PS模塊。AD是可以遠程間接調用DC的PS模塊,不過實際操作發現有些小bug,所以還是直接安裝在本地比較省事,速度也快。


#Import AD Module
Import-Module activedirectory

#Import Office 365 Module

$Sessions=Get-PSSession

if ($Sessions.ComputerName -like "outlook.office365.com"){

    write-host "Detecting current Office365 session, skip.." -ForegroundColor Cyan

}
else{
    
    write-host "Starting new Office365 session" -ForegroundColor Cyan
    $UserCredential = Get-Credential 
    Connect-MsolService -Credential $UserCredential
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
    Import-PSSession $Session
}




#Get Primary SMTP Address
function Get-PrimarySMTP(){

    [CmdletBinding()]
    
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string[]]
        $users
    )

    $pp=$null
    $pp=@{'name'=$null;'primarysmtp'=$null}
    $obj=New-Object -TypeName psobject -Property $pp
 
    $result=@()
    foreach($user in $users){
    $info=get-aduser -Filter {name -eq $user} -Properties proxyaddresses
    $primarySMTPAddress = ""
    foreach ($address in $info.proxyAddresses)
    {
        if (($address.Length -gt 5) -and ($address.SubString(0,5) -ceq 'SMTP:') )
        {
            $primarySMTPAddress = $address.SubString(5)
        
            break
        }

    }
    $objtemp=$obj | select *
    $objtemp.name=$info.Name
    $objtemp.primarysmtp=$primarySMTPAddress
    $result+=$objtemp
    }
    return $result 
}

#Get AD User Informtion

#$ADUsers = Get-ADUser -SearchBase "ou=mango,ou=ddb_group,ou=melbourne,dc=omnicom,dc=com,dc=au" -Properties proxyaddresses, emailaddress, displayname -Filter *
Write-Host " "

$uUser=Read-Host "Please input the domain name "

try{

    $ADUsers=get-aduser $uUser -Properties proxyaddresses, emailaddress, displayname


    #Change SamAccountName and UPN
    foreach ($ADUser in $ADUsers) {
        $ADUser.Name
	    $GivenName = $ADUser.GivenName
	    $SurName = $ADUser.Surname
	
	    if (($GivenName -ne $null) -or ($SurName -ne $null))
	    {
		    $newSAM = $GivenName.ToLower() + '.'+$SurName.ToLower()
            $oldUPN=$ADUser.UserPrincipalName
            $domainName= $oldUPN.Split('@')[1]
		    $newUPN = $newSAM + '@'+$domainName
        
            write-host "Updating ADUPN: $oldupn -> $newUPN" -ForegroundColor Cyan
        

            #Change AD UPN and SamAccount
		    Set-ADUser $ADUser -SamAccountName $newSAM -UserPrincipalName $newUPN 
       
        
            #Change AD email
            $oldEmail=$ADUser.emailaddress

            $newEmail=$newSAM+‘@'+$oldemail.split('@')[1]

            write-host "Updating Email:$oldEmail -> $newEmail" -ForegroundColor Cyan

            set-aduser $newSAM -EmailAddress $newEmail

            #Change Primary SMTP

            $primary=Get-PrimarySMTP -users $ADUser.name | select -ExpandProperty primarysmtp

            Write-Host "Updating ProxyAddress.." -ForegroundColor Cyan

            #Write-Host "Current Primary address is $primary" -ForegroundColor Cyan
        
            $Aduser.proxyaddresses.remove("SMTP:"+$primary)
        
            $Aduser.proxyaddresses.add("smtp:"+$primary)

            $Aduser.proxyaddresses.add("SMTP:"+$newEmail)

            set-aduser $newSAM -replace @{proxyaddresses=[string[]]$ADUser.proxyaddresses} -ErrorAction Stop
        
        

            #Change cloud UPN. If Office365 session is not connected properly, follow commands wont' work!

            $oldmsolupn=Get-MsolUser -SearchString $ADUser.Name 
            $oldmsolupn=$oldmsolupn| select -First 1 | select -ExpandProperty UserPrincipalName

            $newmsolupn=$newSAM+'@'+$oldmsolupn.split('@')[1]

            write-host "Updating MSOLUPN: $oldmsolupn -> $newmsolupn" -ForegroundColor Cyan
            Set-MsolUserPrincipalName -UserPrincipalName $oldmsolupn -NewUserPrincipalName $newmsolupn 
		
            Write-Host ""
	    }
        else{
            Write-Warning "Either GivenName or Surname is Empty"
    
        }
    }

    #Confirm result 

    Write-Host "Confirm AD Result " -ForegroundColor Cyan
    get-aduser $newSAM -Properties proxyaddresses,mail | select Name, SamAccountName, UserPrincipalName, proxyaddresses, mail

    Write-Host "Confirm O365 Result" -ForegroundColor Cyan
    Get-MsolUser -SearchString $ADUser.Name | select UserPrincipalName

}catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]{

    write-host "AD User can not found" -ForegroundColor red
}catch [Microsoft.ActiveDirectory.Management.ADException]{

    Write-Host "User vlaue can't be updated or the specified value already exists" -ForegroundColor Red
}


修改其實都滿簡單地,我的腳本里面也沒有寫太多容錯處理。修改完了之後,windows用戶可能存在Profile和註冊表對不上號的問題,因此還需要修改一些註冊表,具體操作參考 http://beanxyz.blog.51cto.com/5570417/1930788



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