Powershell使用Word CheckSpelling和选定的字典

时间:2014-10-18 10:50:39

标签: powershell dictionary com ms-word spell-checking

我想使用Powershell中的Microsoft Word API和特定字典(“英语(美国)”)拼写检查一些字符串。 我使用以下代码进行检查,但它似乎没有考虑我想要的字典。有什么想法有什么不对?此外,命令“New-Object -COM Word.Dictionary”似乎失败了。

$word = New-Object -COM Word.Application
$dictionary = New-Object -COM Word.Dictionary

foreach ($language in $word.Languages) {
    if ($language.Name.Contains("English (US)")) {
        $dictionary = $language.ActiveSpellingDictionary;
        break;
    }
}

Write-Host $dictionary.Name

$check = $word.CheckSpelling("Color", [ref]$null, [ref]$null, [ref]$dictionary)
if(!$check) {
    Write-Host "Spelling Error!"
}

$word.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
Remove-Variable word

3 个答案:

答案 0 :(得分:0)

COMobject word.dictionary不存在(至少不在我的机器上),这是我在短测试中对我有用的东西:

$dic = New-Object -COM Scripting.Dictionary #credits to MickyB
$w = New-Object -COM Word.Application
$w.Languages | % {if($_.Name -eq "English (US)"){$dic=$_.ActiveSpellingDictionary}}
$w.checkSpelling("Color", [ref]$null, [ref]$null, [ref]$dic)

答案 1 :(得分:0)

除了保罗之外的另一种可能性:

$dictionary = New-Object -COM Scripting.Dictionary

答案 2 :(得分:0)

我遇到了同样的问题,Word.Application.checkSpelling()方法似乎忽略了传递给它的任何字典。我解决了以下问题:创建Word文档,定义文本范围,将该范围的LanguageID更改为我想证明要使用的语言,然后检查检测到的拼写错误。这是代码:

<#Function which helps to pick the language#>
function FindLanguage($language_name){    
    foreach($element in $Word.Languages){
        if($element.Name -eq $language_name){
            $element.Name
            return $element
        }
    }
}
$Proofread_text = "The lazie frog jumpss over over the small dog."
$Word = New-Object -COM Word.Application
$Document = $Word.Documents.Add()
$Textrange = $Document.Range(0)

$english = FindLanguage("English (US)")

$Textrange.LanguageID = $english.ID
$Textrange.InsertAfter($Proofread_text)

<#Handle misspelled words here#>
foreach($spell_error in $textrange.SpellingErrors){
    Write-Host $spell_error.Text    
}

$Document.Close(0)
$Word.Quit()

输出将是:

>>lazie
>>jumpss
>>over

我发现在启动脚本之前禁用单词中的语言自动检测功能很有帮助。特别是当您计划切换语言时。