Skip to content

Instantly share code, notes, and snippets.

@Windos
Last active March 5, 2020 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Windos/d1f9d8622a0b12a44396ce90e9b489b9 to your computer and use it in GitHub Desktop.
Save Windos/d1f9d8622a0b12a44396ce90e9b489b9 to your computer and use it in GitHub Desktop.
Null operators demo for RTPSUG 2020-03-04
break
#region Null Coalescing Operator (??)
# Returns value on the left if it's not null
# Otherwise the right had side is evaluated and returned
$Left ?? $Right
#region The Old Way
$TheThing = $null
if ($null -eq $TheThing) {
"Nope, it wasn't there!"
} else {
$TheThing
}
#endregion
#region The New Way
$TheThing = $null
(!$TheThing) ?? "Nope, it wasn't there!"
#endregion
#region And with a value assigned?
$TheThing = 'This is a value'
$TheThing ?? "Nope, it wasn't there!"
#endregion
#region Both Sides Can Be Evaluated
(Get-ChildItem -Path .\ -EA SilentlyContinue) ?? (Get-Date | Select-Object *)
#endregion
#endregion
#region Null Assignment Operator (??=)
# Assignes the value on the right, only if the left is null
#region The Old Way
$TheThing = $null
if ($null -eq $TheThing) {
$TheThing = "Fallback Value"
}
$TheThing
#endregion
#region The New Way
$TheThing = $null
$TheThing ??= "Fallback Value"
$TheThing
#endregion
#region Existing Value
$TheThing = 'Existing Value'
$TheThing ??= "Fallback Value"
$TheThing
#endregion
#endregion
#region Experimental: Null Conditional Access (?. and ?[])
# Access members and index items on potentially null variables without errors
Get-ExperimentalFeature -Name PSNullConditionalOperators
Enable-ExperimentalFeature -Name PSNullConditionalOperators
#region Methods
$BitsService.Stop()
${BitsService}?.Stop()
#endregion
#region Index
$Users[0]
${Users}?[0]
#endregion
#region Combined
${Users}?[0]?.SamAccountName ?? 'Nothing'
#endregion
#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment