我有一個生成孤立 OneDrive 報告的簡單腳本。它正在作業,但速度很慢,所以我只是想知道如何修改我的腳本以加快行程。任何幫助或建議將不勝感激。
基本上這就是我正在做的事情:
- 從“所有者”列獲取所有者電子郵件并使用 AzureAD 檢查是否有任何錯誤
- 如果我收到錯誤,請在本地 ADGroup 中檢查
- 如果該所有者存在于本地 ADGroup 中,則它是孤兒
- 僅將該用戶匯出到新的 csv 檔案
$ImportData = "E:\scripts\AllOneDriveUser.csv"
$Report = "E:\scripts\OrphanOneDrive.csv"
$CSVImport = Import-CSV $ImportData
ForEach ($CSVLine in $CSVImport) {
$CSVOwner = $CSVLine.Owner
try{
Get-AzureADUser -ObjectId $CSVOwner
}catch{
$StatusMessage = $_.Exception.Message
if($Null -eq $StatusMessage){
Write-Host "User Found, Ignore from orphan list."
}else{
#Owner not found in AzureAD
$group = 'TargetGroup'
$filter = '(memberof={0})' -f (Get-ADGroup $group).DistinguishedName
$filterName = Get-ADUser -LDAPFilter $filter
$ModifiedOwner = $CSVOwner -split"@"[0]
if( $ModifiedOwner[0] -in $filterName.Name ){
Write-host "Adding it into orphaned list"
$CSVLine | Export-Csv $Report -Append -notypeinformation -force
}else{
Write-Host "Not orphaned"
}
}
}
}
我的匯入 csv 檔案中有超過 8000 條記錄,我的本地 AD 組中有超過 5000 名成員,因此需要很長時間。
uj5u.com熱心網友回復:
在這種情況下,您可以通過使用 a 大大改進您的腳本HashSet<T>,但代碼的主要問題是您一遍又一遍地查詢同一個組,它應該在回圈之外!
還有使用Export-Csv -Append,每次回圈迭代附加到檔案非常慢,更好地使用管道簡化流程,因此Export-Csv只接收物件并匯出一次,而不是FileStream每次都打開和關閉。
希望行內評論解釋您可以遵循的邏輯來改進它。
$ImportData = "E:\scripts\AllOneDriveUser.csv"
$Report = "E:\scripts\OrphanOneDrive.csv"
# we only need to query this once! outside the try \ catch
# a HashSet<T> enables for faster lookups,
# much faster than `-in` or `-contains`
$filter = '(memberof={0})' -f (Get-ADGroup 'GroupName').DistinguishedName
$members = [Collections.Generic.HashSet[string]]::new(
[string[]] (Get-ADUser -LDAPFilter $filter).UserPrincipalName,
[System.StringComparer]::OrdinalIgnoreCase
)
Import-CSV $ImportData | ForEach-Object {
# hitting multiple times a `catch` block is expensive,
# better use `-Filter` here and an `if` condition
$CSVOwner = $_.Owner
if(Get-AzureADUser -Filter "userprincipalname eq '$CSVOwner'") {
# we know this user exists in Azure, so go next user
return
}
# here is for user not found in Azure
# no need to split the UserPrincipalName, HashSet already has
# a unique list of UserPrincipalNames
if($hash.Contains($CSVOwner)) {
# here is if the UPN exists as member of AD Group
# so output this line
$_
}
} | Export-Csv $Report -NoTypeInformation
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/518159.html
