#Sound Setting Double Whammy

9 messages · Page 1 of 1 (latest)

tardy vector
#

Exclusive look at a 2-in-1 query over a function I'm writing

function Set-SystemSound { 
    param (
        [Parameter(Mandatory)]
        [string]$EventKey,
        [Parameter(Mandatory)]
        [string]$SoundPath,
        [string]$Scheme
    )
    $EventKey = "HKCU:\AppEvents\Schemes\Apps\$EventKey"
    Set-ItemProperty -Path "$EventKey\.Current" -Name '(Default)' -Value $SoundPath
    if($Scheme) {
        Set-ItemProperty -Path "$EventKey\$Scheme" -Name '(Default)' -Value $SoundPath
    }
}```The points:
- Will that `if($Scheme)` boolean check work as expected? I want it to return false if the user didn't enter anything for it
- Is the way I'm manipulating `$EventKey` at the start "proper"?
- Does it look alright in general?
glad beacon
#

You can use $PSBoundParameters to test for presence of caller-bound arguments:

function Set-SystemSound {
  param(
    [Parameter(Mandatory = $false)]
    [string]$Scheme = 'default value'
  )

  if ($PSBoundParameters.ContainsKey('Scheme')) {
    # caller supplied an argument to -Scheme
  }
  else {
    # caller invoked command without supplying an argument to -Scheme
  }
}
tardy vector
#

oohh

mint minnow
#

Or sometimes you want blank-or-null values for $Scheme to use the default

if( [string]::IsNullOrWhitespace( $Scheme ) ) {
    $Sceme = 'default value'
}
tardy vector
#

How would the original just if($Scheme) evaluate?

plucky hazel
#

it would work as you thought, $Scheme wouldn't exist

tardy vector
#

oh
alright then lol

glad beacon
#

It would, but it important to note that there's a difference between "caller supplied a falsy argument" and "caller supplied no argument":

function Test-ParamBinding {
  param(
    [AllowNull()]
    [AllowEmptyString()]
    $Scheme = $('default')
  )

  if ($PSBoundParameters.ContainsKey('Scheme')) {
    if ($Scheme) {
      Write-Host "Caller supplied truthy value '$Scheme'"
    }
    else {
      Write-Host "Caller supplied a falsy value"
    }
  }
  else {
    Write-Host "Caller supplied no arguments at all!"
  }
}
PS ~> Test-ParamBinding
Caller supplied no arguments at all!
PS ~> Test-ParamBinding -Scheme $false
Caller supplied a falsy value
PS ~> Test-ParamBinding -Scheme $null
Caller supplied a falsy value
PS ~> Test-ParamBinding -Scheme $true
Caller supplied truthy value 'True'
PS ~> Test-ParamBinding -Scheme 'Hello'
Caller supplied truthy value 'Hello'
plucky hazel
#

yeah good point.

also may be worth noting that $PSBoundParameters does not include default param values.