我是一名 PowerShell 初学者用户,我编写了一个脚本来提取有关我的组织(大约 18,000 个用户)中每个用户的邮箱和存档的特定信息。目前运行时间约为 24 小时。我知道它的编码效率不高,我希望有人可以帮助我找到更好的编码方法以缩短运行时间?请让我知道可以使用哪些技术来帮助加快速度。
Param (
[Parameter(Mandatory=$false)]
[string]$OutputPath = 'C:\Temp\Users-ArchiveSize.csv'
)
Connect-ExchangeOnline -UserPrincipalName [email protected] -ConnectionUri "https://outlook.office365.com/powershell?email=@yourmailaddress"
$result = @()
$Users = Get-Content -Path "C:\Temp\users-Testing.csv"
Measure-Command { foreach($user in $users) {
$u = Get-EXOMailbox -Identity $user
If ($u.AutoExpandingArchiveEnabled -eq $true) {
$autoArchiveEnabled = "True"
}
Else {
$autoArchiveEnabled = "False"
}
$displayName = $u.DisplayName
$primarySmtpAddress = $u.PrimarySmtpAddress
$data = Get-EXOMailboxStatistics $u.UserPrincipalName -Archive | select TotalItemSize,ItemCount
$totalSize = $data.TotalItemSize
$itemCount = $data.ItemCount
$result += New-Object psobject -Property @{
'DisplayName' = $displayName;
'PrimarySMTP' = $primarySmtpAddress;
'TotalSize' = $totalSize;
'ItemCount' = $itemCount;
'AutoExpandEnabled' = $autoArchiveEnabled;
}
}
}
if ($OutputPath) {
$result | Export-Csv -Path $OutputPath -NoTypeInformation
}
到目前为止,我已经尝试将针对 Exchange 数据库的查询单独隔离到一个数组中,希望它比同时提取和格式化更快,然后从该数组中提取我需要的内容以进行格式化和导出。我以为这会有所帮助,但实际上花了更长的时间。
我正在使用脚本块探索启动作业,但无法让它正常工作。我认为我对这个概念的理解不够,csv 导出为空。我可以看到它正确执行“$u = Get-EXOMailbox -Identity $user”,但创建变量“$displayName = $u.DisplayName”不起作用,该变量以及其他变量都是空了。
我正在研究并认为并行运行查询可能是另一个不错的选择,但我仍在尝试看看我是否能弄清楚如何做到这一点,或者即使这是可能的。
我仍然只是 PS 的初学者,这些方法/概念很难让我理解并深入研究,我没有很多编程经验。任何帮助,即使只是一个方向,都会真正帮助我!
在 PowerShell 中,当您使用
+=
将项目添加到数组时,它实际上会创建一个新数组并将所有项目复制到其中。
如果您可以在管道中较早地过滤对象,请这样做。 PowerShell 在管道中传递的数据越少,脚本运行的速度就越快。
这是使用通用列表而不是数组的脚本版本:
Param (
[Parameter(Mandatory=$false)]
[string]$OutputPath = 'C:\Temp\Users-ArchiveSize.csv'
)
Connect-ExchangeOnline -UserPrincipalName [email protected] -ConnectionUri "https://outlook.office365.com/powershell?email=@yourmailaddress"
$Users = Get-Content -Path "C:\Temp\users-Testing.csv"
$result = New-Object System.Collections.Generic.List[object]
foreach($user in $users) {
$u = Get-EXOMailbox -Identity $user
If ($u.AutoExpandingArchiveEnabled -eq $true) {
$autoArchiveEnabled = "True"
}
Else {
$autoArchiveEnabled = "False"
}
$displayName = $u.DisplayName
$primarySmtpAddress = $u.PrimarySmtpAddress
$data = Get-EXOMailboxStatistics $u.UserPrincipalName -Archive | select TotalItemSize,ItemCount
$totalSize = $data.TotalItemSize
$itemCount = $data.ItemCount
$result.Add((New-Object psobject -Property @{
'DisplayName' = $displayName;
'PrimarySMTP' = $primarySmtpAddress;
'TotalSize' = $totalSize;
'ItemCount' = $itemCount;
'AutoExpandEnabled' = $autoArchiveEnabled;
}))
}
if ($OutputPath) {
$result | Export-Csv -Path $OutputPath -NoTypeInformation
}