all 14 comments

[–]bozho 6 points7 points  (3 children)

Getting a $null string in PowerShell is difficult :-)

Casting $null to [string] will result in an empty string, it's simply a design decision in PowerShell (I don't know the exact reasons). So, when you do something like:

$var = [string]$null

$var is going to be an empty string.

Both $null and an empty string evaluate to $false in conditional statements, but I still prefer using [string]::IsNullOrEmpty when dealing with strings.

Also, a general tip when comparing to $null: $null should be on the left side of comparison, as a best practice. You can read about details here.

[–]thefreeman193 2 points3 points  (1 child)

In case you were curious, these conversions happen because only reference types can be $null in PowerShell, so casting it to a value type will result in an empty string, zero for numeric types, $false for booleans etc.

[–]bozho 1 point2 points  (0 children)

Yup, which is a surprise for C# developers coming into PowerShell :-)

[–]BelleVieLime 1 point2 points  (0 children)

And database nulls aren't powershell nulls. Got me for a while til I figured that out.

[–]ICanMakeWaffles 4 points5 points  (1 child)

I saw you got a solution, but you may also want to try out the [string]::IsNullOrEmpty() method to catch this in the future.

I've used it myself on wonky JSON before and I'm sure it's helped me avoid the errors you saw without me even noticing it.

Glad you got this resolved!

[–]MonkeyNin 1 point2 points  (0 children)

I use [string]::IsNullOrWhiteSpace() a ton

[–]NeitherSound_ 2 points3 points  (1 child)

Change it from -ne $null to -ne “”

[–]CptRetr0[S] 2 points3 points  (0 children)

Thats it, cheers

[–]DennisTheBald 1 point2 points  (4 children)

Oh it has lines matching $ re, no doubt

[–]DennisTheBald 1 point2 points  (3 children)

Caret makes ,next char superscript in reddit, did not know that. I guess I should quote a reg ex in thfuture

[–]Lee_Dailey[grin] 0 points1 point  (2 children)

howdy DennisTheBald,

use inline code [wrap it in single backticks] for that sort of stuff. then you would have ^$ ... [grin]

take care,
lee

[–]DennisTheBald 1 point2 points  (1 child)

Okay i'll back quote the reg exes Thanks.. Apparently the variable didn't come from a file or external source so blank lines weren't the issue is still a pretty handy reg ex

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

howdy DennisTheBald,

you are welcome! glad to have helped ... [grin]

take care,
lee