如何使用powershell从文件夹中查找某个doc / docx文件短语

时间:2017-05-22 16:31:02

标签: powershell ms-word

早上好,我对powershell很新。

我一直在谷歌搜索如何在某个文件夹中查找.doc,.docx中的某个短语,但我无法找到我想要的确切解决方案。

例如,当我执行此代码时

Get-ChildItem 'C:\Users\koshiasu\Desktop\adhocs' -Filter *.sql |Select-String -Pattern "children"

它在我的powershell底部显示如下

RESULT1

Desktop\adhocs\18722 Parents.sql:11:                     AND EXISTS (SELECT c.id_number FROM children c
Desktop\adhocs\18722 Parents.sql:38:                       AND EXISTS (SELECT c.id_number FROM children c
Desktop\adhocs\2969 ADHOC - Parents in Dallas.sql:11:                     AND EXISTS (SELECT c.id_number FROM children c
Desktop\adhocs\2969 ADHOC - Parents in Dallas.sql:92:                     AND EXISTS (SELECT c.id_number FROM children c

我想对.doc,.docx

做同样的事情

所以我改变了这样的代码

Get-ChildItem 'C:\Users\koshiasu\Desktop\ADHOCS_WORD' -Filter *.doc, *.docx |Select-String -Pattern "Allocations"

但错误是

Get-ChildItem : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Filter'. Specified method is not supported.
At line:2 char:58
+ Get-ChildItem 'C:\Users\koshiasu\Desktop\ADHOCS_WORD' -Filter <<<<  *.doc, *.docx |Select-String -Pattern "Allocations"
    + CategoryInfo          : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.GetChildItemCommand

我应该如何更改代码以显示result1

非常感谢

1 个答案:

答案 0 :(得分:1)

我有一些基本相同的代码,稍微整理一下,这样你就可以知道你在寻找什么:

$Path = "C:\Test"
$Find = "Allocations"
$WordExts = '.docx','.doc','.docm'

$Word = New-Object -ComObject Word.Application #create word obj
$Word.Visible = $false #hide the window

$ValidDocs = Get-ChildItem $Path | ? {$_.Extension -in $WordExts} | ForEach { #Foreach doc/docx/docm file in the above folder
    $Doc = $Word.Documents.Open($_.FullName) #Open the document in the word object
    $Content = $Doc.Content #get the 'content' object from the document
    $Content.MoveStart() | Out-Null #ensure we're searching from the beginning of the doc
                              #term,case sensitive,whole word,wildcard,soundslike,synonyms,direction,wrappingmode
    if ($Content.Find.Execute($Find,$false,        $true,     $false,  $false,    $false,  $true,    1)){ #execute a search
        Write-Host "$($_.Name) contains $($findText)" -ForegroundColor Green
        $_.FullName #store this in $ValidDocs
    } else {
        Write-Host "$($_.Name) does not contain $($findText)" -ForegroundColor Red
    }
    $Doc.Close() #close the individual document
    $Doc = $null #null it just in case
}

$Word.Quit() #quit the word process
$Word = $null #null it just in case

return $ValidDocs #return list of docs with the word in them
相关问题