Solid Snake
Solid Snake

Reputation: 23

powershell 'You cannot call a method on a null-valued expression'

$DrivesObject = Get-Disk | Sort-Object -Property Number 
$DrivesTable = New-Object System.Data.DataTable
$DrivesTable.Columns.AddRange(@("Number", "FriendlyName", "SerialNumber"))
try
{
    foreach ($drive in $DrivesObject)
    { [void]$DrivesTable.Rows.Add(($drive.Number), ($drive.FriendlyName).Trim(), ($drive.SerialNumber).Trim()) }
}
catch
{ Write-Host $_.Exception.Message; Exit }
$DrivesTable

Where I run this script I get error 'You cannot call a method on a null-valued expression.' But If I replace ($drive.SerialNumber).Trim()) with ($drive.SerialNumber) then the script run without error. Please help why adding .Trim() gives error

Upvotes: 2

Views: 6134

Answers (1)

swbbl
swbbl

Reputation: 864

Since Trim() is a method, there must be a value set to use it. In your case, SerialNumber is not present for all Disks, but that's not an issue (depends on the disk's firmware).

If an object/variable/property is not existent (NULL), methods won't work and will throw an error. You need to check that before using such a method.

Either you use the trick which @iRon mentioned by enclosing everthing in double quotes (which will create a String even if the input is NULL) or you need to check for $NULL explicity.

With PS 7 you can additionally use "NULL-conditional operator"

See: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7#null-conditional-operators--and-

Example for PS7:

$nullVar = $null

Write-Host 'Default property accessor (will throw an error)' -ForegroundColor Yellow
Write-Host ("`t{0,-10}: {1}" -f 'toString', $nullVar.toString())
Write-Host ("`t{0,-10}: {1}" -f 'trim', $nullVar.trim())

Write-Host 'Null-conditional operators (works wihtout errors)' -ForegroundColor Yellow
Write-Host ("`t{0,-10}: {1}" -f 'toString', ${nullVar}?.toString())
Write-Host ("`t{0,-10}: {1}" -f 'trim', ${nullVar}?.trim())

Upvotes: 2

Related Questions