Skip to content

/errors/powershell/you-cannot-call-a-method-on-a-null-valued-expression

PowerShell: You cannot call a method on a null-valued expression.

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated
tool
PowerShell
exit code
1
versions
Windows PowerShell 5.1, PowerShell 7.x
os
windows, linux, macos

You cannot call a method on a null-valued expression. means the part before .Method() evaluated to $null. PowerShell does not say which part: in $config.Database.Name.ToUpper(), any of $config, .Database or .Name can be the null one. Print the pieces, find the first $null, and fix the lookup that produced it, or guard the call with if ($null -ne $x).

Reproduce it

powershell
$ErrorActionPreference = 'Stop'
$config = [pscustomobject]@{ Database = [pscustomobject]@{ Host = 'db01' } }
try { $config.Database.Name.ToUpper() } catch { $_.Exception.Message; '  -> ' + $_.FullyQualifiedErrorId }
"Host: [$($config.Database.Host)]  Name: [$($config.Database.Name)]  Name is null: $($null -eq $config.Database.Name)"
$file = Get-ChildItem -Filter *.nomatch | Select-Object -First 1
try { $file.Name.Replace('a', 'b') } catch { $_.Exception.Message }

Output

You cannot call a method on a null-valued expression.
  -> InvokeMethodOnNull
Host: [db01]  Name: []  Name is null: True
You cannot call a method on a null-valued expression.

Reading a property that does not exist returns $null without an error; only the method call fails.

Guard the call

powershell
$name = $null
if ($null -ne $name) { $name.ToUpper() } else { 'name is empty' }
"[$("$name".ToUpper())]"
Set-StrictMode -Version Latest
$config = [pscustomobject]@{ Host = 'db01' }
try { $config.Name } catch { $_.Exception.Message }

Output

name is empty
[]
The property 'Name' cannot be found on this object. Verify that the property exists.
  • Put $null on the left of comparisons ($null -ne $x): with an array on the left, -ne filters the array instead of testing it.
  • "$value" turns $null into an empty string, which is safe when an empty result is acceptable.
  • Strict mode makes missing properties fail at the property access, which points to the real cause.
  • PowerShell 7.1 and later have null-conditional member access, ${name}?.ToUpper(), which returns $null instead of failing. Windows PowerShell 5.1 does not have it.

Sources