无论是否提供凭据,我都可以使用相同的 WMI 命令吗?

Can I use the same WMI command whether credentials are provided or not?

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 合并到一个代码块中吗?

当前的安全上下文似乎无法作为凭据对象传入 (ref this question)。

幸运的是,invoke-wmimethod 对 credential 属性的使用在提供 null 值时表现得好像没有指定一样。因此,如果 $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...

使用 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

技术应该already be available in PowerShell v2.0.