I am trying to print parts of several docx files. The code below works in Windows PowerShell 5.1, but not in PowerShell 7.3. I would like to understand why and help updating the code so it works in PowerShell 7.3.
$path = 'D:\SchoolWeb\DOCXtoPDF\test.docx' #Path to docx
$Word = New-Object -ComObject Word.Application #open MS Word app
$Word.Visible = $false #hide the MS Word app
$docx = $Word.Documents.Open($path) #Open the docx from the path into the open MS Word app
$pagesNum = $Word.ActiveDocument.ComputeStatistics([Microsoft.Office.Interop.Word.WdStatistic]::wdStatisticPages) #Get the number of pages in the docx
$max=$pagesNum-2 #Get the maximum pages because the last two pages are not important
$Missing = [System.Reflection.Missing]::Value # Default values
$BackGround = 0
$Append = 0
$Range = 4 #https://learn.microsoft.com/en-us/office/vba/api/word.wdprintoutrange
$OutputFileName = $Missing
$From = $Missing # values I've tried "1"
$To = $Missing # values I've tried $max
$Item = 0
$Copies = 1
#$Pages = $max # values I've tried
if ($max -gt 1) { $Pages = "1-$max" } else { $Pages = "1" }
$Word.PrintOut([ref]$BackGround, [ref]$Append, [ref]$Range, [ref]$OutputFileName, [ref]$From, [ref]$To, [ref]$Item, [ref]$Copies, [ref]$Pages)
$docx.Close($false)
$Word.Quit()
In Powershell 7.3, I get a MethodException "Exception setting "PrintOut": Cannot convert the "1" value of type "string" to type "Object"."
I know this relates to the $Pages variable.
Here are some places I already looked:
Thank you for explaining why the code works in one PowerShell and not the other and helping me to correct the code so it works in PowerShell 7.3.