![](/img/trans.png)
[英]How can I make Powershell parse XML faster or further optimize my script?
[英]How can I better optimize this O365 powershell script?
該腳本打開與O365的連接,然后遍歷所有郵箱以查找可能是惡意的收件箱規則。
在我們的12K郵箱組織中,此腳本需要24個小時以上才能運行。
$CloudCredentials = import-clixml C:\tools\CloudCreds.xml
Write-Host "Connecting To Exchange Online..." -foregroundcolor white
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell `
-Credential $CloudCredentials -Authentication Basic -
AllowRedirection -WarningAction SilentlyContinue
Import-PSSession $Session -Prefix Cloud -DisableNameChecking -AllowClobber | Out-Null
Connect-MsolService -Credential $CloudCredentials
Invoke-Command -Session (Get-PSSession | ?{$_.state -eq "Opened"}) -ScriptBlock {GEt-Mailbox -resultsize unlimited | Select-Object PrimarySMTPAddress,UserPrincipalName}
foreach ($MB in $MBs) {
$Rules=@()
$Rules += Get-CloudInboxRule -Mailbox $MB.UserPrincipalName -WarningAction SilentlyContinue
if ($Rules.Length -gt 0) {
foreach ($R in $Rules) {
if (($R.Name -eq "postmaster") -or
($R.Name -eq ".net") -or
($R.Name -eq ".com") -or
($R.Name -eq ".org") -or
($R.Name -eq ".")
)
{
write-host $MB.UserPrincipalName
#Remove-CloudInboxRule -Mailbox $MB.UserPrincipalName -Id $R.Name -Confirm:$false
}
}
}
}
Get-InboxRule(在這里重命名為Get-CloudInboxRule)迭代似乎花費了最長的時間。 就目前而言,此代碼每1000個郵箱大約需要1個小時。 這意味着對於我們的1.5萬用戶而言,這需要15個小時的掃描時間……這是在垃圾郵件開始之前嘗試查找惡意規則的時間。
ps這是在SuperUser中發布的,但我意識到這是Powershell編程問題,而不是真正的poweruser問題。
您可能想看一下用於並行處理的Powershell工作流,我還沒有以這種規模使用它,但是它應該加快大型或慢速的“ ForEach”循環。 當我必須連接或ping到大量計算機時,通常使用此方法。
范例程式碼
CLS
### Worflows, Functions, etc.
#Workflow
workflow CheckMailBoxesForBadRules
{
#Mailboxes
$MailBoxes = @(
@{Name="Mailbox1"; Rules=@('rule1','rule2','rule3')}
@{Name="Mailbox2"; Rules=@('rule1','rule2')}
@{Name="Mailbox3"; Rules=@('rule1','rule3')}
@{Name="Mailbox4"; Rules=@('rule2','rule3')}
@{Name="Mailbox5"; Rules=@('rule1')}
@{Name="Mailbox6"; Rules=@('rule2')}
@{Name="Mailbox7"; Rules=@('rule3')}
@{Name="Mailbox8"; Rules=@()}
)
ForEach -Parallel ($Mailbox in $MailBoxes)
{
$BadRules = @()
Foreach ($Rule in $Mailbox.Rules)
{
#logic
$BadRules += $Rule
}
If ($BadRules){
"$($MailBox.Name) " +
"bad-rules: $($BadRules -join ", ")"
}
}
}
### Script Execution
# Workflow Start
CheckMailBoxesForBadRules
輸出量
Mailbox7 bad-rules: rule3
Mailbox6 bad-rules: rule2
Mailbox5 bad-rules: rule1
Mailbox4 bad-rules: rule2, rule3
Mailbox3 bad-rules: rule1, rule3
Mailbox2 bad-rules: rule1, rule2
Mailbox1 bad-rules: rule1, rule2, rule3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.