powershellhashtablecustom-objectpscustomobjectparameter-splatting

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


Going to give an example to make it clearer what I want to do

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

This works correctly.

The one I want to do is pass splatted arguments stored in property 'CommonArgs' of object 'CSObject', something like this:

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

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

Solution

  • Something like the following should work:

    # 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