briskovich
briskovich

Reputation: 690

Powershell script not iterating through child folders

I sniped this script online and it works fine for converting the files in the parent folder. It does not however iterate through the child folders. I do not get any errors and I have verified all the folder permissions are correct. Additionally, I have scripts that are coded similar for *.docx and *.pptx files and they run successfully. This one however is not working as expected. Any ideas?

$path = "c:\converted\" 
$xlFixedFormat = "Microsoft.Office.Interop.Excel.xlFixedFormatType" -as [type] 
$excelFiles = Get-ChildItem -Path $path -include *.xls, *.xlsx -recurse 
$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 
"converted $wb.fullname" 
 $workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $filepath) 
 $objExcel.Workbooks.close() 
 #get rid of conversion copy 
 #Remove-Item $wb.fullname 
} 
$objExcel.Quit() 

Upvotes: 0

Views: 71

Answers (1)

user6811411
user6811411

Reputation:

$excelFiles will contain subfolders, but your construction of $filepath uses only the original $path and current $wb.BaseName without taking into account that the current $wb.FullName may contain a longer path.

Replace

 $filepath = Join-Path -Path $path -ChildPath ($wb.BaseName + ".pdf") 

with

$filepath = $wb.fullname -replace $wb.extension,".pdf"

Upvotes: 1

Related Questions