$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