WMI命令可以接收显式凭据作为参数(-Credential
标志),或者在没有提供凭据的情况下在运行脚本的用户的安全上下文中运行。
现在,我的脚本看起来像这样:
if ($Creds) { # if the user provided credentials
Invoke-WMIMethod -Credential $Creds <...something...>
... hundreds more lines of Invoke-WMIMethod code ...
else { # user did not supply credentials, use current security context
Invoke-WMIMethod <...something...>
... same exact hundreds of lines of Invoke-WMIMethod code, without -Credential ....
}
换句话说,唯一的区别是-Credential
标志。有什么方法可以将这个巨大的if-else合并到一个代码块中吗?
答案 0 :(得分:2)
使用splatting动态地将参数传递给cmdlet,如下所示:
$params = @{
'Class' = 'Win32_Foo'
'ComputerName' = 'bar'
...
}
if ($cred) {
$params['Credential'] = $cred
}
Invoke-WmiMethod @params
或者像这样:
$optional_params = @{}
if ($cred) {
$optional_params['Credential'] = $cred
}
Invoke-WmiMethod -Class Win32_Foo -Computer bar ... @optional_params
答案 1 :(得分:0)
看起来当前的安全上下文不能作为凭证对象(ref this question)传递。
幸运的是,invoke-wmimethod使用凭证属性的行为似乎在提供空值时未指定。因此,如果$cred
为空,则invoke-wmimethod -credential $cred <...something...>
的行为应与invoke-wmimethod <...something...>
相同。
现在,更好的方法可能只是保留if else
并删除任何重复的代码。所以,而不是:
if ($Creds) { # if the user provided credentials
Invoke-WMIMethod -Credential $Creds <...something...>
... hundreds more lines of code ...
else { # user did not supply credentials, use current security context
Invoke-WMIMethod <...something...>
... same exact hundreds of lines of code ....
}
你会:
if ($Creds) { # if the user provided credentials
$myresults = Invoke-WMIMethod -Credential $Creds <...something...>
else { # user did not supply credentials, use current security context
$myresults = Invoke-WMIMethod <...something...>
}
... hundreds more lines of code using $myresults...