Why powershell does not open excel?

Eli Valero 1 Reputation point
2020-09-04T16:59:03.92+00:00

$Excel = New-object -ComObject Excel.application
$Path = "Path"
$Excel.Workbooks.Open($Path)

It works most of the time, but sometimes, like today, is not working.
The error is:

You cannot call a method on a null-valued expression
At line: "x" Char: "s"
$Excel.Workbooks.Open($Path)

Any suggestions?

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2020-09-04T19:14:11.293+00:00

    Try wrapping that in a Try/Catch:

    Try{
        $Excel = New-object -ComObject Excel.application -ErrorAction STOP
        $Path = "Path"
        $Excel.Workbooks.Open($Path)
    }
    Catch{
        $_      # just display the exception (or send it into the pipeline)
        Throw "your failure message here"    # or 'Throw $_'
    }
    

    Without knowing what the problem is I don't think anyone can offer advice that's meaningful.


  2. Eli Valero 1 Reputation point
    2020-09-04T20:31:58.897+00:00

    Hello Rich,

    This is what I have now. That is giving me the mentioned error. I apologize for not being detailed enough.

    $Excel = New-Object -ComObject Excel.application
    $FilePath = "Path"
    $Workbook = $Excel.Workbooks.Open($FilePath)
    $Excel.visible = $True
    $app = $excel.Application
    $app.Run("Macro")


  3. Clifton Dunaway 1 Reputation point
    2021-04-28T13:00:11.97+00:00

    I have the same problem. When I tried the Try-Catch code, here is my error:

    your failure message here
    At line:9 char:6

    • Throw "your failure message here" # or 'Throw $_'
    • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : OperationStopped: (your failure message here:String) [], RuntimeException
    • FullyQualifiedErrorId : your failure message here
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.