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
Code
$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”))
{
$SCID_Volume_Template_Params.Remove($item.Key)
}
}
When I loop through this hashtable all parameters which has value remains but with true and empty value are deleted
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.
ta11ow
October 3, 2019, 7:07am
5
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”
js2010
October 4, 2019, 7:15am
7
Any string evaluates to true when casted to boolean.
$true -eq 'hi there'
True