Powershell and SQL parameters. If empty string, pass DBNull Powershell and SQL parameters. If empty string, pass DBNull powershell powershell

Powershell and SQL parameters. If empty string, pass DBNull


In PowerShell, you can treat null/empty strings as a boolean.

$x = $nullif ($x) { 'this wont print' }$x = ""if ($x) { 'this wont print' }$x = "blah"if ($x) { 'this will' }

So.... having said that you can do:

$Parameter.Value = $(if ($x) { $x } else { [DBNull]::Value })

But I'd much rather wrap this up in a function like:

function CatchNull([String]$x) {   if ($x) { $x } else { [DBNull]::Value }}


I don't know about powershell, but in C# I would do something like this:

if ([string]::IsNullOrEmpty($objUser.Telephone)){ $objDbCmd.Parameters["@telephone"].Value = [DBNull]::Value;}else{ $objDbCmd.Parameters["@telephone"].Value = $objUser.Telephone;}


Always append +"" at the end of db values...

$command.Parameters["@EmployeeType"].Value= $ADResult.EmployeeType + ""