首页 > 解决方案 > 处理来自 sql 表的 PSCustomObject 中的空值..无法转换对象

问题描述

在从 SQL 中提取数据时,该行中的某些列为空。我收到一条异常消息:

使用“1”参数调用“GetString”的异常:“无法将“System.DBNull”类型的对象转换为“System.String”类型。”

我该如何处理?它似乎基本上只是移动到下一行,但我需要所有行和所有列。如果该列为空,我可以,但我想我确实需要将其设置为空字符串。此数据将用于为 AD 中的用户设置详细信息。当我使用该Set-ADUser命令时,即使它为空,我也需要能够使用该变量。我不希望 PowerShell 不执行Set-ADUser命令,因为特定变量为空。它最失败的一个是 supr_username。

我花了很长时间才从 Oracle sql 表中获取输出,以便将其用于Set-ADUser. 我还没有找到任何东西来做我想做的事情。

 [pscustomobject]@{
 Identity = $_.GetString(2)
 Title = $_.GetString(3)
 Department = $_.GetString(4)
 MSC = $_.GetString(5)
 Office_Location = $_.GetString(6)
 Office_Phone = $_.GetString(7)
 Supr_username = $_.GetString(10)
 }
 }````


标签: sqlpowershell

解决方案


You can initialize your custom object properties with values of empty string (""). Then you can test if the column index (ordinal) contains a DBNull and convert to string if it is not DBNULL.

$obj = [pscustomobject][ordered]@{Identity = ""
    Title = ""
    Department = ""
    MSC = ""
    Office_Location = ""
    Office_Phone = ""
    Supr_username = ""
    }

$obj.Identity = if (!$_.isDbNull(2)) { $_.GetString(2) }
$obj.Title = if (!$_.isDbNull(3)) { $_.GetString(3) }
$obj.Department = if (!$_.isDbNull(4)) { $_.GetString(4) }
$obj.MSC = if (!$_.isDbNull(5)) { $_.GetString(5) }
$obj.Office_Location = if (!$_.isDbNull(6)) { $_.GetString(6) }
$obj.Office_Phone = if (!$_.isDbNull(7)) { $_.GetString(7) }
$obj.Supr_username = if (!$_.isDbNull(10)) { $_.GetString(10) }

$obj

推荐阅读