2

Trying to use native powershell way to assign null value to variable which can not be resolved. My understanding if I set Set-StrictMode -Off I shall be able to do something like below but it fails. Is there a way to tell powershell engine that in case exception is thrown just assign $null to result and don't show any exceptions without if statement

PS C:\Users\a> $item = $string.NonExistentmember.Split("/")
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $item = $string.NonExistentmember.Split("/")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
Gregory Suvalian
  • 3,566
  • 7
  • 37
  • 66
  • Umm... no. PowerShell will expand non-existent values/properties to empty values alright, but that doesn't mean you can call a (non-existing) method on such an empty value. In this particular case you could dodge the error by using the `-split` operator instead of the `Split()` method, but good practice is to not expect the runtime to gloss over such things. – Ansgar Wiechers Dec 18 '18 at 19:16

1 Answers1

3

This isn't related to strict mode (which is off by default anyway). You're looking more for something like C#'s null conditional operator ?., which would let you do

$string?.NonExistentmember?.Split("/")

if it existed in PowerShell, which it unfortunately doesn't.
(However, its introduction is being discussed in this GitHub issue.)

You can use the split operator like Ansgars suggested in a comment:

$string.NonExistentmember -split "/"

But do note that they don't work exactly the same (the operator uses regex, the method uses chars).

mklement0
  • 382,024
  • 64
  • 607
  • 775
briantist
  • 45,546
  • 6
  • 82
  • 127