0

I am getting the following non-terminating error in PowerShell. I want to catch this and write-host a generic statement, rather than see the error.

Here is the output:

You cannot call a method on a null-valued expression. At C:\PowerShell Scripts\windowsUpdates.ps1:17 char:2 + $a = $key.GetValue("LastSuccessTime") + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRec ordException + FullyQualifiedErrorId : InvokeMethodOnNull

My catch statement is currently not "catching" this.

Any help is appreciated.

SMPLGRP
  • 251
  • 3
  • 8
  • 22
  • Possible duplicate of [You cannot call a method on a null-valued expression - general](http://stackoverflow.com/questions/31335195/you-cannot-call-a-method-on-a-null-valued-expression-general) – Michael Freidgeim Jun 20 '16 at 01:36
  • Does this answer your question? [You cannot call a method on a null-valued expression](https://stackoverflow.com/questions/27525170/you-cannot-call-a-method-on-a-null-valued-expression) – Elikill58 Apr 29 '23 at 12:32

2 Answers2

2

I figured this out. I simply added if($variable -eq $null){write-host "message";}.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
SMPLGRP
  • 251
  • 3
  • 8
  • 22
0

There are a few options

Depending on where you are getting the null variable from you could add

-ErrorAction Stop" after the command so that it treats the non-terminating error as a terminating error.

If that's not an option you could throw an error to force your catch statement to catch the error

if($variable -eq $null){Throw("Variable is Null")}

Or you can make it so that all errors are treated as terminating errors so your catch statement will catch anything that is thrown

$ErrorActionPreference = "Stop"

For more information look at the MSDN documentation here: http://blogs.msdn.com/b/kebab/archive/2013/06/09/an-introduction-to-error-handling-in-powershell.aspx

Schuyler
  • 509
  • 1
  • 9
  • 19