该脚本打开与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个小时。这意味着对于我们的15K用户来说,这需要15个小时来扫描......在垃圾邮件开始之前尝试查找恶意规则的时间很长。
p.s这张贴在SuperUser上,但我意识到它是一个Powershell编程问题,而不是真正的poweruser问题。
答案 0 :(得分:0)
您可能希望查看用于并行处理的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