提问人:Viktor Cvijic 提问时间:11/1/2023 最后编辑:Eugene AstafievViktor Cvijic 更新时间:11/9/2023 访问量:42
Power shell Outlook 互操作程序集问题
Power shell Outlook interop assembly problem
问:
我正在尝试使用PowerShell脚本从文件夹中的Outlook项目中提取附件。代码是:'
# Specify the folder containing Outlook item files (.msg)
$sourceFolder = "C:\GRAINGER\GRAINGER\06-07-2023 Placements"
# Specify the parent folder where you want to save attachments
$saveFolder = "C:\GRAINGER\GRAINGER\Attachments\06-07-2023 Placements A"
# Load the Outlook COM Object
Add-Type -TypeDefinition @"
using System;
using Microsoft.Office.Interop.Outlook;
"@
# Create an Outlook Application object
$outlook = New-Object -ComObject Outlook.Application
# Get a list of .msg files in the source folder
$msgFiles = Get-ChildItem $sourceFolder -Filter *.msg
# Loop through each .msg file and extract attachments
foreach ($msgFile in $msgFiles) {
$mailItem = $outlook.Session.OpenSharedItem($msgFile.FullName)
# Create a folder with the same name as the Outlook item file
$itemFolder = New-Item -Path "$saveFolder\$($msgFile.BaseName)" -ItemType Directory
# Loop through each attachment in the email
foreach ($attachment in $mailItem.Attachments) {
$attachment.SaveAsFile("$itemFolder\$($attachment.FileName)")
}
# Close the mail item
$mailItem.Close()
}
# Release Outlook objects
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($attachment) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($mailItem) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($outlook) | Out-Null
我不断收到这样的错误: 类型或命名空间名称“Office”执行 命名空间“Microsoft”中不存在(是否缺少程序集引用? 类别信息 : InvalidData: (Microsoft.Power...peCompilerError:AddTypeCompilerError) [Add-Type],除了 离子 + FullyQualifiedErrorId:SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand
我安装了 office 365,也安装了 outlook。但我被困在这里......
答:
1赞
Dmitry Streblechenko
11/1/2023
#1
您需要先添加互操作 dll
Add-Type -AssemblyName "Microsoft.Office.Interop.Outlook"
或者,您可以跳过整个块并使用后期绑定,而无需依赖互操作。Add-Type -TypeDefinition @"
0赞
Eugene Astafiev
11/9/2023
#2
错误消息指出缺少程序集引用:
The type or namespace name 'Office' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
因此,在代码中使用 Outlook 对象模型之前,需要添加程序集引用。例如,下面介绍如何连接到正在运行的 Outlook 实例或创建新的 Outlook 实例(如果没有正在运行):Application
Add-Type -assembly "Microsoft.Office.Interop.Outlook"
Add-Type -assembly "System.Runtime.Interopservices"
try
{
$outlook = [Runtime.Interopservices.Marshal]::GetActiveObject('Outlook.Application')
$outlookWasAlreadyRunning = $true
}
catch
{
try
{
$Outlook = New-Object -comobject Outlook.Application
$outlookWasAlreadyRunning = $false
}
catch
{
write-host "You must exit Outlook first."
exit
}
}
$namespace = $Outlook.GetNameSpace("MAPI")
评论