I am running below code -

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Excel")

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Core")

[Microsoft.Office.Interop.Excel.Application]$xl = new-object
Microsoft.Office.Interop.Excel.ApplicationClass

$file="D:\test\test.csv"

$xl.visible = $true

$wbk = $xl.Workbooks.Open("$file")

$wks = $wbk.worksheets.item(1)

$r1=[Microsoft.Office.Interop.Excel.IRange]$wks.Range("A1:A1")



#Commented code

#$r2=[Microsoft.Office.Interop.Excel.IRange]$wks.Range("A2:A2")

#$mis = [System.Reflection.Missing]::Value;

#$xl.Union($r5, $r6, $mis, $mis, $mis, $mis, $mis, $mis, $mis, $mis, $mis,
$mis, $mis, $mis, $mis, $mis, $mis, $mis, $mis, $mis, $mis, $mis, $mis, $mis,
$mis, $mis, $mis, $mis, $mis, $mis)

..............

It throws below error while I try to typecast _ComObject returned to IRange
(To run the script, just create a new Excel file and save it to .csv format
D:\test\test.csv)

Error message -

$r1=[Microsoft.Office.Interop.Excel.IRange]$wks.Range <<<< ("A11")

+ CategoryInfo : NotSpecified: ( [], RuntimeException

+ FullyQualifiedErrorId : RuntimeException

Typecasting is required otherwise the next command to union two range
(commented code) fails with same error.

I am stuck on it. Please advice.