Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to differentiate not set parameter from $false, 0, empty string?

I have function that updates object in WMI. I want user to be able to specify in parameters only values that he wants to update. How can I do it?

function UpdateObject ([bool] $b1, [bool] $b2, [int] $n1, [string] $s1)
{
    $myObject = GetObjectFromWmi #(...)
    #(...)

    #This is bad. As it overrides all the properties.
    $myObject.b1 = $b1
    $myObject.b2 = $b2
    $myObject.n1 = $n1
    $myObject.s1 = $s1

    #This is what I was thinking but don't kwow how to do
    if(IsSet($b1)) { $myObject.b1 = $b1 }
    if(IsSet($b2)) { $myObject.b2 = $b2 }
    if(IsSet($n1)) { $myObject.n1 = $n1 }
    if(IsSet($s1)) { $myObject.s1 = $s1 }

    #(...) Store myObject in WMI.
}

I tried passing $null as as parameter but it get's automaticly converted to $false for bool, 0 for int and empty string for string

What are your suggestions?

like image 649
Hooch Avatar asked Dec 19 '22 05:12

Hooch


1 Answers

Check $PSBoundParameters to see if it contains a key with the name of your parameter:

if($PSBoundParameters.ContainsKey('b1')) { $myObject.b1 = $b1 }
if($PSBoundParameters.ContainsKey('b2')) { $myObject.b2 = $b2 }
if($PSBoundParameters.ContainsKey('n1')) { $myObject.n1 = $n1 }
if($PSBoundParameters.ContainsKey('s1')) { $myObject.s1 = $s1 }

$PSBoundParameters acts like a hashtable, where the keys are the parameter names, and the values are the parameters' values, but it only contains bound parameters, which means parameters that are explicitly passed. It does not contain parameters filled in with a default value (except for those passed with $PSDefaultParameterValues).

like image 52
briantist Avatar answered Jan 13 '23 15:01

briantist