07-21-2023, 08:42 PM
I've just started doing some PowerShell scripting, and I'm running into a problem testing variables for a value. I try to run everything with all warnings enabled, especially while I'm learning, in order to catch dumb mistakes. So, I'm using CTPV3 and setting strict mode on with "set-strictmode -version latest". But I'm running into a road block with checking incoming variables for a value. These variables may or may not already be set.
# all FAIL if $var is undefined under "Set-StrictMode -version latest"
if ( !$var ) { $var = "new-value"; }
if ( $var -eq $null ) { $var = "new-value"; }
I can't find a way to test if a variable has a value that doesn't cause warnings when the variable is missing unless I turn off strict mode. And I don't want to turn strict mode on and off all over the place just to test the variables. I'm sure I'd forget to turn it back on somewhere and it looks terribly cluttered. That can't be right. What am I missing?
# all FAIL if $var is undefined under "Set-StrictMode -version latest"
if ( !$var ) { $var = "new-value"; }
if ( $var -eq $null ) { $var = "new-value"; }
I can't find a way to test if a variable has a value that doesn't cause warnings when the variable is missing unless I turn off strict mode. And I don't want to turn strict mode on and off all over the place just to test the variables. I'm sure I'd forget to turn it back on somewhere and it looks terribly cluttered. That can't be right. What am I missing?