REmoving keys with empty value deletes key with $TRUE as value

I have a piece of code where I create a hash with all parameters which run with a command. BEfore doing so I check for empty parameters and delete those. This also deletes where parameter has a True value while it leaves False. I am unable to understand why so


$Volume_Template_Params1 = @{

EnableDeduplication = $deduplication;
EnableEncryption = $encryption;
EnableIOPSLimit = $enable_IOLimit;
EnableDataTransferLimit = $Senable_DataLimit;
EnableCompression = $Compress;


$Volume_Template_Params = $Volume_Template_Params1.Clone()
foreach ($item in $Volume_Template_Params1.GetEnumerator()) {
if ([string]::IsNullOrWhiteSpace($item.Value) -or ($item.Value -ieq “null”))

When I loop through this hashtable all parameters which has value remains but with true and empty value are deleted

You need to compare with $null object in your if statement not with "null" string object.
if ([string]::IsNullOrWhiteSpace($item.Value) -or ($item.Value -ieq $null))
Thank you.

It works, thank you, but why “null” would remove True. Suppose if it is a keyword how should it be handled

Because null as a string is different from $null as a null. In fact, you don’t need the 2nd condition…

if ([string]::IsNullOrWhiteSpace($item.Value)) would be fine.

Thank you.

If you want it to remove $false values as well, that condition won’t work.

In fact, I’m pretty sure the original if statement is making some assumptions that won’t pan out.

# original: if ([string]::IsNullOrWhiteSpace($item.Value) -or ($item.Value -ieq "null"))

# stated condition from OP: 
# - remove parameters with $null value
# - remove parameters with $false value

# I'd recommend:
if (-not $item.Value -or [string]::IsNullOrWhitespace($item.Value)) { }

For now I have opted if ([string]::IsNullOrWhiteSpace($item.Value)) but still not clear what null has to do with “true”

Any string evaluates to true when casted to boolean.

$true -eq 'hi there'