狂自私

导航

PowerShell-将word另存为pdf

$folderPath = "D:\工作\temp\2023年4月19日"
$folderPathOut = "D:\工作\temp\2023年4月19日"
$wordFiles = Get-ChildItem -Path $folderPath -Filter "*.docx"
try{
    Get-Process -Name "*word*" |Stop-Process         #避免之前运行失败的word程序影响
    $wordObject = new-object -ComObject "Word.Application"
}
catch {
    Write-Host "Exception Caught: " $_.Exception -ForegroundColor Red
    exit
}
foreach ($file in $wordFiles){
    $pdfPath = Join-Path -Path $folderPathOut -ChildPath ($file.BaseName + ".pdf")
    try{
        $document = $wordObject.Documents.Open($file.FullName)
    }
    catch {
        Write-Host "打开word文件: " $_.Exception -ForegroundColor Red
        continue
    }
    try{
        $document.SaveAs($pdfPath, 17)
    }
    catch {
        Write-Host "另存为: " $_.Exception -ForegroundColor Red
    }
    finally{
        $document.Close()
    }
}
$wordObject.Quit()
Remove-Variable wordObject

 

posted on 2023-05-18 15:05  狂自私  阅读(66)  评论(0编辑  收藏  举报