Object reference not set to an instance of an object
Object reference not set to an instance of an object
DodaTech
3 min read
The “Object reference not set to an instance of an object” error in PowerShell means you tried to access a property or method on a variable that is $null.
What It Means
PowerShell is built on .NET, where every object reference either points to an actual instance or is $null. When you access a property ($obj.Property) or call a method ($obj.Method()) on a $null reference, .NET throws a NullReferenceException — the most common runtime exception across all .NET languages. The error tells you a reference was null but does not tell you which variable, so you must trace back through your code to find the source.
Why It Happens
- A cmdlet or function returned
$nullbut you did not check the result. - A hash key or array index does not exist:
$data["missing"]. - A property on a nested object is null:
$computer.BIOS.SerialNumberwhere$computer.BIOSis$null. - You assigned
$nullearlier and forgot:$result = $null. - An XML node or JSON field was not present in the parsed document.
- A parameter was not provided:
param($Name)called without$Name.
How to Fix It
1. Check for null before accessing properties
# Bad
$process = Get-Process -Name "nonexistent" -ErrorAction SilentlyContinue
$process.Name
# Good
$process = Get-Process -Name "nonexistent" -ErrorAction SilentlyContinue
if ($process) {
$process.Name
} else {
Write-Warning "Process not found"
}2. Use the null-conditional operator (PowerShell 7+)
# Only available in PowerShell 7 and later
$computer.BIOS?.SerialNumber
# Returns $null instead of throwing if BIOS is null3. Use default values with the null-coalescing operator
# PowerShell 7+
$name = $user.Name ?? "Unknown"
# Or in older versions
$name = if ($user) { $user.Name } else { "Unknown" }4. Check before method calls
$services = Get-Service -Name "Nonexistent" -ErrorAction SilentlyContinue
if ($null -ne $services) {
$services.Start()
}5. Verify hash tables and arrays have the key or index
$data = @{ name = "Alice" }
# Bad — key doesn't exist
$data.email.ToString()
# Good — check first
if ($data.ContainsKey("email")) {
$data.email.ToString()
}
# Or use TryGetValue
$value = $null
if ($data.TryGetValue("email", [ref]$value)) {
$value.ToString()
}6. Trace null sources with verbose output
Write-Debug "Variable `$result is: $($result | Out-String)"
$result.Property # If this fails, the debug output shows what $result wasBuilt by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro