Open a word document and specify encoding with PowerShell

谁说胖子不能爱 提交于 2021-01-29 02:43:52

问题


I'm trying to tell PowerShell to open a text file and choose a certain encoding option. By default, when opening this text file in Word manually, it tries to open it with Japanese encoding and so doesn't show certain characters correctly.

I've tried lots of different things but nothing works so I'm totally stuck.

This text file, amongst others, needs to be converted to PDF on a daily basis.

My current script is as follows:

$wdFormatPDF = 17

$word = New-Object -ComObject Word.Application
$word.Visible = $true

$folderpath = "C:\Users\smirabile\Downloads\report-testing-destination\*"
$fileTypes  = "accepted.spl"

Get-ChildItem -Path $folderpath -Include $fileTypes | ForEach-Object {
    $path = ($_.FullName).Substring(0, ($_.FullName).LastIndexOf("."))

    $doc = $word.Documents.Open($_.FullName)

    $Word.Selection.PageSetup.Orientation = 1
    $Word.Selection.PageSetup.LeftMargin  = 20
    $Word.Selection.PageSetup.RightMargin = 20
    $doc.Select()
    $Word.Selection.Font.Size = 9
    $doc.SaveAs([ref]$path, [ref]$wdFormatPDF)

    $doc.Close()
}

$word.Quit()
Stop-Process -Name WINWORD -Force

回答1:


When in doubt, read the documentation:

Syntax

expression.Open(FileName, ConfirmConversions, ReadOnly, AddToRecentFiles,
    PasswordDocument, PasswordTemplate, Revert, WritePasswordDocument,
    WritePasswordTemplate, Format, Encoding, Visible, OpenConflictDocument,
    OpenAndRepair, DocumentDirection, NoEncodingDialog)

[…]
Encoding | Optional | Variant | The document encoding (code page or character set) to be used by Microsoft Word when you view the saved document. Can be any valid MsoEncoding constant. […] The default value is the system code page.

Use [Type]::Missing for parameters that you want used with their default value.

Example (using iso-8859-15 encoding):

$def = [Type]::Missing
$doc = $word.Documents.Open(
         $_.FullName, $def, $def, $def, $def, $def, $def, $def, $def, $def, 28605
       )


来源:https://stackoverflow.com/questions/41485112/open-a-word-document-and-specify-encoding-with-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!