导出前检查文件是否正在使用中

时间:2016-07-13 21:53:30

标签: loops powershell

我正在编写一个将excel文件导出为PDF的脚本。我得到了那部分工作,但是,因为我在现有PDF上保存,所以当导出发生时它无法打开。我正在寻找一种方法让PowerShell检查文件当前是否打开,如果是,请等待X秒然后再次检查。如果没有,它可以继续。

如果PDF打开,它目前可以正常工作并打破,但是我需要它循环。

这是我到目前为止所拥有的:

$path = "c:\users\XXXXX\documents" 
$xlFixedFormat = "Microsoft.Office.Interop.Excel.xlFixedFormatType" -as [type]
$excelFiles = Get-ChildItem -Path $path -Include spreadsheet.xlsx -Recurse 
$File = "c:\users\XXXXX\documents\Exported.pdf"

try {
  [IO.File]::OpenWrite($File).Close();
  $true
} catch {
  break
}

$objExcel = New-Object -ComObject Excel.Application 
$objExcel.Visible = $false
foreach ($wb in $excelFiles) {
  $filepath = Join-Path -Path $path -ChildPath ($wb.BaseName + ".pdf")
  $workbook = $objExcel.Workbooks.Open($wb.FullName, 3)
  $workbook.Saved = $true
  "saving $filepath"
  $workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $filepath)
  $objExcel.Workbooks.Close() 
}
$objExcel.Quit()

1 个答案:

答案 0 :(得分:3)

这应该做你想要的;感谢Ben Baird的Test-FileLock函数。

function Test-FileLock {
    param ([parameter(Mandatory=$true)][string]$Path)

    $oFile = New-Object System.IO.FileInfo $Path

    if ((Test-Path -Path $Path) -eq $false)
    {
      return $false
    }

    try
    {
        $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
        if ($oStream)
        {
          $oStream.Close()
        }
        # file is unlocked.
        $false
    }
    catch
    {
      # file is locked by a process.
      return $true
    }
}

$path = "c:\users\XXXXX\documents" 
$xlFixedFormat = "Microsoft.Office.Interop.Excel.xlFixedFormatType" -as [type]
$excelFiles = Get-ChildItem -Path $path -Include spreadsheet.xlsx -Recurse 
$File = "c:\users\XXXXX\documents\Exported.pdf"

while((Test-FileLock $file) -eq $true)
{
    Start-Sleep -Seconds 3
}

$objExcel = New-Object -ComObject Excel.Application 
$objExcel.Visible = $false
foreach ($wb in $excelFiles) {
  $filepath = Join-Path -Path $path -ChildPath ($wb.BaseName + ".pdf")
  $workbook = $objExcel.Workbooks.Open($wb.FullName, 3)
  $workbook.Saved = $true
  "saving $filepath"
  $workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $filepath)
  $objExcel.Workbooks.Close() 
}
$objExcel.Quit()

代码将检查文件锁定,如果检测到它等待3秒,然后再试一次。锁定一旦清除,PDF导出代码就会运行。