Forum Discussion

bvi2006's avatar
bvi2006
Copper Contributor
Apr 19, 2019
Solved

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...
  • Kevin_Morgan's avatar
    Apr 22, 2019

    bvi2006 

     

    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
    }

Resources