微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决Powershell Splatting 对象属性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”中的乱码参数,如下所示:

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

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

解决方法

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

    • 但是,有一个 approved 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。