使用Powershell,我们可以使用下面的代码将Word文件转换为PDF,但我们需要为多个文件夹执行此操作。我们怎么做到这一点?
$wdFormatPDF = 17
$word = New-Object -ComObject word.application
$word.visible = $false
$folderpath = "C:\folder\*"
$fileTypes = "*.docx","*doc"
Get-ChildItem -path $folderpath -include $fileTypes |
foreach-object `
{
$path = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
"Converting $path to pdf ..."
$doc = $word.documents.open($_.fullname)
$doc.saveas([ref] $path, [ref]$wdFormatPDF)
$doc.close()
}
$word.Quit()
答案 0 :(得分:0)
您可以使用Get-ChildItem
的-Directory属性来仅获取给定文件夹的目录,然后在每个单独的文件夹中枚举您的代码
$Folders = Get-ChildItem <Path to convert here> -Directory
ForEach ($Folder in $Folders)
{
$wdFormatPDF = 17
$word = New-Object -ComObject word.application
$word.visible = $false
$folderpath = "$($Folder.FullName)\*"
$fileTypes = "*.docx","*doc"
Get-ChildItem -path $folderpath -include $fileTypes |
foreach-object `
{
$path = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
"Converting $path to pdf ..."
$doc = $word.documents.open($_.fullname)
$doc.saveas([ref] $path, [ref]$wdFormatPDF)
$doc.close()
}
$word.Quit()
}
答案 1 :(得分:0)
添加递归将轻松解决问题。
Get-ChildItem -path $folderpath -include $fileTypes -Recursive |