Error when attempting to open MS word file

Hello, I am new to PowerShell and I am trying to learn to manipulate MS word with PowerShell.

Below are the commands that I ran:

PS C:\WINDOWS\system32> $Word = New-Object –comobject Word.Application

PS C:\WINDOWS\system32> $Document = $Word.documents.open( $Filename )
Object reference not set to an instance of an object.
At line:1 char:1

  • $Document = $Word.documents.open( $Filename )
  •   + CategoryInfo          : OperationStopped: (:) [], NullReferenceException
      + FullyQualifiedErrorId : System.NullReferenceException
    
    

However, I have encountered an error and I do not know how to resolve it. I would appreciate it if someone could help me with this. Thank you.

You’re using the variable $filename but you haven’t given the variable a value. You need to set it to a string that represents the path to the file. e.g.
$filename = 'C:\mydocs\mydoc.docx'

Thanks for the reply Matt, I didn’t include the line where I declared the variable but I did assign a value to the variable $filename in the previous line, so I don’t think that’s the problem here.

Do you happen to know what the error message “Object reference not set to an instance of an object.” means?

It means the Object reference (the variable) does not have a value.

I can reproduce the error by not setting $filename to a value. Please post your full code.

Ok, here is my full code.

$filename = .\Desktop\test.docx

$Word = New-Object –comobject Word.Application

$Document = $Word.documents.open( $Filename )

The behaviour you should be seeing when you run that code is that the first line opens the Word document, it doesn’t actually assign any value to $filename.

You should enclose the .Desktop\test.docx in single quotes '.\Desktop\test.docx'

2 Likes

Ohhh I see, the error disappeared after I enclosed the path in single quotes. Thank you very much for the help!