PowerShell 6 找不到 Excel Interop。PowerShell 5.1 确实

Pok*_*tov 3 excel powershell ms-office

为了使用 xlFileFormat 枚举中的常量,我使用了

[reflection.assembly]::LoadWithPartialName("Microsoft.Office.InterOp.Excel")
Run Code Online (Sandbox Code Playgroud)

在 PowerShell 5.1 中它可以工作。现在我转换到 PowerShell 6。同一行发出错误消息:

使用“1”个参数调用“LoadWithPartialName”时出现异常:“无法加载文件或程序集“Microsoft.Office.InterOp.Excel,Culture=neutral,PublicKeyToken=null”。不支持操作。”

相反,调用 Add-Type,我也收到错误:

Add-Type -AssemblyName "Microsoft.Office.Interop.Excel"
Run Code Online (Sandbox Code Playgroud)

添加类型:找不到路径“C:\transform\software\Microsoft.Office.Interop.Excel.dll”,因为它不存在。

如何加载随 Office 安装的 Interop DLL?

小智 5

这是从 PowerShell 7 访问它的更灵活的方法:

$original_pwd = (Get-Location).Path

cd  C:\Windows\assembly\

$interop_assemply_location = (Get-ChildItem -Recurse  Microsoft.Office.Interop.Outlook.dll).Directory

cd $interop_assemply_location 

Add-Type -AssemblyName "Microsoft.Office.Interop.Outlook" 

cd "$original_pwd"

$Outlook = New-Object -comobject Outlook.Application

$namespace = $Outlook.GetNameSpace("MAPI")
Run Code Online (Sandbox Code Playgroud)

  • 如果你希望它更灵活,那么你需要使用 cd "$env:windir\ assembly" 而不是硬编码路径 (3认同)