Forum Discussion
bvi2006
Apr 19, 2019Copper Contributor
Unable to cast object of type System.DBNull
Hi, In pulling data from SQL, some of the columns in the row are null. I receive an exception message: Exception calling "GetString" with "1" argument(s): "Unable to cast object of type 'System.DBN...
- Apr 22, 2019
Can you try the below line :
$Supr_username = if ($_.IsDbNull(10)) { '' } Else { $_.GetString(10) }
Complete script :
$result = $SelectDataTable | foreach-object {
$Supr_username = if ($_.IsDbNull(10)) { '' } Else { $_.GetString(10) }
[pscustomobject]@{
Identity = $_.GetString(2)
Title = $_.GetString(3)
Department = $_.GetString(4)
MSC = $_.GetString(5)
Office_Location = $_.GetString(6)
Office_Phone = $_.GetString(7)
Supr_username = $Supr_username
}
Kevin_Morgan
Apr 22, 2019Iron Contributor
Can you try the below line :
$Supr_username = if ($_.IsDbNull(10)) { '' } Else { $_.GetString(10) }
Complete script :
$result = $SelectDataTable | foreach-object {
$Supr_username = if ($_.IsDbNull(10)) { '' } Else { $_.GetString(10) }
[pscustomobject]@{
Identity = $_.GetString(2)
Title = $_.GetString(3)
Department = $_.GetString(4)
MSC = $_.GetString(5)
Office_Location = $_.GetString(6)
Office_Phone = $_.GetString(7)
Supr_username = $Supr_username
}
Gary_Broughton
Sep 16, 2020Copper Contributor
if ($_.GetType().Name -eq 'DBNull') { $returnValue = 0 } else { $returnValue = $_ }
aka:
$conn.Open()
try {
$reader = $cmd.ExecuteReader()
} catch {
Throw $Error[0]
}
foreach ($read in $reader) {
if ($read[0].GetType().Name -eq 'DBNull') {
$networkCharge = 0
} else {
$networkCharge = $read[0].ToDecimal($null)
}
}
$conn.Close()
return $networkCharge