微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我无法使用 Powershell 从 Word 文档中提取超链接

如何解决我无法使用 Powershell 从 Word 文档中提取超链接

我正在尝试通过目录结构递归地搜索word文档,然后提取链接代码执行时输出如下:

'Cannot Convert an object of type string to an object of type Int64'

我尝试过的一切似乎都不起作用。我试过使用:

  • “超链接”= $_Address
  • "超链接" = $thisDoc.Address
  • "超链接" = $thisDoc.Hyperlink.Address
processing 2 docs

File Name                Hyperlink
---------                ---------
C:\temp\doc1.docx
C:\temp\doc1.docx
C:\temp\folder\doc2.docx
C:\temp\folder\doc2.docx

解决方法

错误在于您如何为所需的属性值调用它。

试试这个...重构

Clear-Host

$parentFolder = "D:\temp\Word"

$ourDocs = Get-ChildItem -Recurse -LiteralPath $parentFolder -file -include '*.doc*'
"processing {0} docs" -f $ourDocs.Count


$word                = New-Object -ComObject word.application
$word.Visible        = $false
$word.ScreenUpdating = $false

# This really is not needed for your posted use case.
# $array = New-Object System.Collections.ArrayList

$ourDocs | 
ForEach-Object{
    $thisDoc = $word.Documents.Open($PSItem.FullName)

    @($thisDoc.Hyperlinks) | 
    ForEach-Object {
        [pscustomobject]@{
            FileName  = $thisDoc.FullName
            HyperLink = $PSitem.Address
        }
    }
    $thisDoc.Close()
}

$Word.Quit()


# cleanup com objects
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

# Results
<#
processing 4 docs

FileName                     HyperLink                                        
--------                     ---------                                        
D:\temp\Word\WES - Copy.docx http://stackoverfow.com/                         
D:\temp\Word\WES - Copy.docx https://superuser.com/questions/tagged/powershell
#>

更新相对于您的 Csv 评论和我的回复...

...

$ourDocs | 
ForEach-Object{
    $thisDoc = $word.Documents.Open($PSItem.FullName)

    @($thisDoc.Hyperlinks) | 
    ForEach-Object {
        [pscustomobject]@{
            FileName  = $thisDoc.FullName
            HyperLink = $PSitem.Address
        }
    } | 
    Export-Csv -Path 'D:\Temp\WordHyperLinkReport.csv' -Append -NoTypeInformation
    $thisDoc.Close()
}

...

Import-Csv -Path 'D:\Temp\WordHyperLinkReport.csv'
# Results
<#
FileName                     HyperLink                                        
--------                     ---------                                        
D:\temp\Word\WES - Copy.docx http://stackoverfow.com/                         
D:\temp\Word\WES - Copy.docx https://superuser.com/questions/tagged/powershell
#>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。