#以下脚本可以导出邮箱及OneDrive目前使用大小

#The below parts needs to be modified
#(需要更改)这里需要根据您的tenant进行更改
$adminUPN= "[email protected]"
#(需要更改)orgName是您onmicrosoft.com域名前面的那个字段,E.g 我的是tonysoft.onmicrosoft.com
$orgName="tonysoft"
#(需要更改)这里是导出的路径
$CSV = "D:\SPO1.csv"
#No need to modify the below parts
#==================================================================================================
#连接部分
$userCredential = Get-Credential -UserName $adminUPN -Message "Type the password."
try{
Connect-SPOService -Url https://$orgName-admin.sharepoint.com -Credential $userCredential
Connect-Msolservice -Credential $userCredential
Connect-ExchangeOnline -Credential $userCredential
}catch{

    Write-Host ("You need to make sure the following Module has been installed...") -fore Red
    Write-Host ("To install SharePoint Online: Install-Module -Name Microsoft.Online.SharePoint.PowerShell") -fore Cyan
    Write-Host ("To install MS Online: Install-Module Msoline") -fore Cyan
    Write-Host ("To install Exchange Online: Install-Module ExchangeOnlineManagement") -fore Cyan
    Break;
}
#===================================================================================================
#提取数据部分
$result = @()

Write-Host ("Collecting all user's information...") -fore Green
$AllUsers = get-msoluser -All | Select-Object UserPrincipalName,blockCredential,Country,Department,Displayname,Title

$i = 0

foreach($User in $AllUsers)
{   
    $i ++
    $Persentage = (($i/($AllUsers.Count)) * 100).toString("#.##") 
    Write-Progress -Activity "Search in Progress" -Status "$Persentage%" -PercentComplete $Persentage;
    $user.UserPrincipalName

    Write-Host("Progress: " + (($i/($AllUsers.Count)) * 100).toString("#.##") + "%") -Fore Green

    #Get Mailbox Usage
    Try{
        $MB = get-mailboxstatistics $user.UserPrincipalName -erroraction silentlycontinue| Select-Object TotalItemSize
    }Catch{
        #user does not have EXO enabled
    }

    #Get ODB usage
    $link = $user.UserPrincipalName.Replace("@","_").Replace(".","_")
    $url = "https://$orgName-my.sharepoint.com/personal/$link"
    Try{
        $ODB = Get-SPOSite $url -Detailed -ErrorAction SilentlyContinue | Select-Object url, storageusagecurrent, Owner
    }Catch{
        #User does not have ODB enabled...
    }Finally{
        $usage = $ODB.StorageUsageCurrent / 1024
    }

    #Combine the result
    $result += New-Object PSObject -Property @{
        BlockCredential  = $User.blockCredential
        Country = $User.Country
        Department = $User.Department
        Displayname = $User.Displayname
        UserPrincipalName = $User.UserPrincipalName
        MBX_Usage = $MB.TotalItemSize
        Drive_Usage_In_MB = $usage

        }

}
#将数据导出到CSV,若CSV已存在,则覆盖原CSV中的数据
$result | Select-Object BlockCredential,Country,Department,Displayname,UserPrincipalName,MBX_Usage,Drive_Usage_In_MB |Export-Csv $CSV -encoding utf8 -notype 
Write-Host ("CSV has been exported under: " + $CSV) -fore Green