http://www.jaapbrasser.com/


需求就是批量转换大量的PPT文件为PDF文件,如果手动一个个文件打开再另存为,也可以实现,这样会花费比较长的时间,当然,一个POWERSHELL人员会用另一种思维来解决。


wKioL1nAxdvDnAe0AAFk40KfWSc154.png-wh_50


其实有很多PPT文件,涉嫌个人工作,故略去。


打开一个ISE,记住一定要用管理员权限打开,否则执行代码时会出错。

Get-ChildItem -Path 'C:\Work file\test\HD 工作文档\运维类\Report' -Filter *pptx -Recurse |
ForEach-Object -Begin {
    $null = Add-Type -AssemblyName Microsoft.Office.Interop.powerpoint
    $SaveOption = [Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType]::ppSaveAsPDF
    $PowerPoint = New-Object -ComObject "PowerPoint.Application"
} -Process {
    $Presentation = $PowerPoint.Presentations.Open($_.FullName)
    $PdfNewName = $_.FullName -replace '\.pptx$','.pdf'
    $presentation.SaveAs($PdfNewName,$SaveOption)
    $presentation.close()
} -end{
    $powerpoint.quit()
    Stop-Process -name POWERPNT -Force

执行一下,看结果。


wKioL1nAxqCRklHtAAQzO0rN-dM526.png-wh_50



当时出错,是我把进程名POWERPNT,写成了PONWERPOINT了


再用脚本看看执行结果:

foreach ($Extension in ('pptx','pdf')) {
    Get-ChildItem -Path 'C:\Work file\test\HD 工作文档\运维类\Report' -File -Filter "*$Extension" -Recurse |
    Measure-Object -Property Length -Sum | ForEach-Object {
        [pscustomobject]@{
            'SizeinMB'  = [math]::Round($_.Sum/1MB,2)
            'Extension' = $Extension
        }
    }
}


PS C:\> foreach ($Extension in ('pptx','pdf')) {

    Get-ChildItem -Path 'C:\Work file\test\HD 工作文档\运维类\Report' -File -Filter "*$Extension" -Recurse |

    Measure-Object -Property Length -Sum | ForEach-Object {

        [pscustomobject]@{

            'SizeinMB'  = [math]::Round($_.Sum/1MB,2)

            'Extension' = $Extension

        }

    }

}


SizeinMB Extension

-------- ---------

  134.14 pptx     

   74.93 pdf      


这里面有一个很重要的调用对像的方法,就是:

$null = Add-Type -AssemblyName Microsoft.Office.Interop.powerpoint

这个方法$null 这个解释起来是一个空封装到一个空对像的引用,目前只能是大概知道这种方法,以前测试过代码对OFFICE对像的引用总是出错,有可能是调用方法不对。当然,还会对OFFICE对像的调用做进一步的研究。