When checking variables and collections of variables for nullity, comparison operators seem to enumerate collections of size 2 or more:
> if ( @( $null, $null ) -eq $null ) { $True } else { $False }
True
Run Code Online (Sandbox Code Playgroud)
But they do not for collections of size 1:
> if ( @( $null ) -eq $null ) { $True } else { $False }
False
Run Code Online (Sandbox Code Playgroud)
I'm aware that it's best practice to null-compare using the left-hand side ($null -eq @( …
我正在从Powershell脚本中将行插入表中.我遍历PSObjects("属性包")的集合,并为每个插入一行.PSObject上的每个noteProperty对应于表中的一列.其中大多数是字符串,少数是日期,还有一些是布尔.
但是,Powershell中具有$ null值的属性将作为"空"字符串插入,而不是表中的NULL.$ null日期值显示为1900-01-01.除了指定了NOT NULL的几列之外,该表没有任何约束.如果我使用NULL作为值进行手动插入,它可以正常工作.
我可以循环遍历每个对象,寻找$ null属性,然后用字符串NULL替换它,但这似乎是一种黑客而不是"正确"的方式.正如你在下面看到的那样,我已经为booleans做了这个,因为表中相应的列是位.我错误地认为Powershell中的$ null会在SQL中转换为NULL.如果属性在Powershell中的值为$ null,是否有另一种方法可以使它正确地将NULL插入表中?或者,在插入最佳方法之前将$ null转换为字符串"NULL"?
这是我正在使用的代码:
$listOfLunsReport = Import-Clixml e:\powershell\myObjectCollection.xml
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Data Source=SQLSERVER\MYDATABASE;Initial Catalog=my_report;Integrated Security=SSPI;"
$conn.open()
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.connection = $conn
foreach ($lunObject in $listOfLunsReport)
{
if ($lunObject.SnapsConfigured -eq $true)
{
$snapBit = 1
}
else
{
$snapBit = 0
}
if ($lunObject.isDatastore -eq $true)
{
$dsBit = 1
}
else
{
$dsBit = 0
}
$cmd.commandtext = "INSERT INTO listOfLuns (Array,lunNumber,LunUID,CapacityInMB,StorageGroup,`
SnapsConfigured,SnapName,SnapUID,NumberOfSnaps,LatestSnap,VM,PhysicalServer,isDatastore,`
DatastoreName,ReportDate,ArrayModel,ArrayLocation) VALUES ('{0}','{1}','{2}','{3}','{4}',`
'{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}')" -f …Run Code Online (Sandbox Code Playgroud)