我们倾向于将消息从 Outlook 拖放到 Windows 资源管理器中,因此我需要重命名默认消息文件名,以便可以从资源管理器中搜索/读取文件。
我设法将以下代码放在一起,几乎将网络文件夹上的 Outlook 文件从默认的“Subject.msg”重命名为“To - Subject - ReceivedDate - hhmmss.msg”。唯一的问题是重命名步骤不起作用,因为我相信 Outlook 进程正在锁定文件。我会很感激帮助避免锁定和重命名文件?另外,我不确定如果收件人列表中有多个人会发生什么,我很乐意在收件人列表中取第一个名字吗?这是我的努力:
$olMailItemPath = "W:\Marketing\Prospects\Emails\*"
Write-Host $olMailItemPath
$SourceFiles = Get-Item -path $olMailItemPath -include *.msg
$outlook = New-Object -comobject outlook.application
$namespace = $outlook.GetNamespace("MAPI")
function cleanName($aname)
{
$aname = $aname -replace "'"
$aname = $aname -replace ":"
$aname = $aname -replace "@"
$aname = $aname -replace "-"
return ($aname.trim())
}
function cleanSubject($subject)
{
$subject = $subject -replace 'Re:'
$subject = $subject
return (' - ' + $subject.trim() + ' - ')
}
foreach ($msg in $SourceFiles){
$olMailItem = $NameSpace.OpenSharedItem($msg)
$EmailTo = $olMailItem.To
$EmailSubject = $olMailItem.Subject
$DateRecieved = $olMailItem.ReceivedTime
$newfilename = (cleanName($EmailTo)) + (cleanSubject($EmailSubject)) + $DateRecieved.ToString("yyyyMMdd - hhmmss") + ".msg"
# Write-Host "Email Sent To: $EmailTo "
# Write-Host "Subject: $EmailSubject "
# Write-Host "Date Recieved: $DateRecieved"
Write-Host $msg
Write-Host $newfilename
Rename-Item $msg $newfilename
}
ps [插入@ 2013 年 6 月 18 日] 作为对 Athom 的回答,我知道 Outlook 正在锁定文件,因为我收到以下错误:
Rename-Item : The process cannot access the file because it is being used by another process.
At C:\Users\Bertie\Dropbox\Programming\Powershell\Rename Outlook Messages.ps1:41 char:16
+ Rename-Item <<<< -path $msg -newname $newFileName
+ CategoryInfo : WriteError: W:\Marketing\Prospects\Emails\new.msg:String) [Rename-Item], IOException
+ FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand
但是,当我关闭 Outlook(由 powershell 脚本启动)时,我可以运行 Rename-Item 命令并成功运行。