Powershell:清空多个帐户的文件夹 [英] Powershell: Empty Folder Cleanup of Multiple Accounts

查看:68
本文介绍了Powershell:清空多个帐户的文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这不是正确的子论坛,我很抱歉。  我在一个高度自动化的环境中工作,在其文档处理任务中使用Exchange。 电子邮件会被发送到文件夹,然后从中读取并进一步处理,然后存档。 
这导致数百个空档案文件夹,我想按计划清理。 我找到了一个使用EWS的功能脚本,适用于单个邮箱/帐户:

My apologies if this is not the correct subforum.   I work in a heavily automated environment that uses Exchange in its document processing tasks.  Emails get sent to folders, then read from them and further processed, then archived.  This results in hundreds of empty archive folders, which I would like to clean up on a schedule.  I have found a functional script that uses EWS and works well for a single mailbox/account:

##Version 2 added url encoding
## Get the Mailbox to Access from the 1st command line argument. Enter the SMTP address of the mailbox
$MailboxName = "SMTPAddress"

## Load Managed API dll
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
Add-Type -AssemblyName System.Web

## Set Exchange Version. Use one of the following:
## Exchange2007_SP1, Exchange2010, Exchange2010_SP1, Exchange2010_SP2, Exchange2013, Exchange2013_SP1
$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1

## Create Exchange Service Object
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)

## Set Credentials to use two options are available Option1 to use explicit credentials or Option 2 use the Default (logged On) credentials

## Credentials Option 1 using UPN for the Windows Account
$psCred = Get-Credential
$creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())
$service.Credentials = $creds

## Credentials Option 2
#service.UseDefaultCredentials = $true

## Choose to ignore any SSL Warning issues caused by Self Signed Certificates

## Code From http://poshcode.org/624
## Create a compilation environment
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Provider.CreateCompiler()
$Params=New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable=$False
$Params.GenerateInMemory=$True
$Params.IncludeDebugInformation=$False
$Params.ReferencedAssemblies.Add("System.DLL") | Out-Null

$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() {
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert,
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly

## We now create an instance of the TrustAll and attach it to the ServicePointManager
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll

## End code from http://poshcode.org/624

## Set the URL of the CAS (Client Access Server) to use two options are available to use Autodiscover to find the CAS URL or Hardcode the CAS to use

## CAS URL Option 1 Autodiscover
$service.AutodiscoverUrl($MailboxName,{$true})
"Using CAS Server : " + $Service.url
  
## CAS URL Option 2 Hardcoded
#$uri=[system.URI] "https://casservername/ews/exchange.asmx"
#$service.Url = $uri
  
## Optional section for Exchange Impersonation
#$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)

## Show Trace. Can be used for troubleshooting errors
#$service.traceenabled = $true

function ConvertId{
	param (
	        $OwaId = "$( throw 'OWAId is a mandatory Parameter' )"
		  )
	process{
	    $aiItem = New-Object Microsoft.Exchange.WebServices.Data.AlternateId
	    $aiItem.Mailbox = $MailboxName
	    $aiItem.UniqueId = $OwaId
	    $aiItem.Format = [Microsoft.Exchange.WebServices.Data.IdFormat]::OwaId
	    $convertedId = $service.ConvertId($aiItem, [Microsoft.Exchange.WebServices.Data.IdFormat]::EwsId)
		return $convertedId.UniqueId
	}
}

## Get Empty Folders from EMS
get-mailboxfolderstatistics -identity cnrecon | Where-Object{$_.FolderType -eq "User Created" -band $_.ItemsInFolderAndSubFolders -eq 0} | ForEach-Object{
	# Bind to the Inbox Folder
	"Deleting Folder " + $_.FolderPath
	try{
		
		$urlEncodedId = [System.Web.HttpUtility]::UrlEncode($_.FolderId.ToString())
		$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId((Convertid $urlEncodedId))
		#$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId((Convertid $_.FolderId))
		$ewsFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
		if($ewsFolder.TotalCount -eq 0){
			$ewsFolder.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete)
			"Folder Deleted"
		}
	}
	catch{
		$_.Exception.Message
	}
}

稍微调整一下,通过将$ MailboxName定义为我想要清理的所需框的SMTP地址,这对我运行它的每个邮箱都很有效。 值得注意的是,由于某种原因,$ MailboxName别名在自动发现中查找
的部分无法正常工作...我还必须手动将地址放在那里。

With a little tweaking this works great for each mailbox I run it against by defining the $MailboxName as the SMTP address of the desired box I want to clean.  It's worth noting that for some reason the $MailboxName alias isn't working in the part where it looks up in Autodiscover...I have to manually put the address in there as well.

我的问题是,是否可以将其修改为针对多个电子邮箱? 我有几个记分箱,每个记分箱都有数百个空的归档文件夹。 为每个框运行单独的脚本似乎效率低下。 我尝试使用$ MailboxName的地址替换文本
文件,但这在自动发现部分中不起作用。

My question is, can this be modified to work against multiple email boxes?  I have several score boxes with hundreds of empty archived folders each.  Running an individual script for each box seems inefficient.  I tried supplanting a text file with addresses for $MailboxName, but that doesn't work in the Autodiscover part further down.

感谢您提供的任何帮助,我对Powershell或一般的脚本都不是很有经验,所以这感觉就像我潜水一点。

Thank you for any help you can offer, I'm not very experienced with Powershell or scripting in general, so this feels like I'm diving in a little deep.

推荐答案

您需要重写脚本才能执行此操作,例如,可以使用Get-Mailbox来提供
get
- mailboxfolderstatistics,您仍然需要单独处理每个邮箱。

> ;>感谢您提供的任何帮助,我对Powershell或一般的脚本都不是很有经验,所以这感觉就像我在深度潜水一样。

>> Thank you for any help you can offer, I'm not very experienced with Powershell or scripting in general, so this feels like I'm diving in a little deep.

有一个类似的脚本如果您打算在100个邮箱中运行它,那么删除您想要非常小心的数据,我的建议是您首先将其重写为报告脚本,您只需将结果输出到文本文件然后当您有$ b时$ b运行良好且您确信不会删除任何不应该删除的东西,而是将其更改为删除内容的脚本。

with a script like this that deletes data you do want to be very careful if your going to run it against 100's of mailboxes, my suggestion is you rewrite it first as a reporting script where you just output the result to a text file then when you have that running well and your confident it's not going to delete anything that it shouldn't you can than change it to a script that deletes things.

干杯

Glen

Cheers
Glen


这篇关于Powershell:清空多个帐户的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆