sql - 处理来自 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)
}
}````
解决方案
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
推荐阅读
- django - 在单个模板中传递多个视图
- python - 在 Windows 下将 Flask 作为子进程运行
- java - 试图在java中计算2个3维坐标之间的距离
- java - 使用地图值处理地图
- android - React Native 应用程序在启动时不断崩溃 [仅在 Android Oreo 上]
- java - 使用spring java复制mongo文档的最佳方法
- scala - IntelliJ 使用具有布尔属性的 scalatags 显示错误
- cmd - 在 cmd 中使用时传递给 cmd 的注册表变量 (%1) 不显示完整路径(不包含带空格的文本)
- visual-studio-code - 树视图中不显示文件夹“libs”(带有“s”)
- node.js - 绑定 Mosca 监听 IP 地址?