Powershell Splatting 对象属性 (Typeof System.Collections.Hashtable)

Powershell Splatting Object Attribute (Typeof System.Collections.Hashtable)

举个例子让我更清楚我想做什么

$AzLogin = @{

 Subscription = [string] 'SubscriptionID';
 Tenant = [string] 'tenantID';
 Credential = [System.Management.Automation.PSCredential] $credsServicePrincipal;
 ServicePrincipal = $true;

}

try{
 Connect-Azaccount @$AzLogin -errorAction Stop
}catch{
 Write-Host "Error: $($_.exception)" -foregroundcolor red
}

这可以正常工作。

我想做的是传递存储在对象 'CSObject' 的 属性 'CommonArgs' 中的 splatted 参数,像这样:

$CSObject =@ {
 [PScustomObject]@{CommonArgs=$AzLogin;}
}

try{
 Connect-Azaccount @CSObject.commonArgs -errorAction Stop
}catch{
 Write-Host "Error: $($_.exception)" -foregroundcolor red
}
  • 你只能把一个变量作为一个整体,而不是returns一个表达式属性 值 - 从 PowerShell 7.1 开始

    • 但是,approved RFC 允许基于表达式的展开;但是,它的实施没有具体的时间框架;欢迎社区成员贡献。
  • 用于展开的变量只能包含一个 哈希表(包含参数名称和参数对,如您的问题) 数组 (包含位置参数),而不是 [pscustomobject] - 请参阅 about_Splatting

像下面这样的东西应该可以工作:

# Note: It is $CSObject as a whole that is a [pscustomobject] instance,
#       whereas the value of its .CommonArgs property is assumed to be
#       a *hashtable* (the one to use for splatting).
$CSObject = [pscustomobject] @{
  CommonArgs = $AzLogin  # assumes that $AzLogin is a *hashtable*
}

# Need a separate variable containing just the hashtable
# in order to be able to use it for splatting.
$varForSplatting = $CSObject.CommonArgs

Connect-Azaccount @varForSplatting -errorAction Stop