在Powershell中转换后删除文件

时间:2015-05-15 10:42:48

标签: powershell

我在Powershell中缺乏经验 - 但通过反复试验,我设法让.doc / .docx到.pdf转换适用于指定的文件夹和所有子文件夹。

$wdFormatPDF = 17
$word = New-Object -ComObject word.application
$word.visible = $false
$fileTypes = "*.docx","*.doc"
Get-ChildItem -Recurse -path "C:\test-acrobat" -include $fileTypes |
foreach-object `
{
 $path =  ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
 "Converting $path to pdf ..."
 $doc = $word.documents.open($_.fullname)
 $doc.saveas( $path, $wdFormatPDF)
 $doc.close()
}
$word.Quit()

现在我希望能够在转换后删除原始的.doc / .docx文件。在进行一些搜索时,我发现了我认为可行的方法:

{
  remove-item $fileTypes  # delete file from file-system
}

但我宁愿检查也不要输入删除文件的命令......

非常感谢任何帮助。 菲利普

1 个答案:

答案 0 :(得分:0)

我会在foreach循环中添加删除。

所以你会得到:

$wdFormatPDF = 17
$word = New-Object -ComObject word.application
$word.visible = $false
$fileTypes = "*.docx","*.doc"
Get-ChildItem -Recurse -path "C:\test-acrobat" -include $fileTypes |
foreach-object `
{
  $path =  ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
  Write-Host "Converting $path to pdf ..."
  $doc = $word.documents.open($_.fullname)
  $doc.saveas( $path, $wdFormatPDF)
  $doc.close()
  Remove-Item $_.fullname
}
$word.Quit()