我们倾向于将Outlook中的消息拖放到Windows资源管理器中,因此我需要重命名默认消息文件名,以便可以从资源管理器中搜索/读取文件。
我设法将以下代码放在一起,几乎将网络文件夹中的Outlook文件从默认的“Subject.msg”重命名为“To - Subject - ReceivedDate - hhmmss.msg”。唯一的问题是重命名步骤不起作用,因为我认为Outlook进程正在锁定文件。我将不胜感激,以避免锁定和重命名文件?另外,我不确定如果To列表中有多个人会发生什么,我很乐意在To列表中取名?这是我的努力:
$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
}
P.S。 [插入@ 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命令并成功运行。
答案 0 :(得分:1)
这是怎么回事?
基本上我所做的改变是:
然后另一个循环进行重命名。
# Declare the hastable to store the names, then generate the names.
$nameHash = @{}; Foreach ($msg in $SourceFiles){
# Do the Outlook thing
$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"
# Store the names
$nameHash.Add("$msg","$newfilename")
}
# Kill Outlook.. Then wait....
Stop-Process -Name Outlook -Force
Start-Sleep -m 500 # You might be able to remove this - depends how beefy your CPU is.
# Rename
ForEach ($item in $nameHash.GetEnumerator()) {
# Testing >>-->
echo $item.Name
echo $item.Value
# <--<< Testing
Rename-Item $item.Name $item.Value
}