Hoo*_*och 4 powershell powershell-2.0 powershell-3.0 powershell-4.0
我有更新WMI中对象的功能。我希望用户能够仅在参数中指定他要更新的值。我该怎么做?
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.
}
Run Code Online (Sandbox Code Playgroud)
我尝试将$nullas作为参数传递,但是它会自动转换为$falsefor bool,0for int和empty stringforstring
您有什么建议?
检查$PSBoundParameters它是否包含带有您的参数名称的键:
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 }
Run Code Online (Sandbox Code Playgroud)
$PSBoundParameters就像哈希表一样,键是参数名称,值是参数的值,但它仅包含绑定的参数,这意味着已明确传递了参数。它不包含用默认值填充的参数(使用传递的参数除外$PSDefaultParameterValues)。
| 归档时间: |
|
| 查看次数: |
473 次 |
| 最近记录: |