1

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

$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
}
4

1 回答 1

3
  • 从 PowerShell 7.1 开始,您只能将一个变量作为一个整体,而不是一个返回属性值的表达式。

    • 但是,有一个批准的 RFC允许基于表达式的 splatting;但是,它的实施没有具体的时间框架;欢迎社区成员贡献。
  • 用于喷溅的变量可能仅包含哈希表(包含参数名称和参数对,如您的问题)数组(包含位置参数),而不是[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

于 2020-12-22T15:32:47.047 回答