【发布时间】:2016-07-18 13:04:41
【问题描述】:
编辑:从 PowerShell 7 Preview 2 开始,-not [System.DBNull]::Value 的计算结果为 $true,感谢 Joel Sallow 通过pull request 9794
花更多时间在 PowerShell 中提取 SQL 数据。在比较过程中遇到 [System.DBNull]::Value 问题以及 PowerShell 如何处理此问题。
这是我看到的行为示例以及解决方法
#DBNull values don't evaluate like Null...
if([System.DBNull]::Value){"I would not expect this to display"}
# The text displays.
if([string][System.DBNull]::Value){"This won't display, but is not intuitive"}
# The text does not display.
#DBNull does not let you use certain comparison operators
10 -gt [System.DBNull]::Value
# Could not compare "10" to "". Error: "Cannot convert value "" to type "System.Int32". Error: "Object cannot be cast from DBNull to other types.""
[System.DBNull]::Value -gt 10
# Cannot compare "" because it is not IComparable.
#No real workaround. Must use test for null workaround in conjunction to avoid comparison altogether:
[string][System.DBNull]::Value -and [System.DBNull]::Value -gt 10
#Example scenario with a function that uses Invoke-Sqlcmd2 to pull data
Get-XXXXServer | Where-Object{$_.VCNumCPUs -gt 8}
#Error for every line where VCNumCPU has DBNull value
#workaround
Get-XXXXServer | Where-Object{[string]$_.VCNumCPUs -and $_.VCNumCPUs -gt 8}
我是否遗漏了什么,或者没有“简单”的解决方法可以让经验不足的人按预期使用 PowerShell 比较?
我提交了 a suggestion on Connect 并有一个临时的 workaround from Dave Wyatt 将数据行转换为 psobjects 并将 dbnulls 转换为空值,但是这个 adds a bit of overhead。考虑到 PowerShell 现有的“松散”行为,似乎应该在幕后处理一些事情?
任何提示,或者我现在已经用尽我的选择了吗?
【问题讨论】:
-
我在进行一些编码以使用 sql db 时遇到了这个“特殊情况”。我的解决方案只是检查它 if ($val -ne [DBNull]::Value){} 但这并不能解决比较问题。我赞成您的连接条目。
标签: sql powershell dbnull