code_junkie

PowerShell - How do I test for a variable value with “Set-StrictMode -version latest”

Nov 14th, 2011
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. # all FAIL if $var is undefined under "Set-StrictMode -version latest"
  2. if ( !$var ) { $var = "new-value"; }
  3. if ( $var -eq $null ) { $var = "new-value"; }
  4.  
  5. if (!(test-path variable:var)) {$var = $null} # test for EXISTENCE & create
  6. if ( !$var ) { $var = "new-value"; } # test the VALUE
  7.  
  8. $var = & { Set-StrictMode -off; switch( $var ) { $null { "new-value" } default { $var } }}
  9.  
  10. & { Set-StrictMode -off; if (!$var) { set-variable -scope 1 var "new-value" }}
  11.  
  12. function set-Variable-IfMissingOrNull ($name, $value)
  13. {
  14. $isMissingOrNull = !(test-path ('variable:'+$name)) -or ((get-variable $name -value) -eq $null)
  15. if ($isMissingOrNull) { set-variable -scope 1 $name $value }
  16. }
  17. set-alias ?? set-Variable-IfMissingOrNull
  18. #...
  19. ## in use, must not have a leading $ or the shell attempts to read the possibly non-existant $var
  20. set-VarIfMissingOrNull var "new-value"
  21. ?? varX 1
  22.  
  23. function test-variable
  24. {# return $false if variable:$name is missing or $null
  25. param( [string]$name )
  26. $isMissingOrNull = (!(test-path ('variable:'+$name)) -or ((get-variable -name $name -value) -eq $null))
  27. return !$isMissingOrNull
  28. }
  29. set-alias ?-var test-variable
  30. if (!(?-var var)) {$var = "default-value"}
  31.  
  32. Set-Variable
  33.  
  34. -- ReadOnly: Cannot be deleted or changed without the Force parameter.
  35. -- Constant: Cannot be deleted or changed. Constant is valid only when
  36. creating a new variable. You cannot set the Constant option on an
  37. existing variable.
Add Comment
Please, Sign In to add comment