Powershell and SQL parameters. If empty string, pass DBNull

Question:

I got this parameter:

Where the string $objUser.Telephone can be empty. If it’s empty, how can I convert it to [DBNull]::Value?

I tried:

But that gives me the error:

Exception calling “ExecuteNonQuery” with “0” argument(s): “Failed to convert parameter value from a ResultPropertyValueCollection to a String.”

And if I convert it to a string, it inserts an empty string "", and not DBNull.

How can this be accomplished?

Thanks.

Answer:

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

So…. having said that you can do:

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

Source:

Powershell and SQL parameters. If empty string, pass DBNull by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply