问题描述
我正在尝试通过目录结构递归地搜索word文档,然后提取超链接。代码执行时输出如下:
'Cannot Convert an object of type string to an object of type Int64'
我尝试过的一切似乎都不起作用。我试过使用:
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
#>