Search code examples
powershellpowershell-remoting

PowerShell Implicit remoting does not use $PSDefaultParameterValues


I am trying to use the $PSDefaultParameterValues to simplify my life. I am running into the problem that when calling cmdlets loaded via implicit remoting, anything I set in $PSDefaultParameterValues is ignored.

A simplified example of what I am currently running into:

$domainController = 'dc1.ptloma.edu' 
Import-Module ActiveDirectory

foreach($command in (Get-Command -Module ActiveDirectory -ParameterName Server))
{
    $PSDefaultParameterValues["$($command.Name):Server"] = $domainController
}        

$exchangeSessionParameters = @{
    Name = "ExchangeInterop"
    ConfigurationName = "Microsoft.Exchange"
    Authentication = "Kerberos"
    Credential = $ExchangeCredential
    ConnectionUri = "http://server.domain.com/PowerShell/"
}

$exchangePsSession = New-PSSession @exchangeSessionParameters
$remoteModule = Import-Session -Session $exchangePsSession

foreach($command in (Get-Command -Module $remoteModule -ParameterName DomainController))
{
    $PSDefaultParameterValues["$($command.Name):DomainController"] = $domainController
}

try
{
    New-AdGroup -Path "OU=Automated,OU=Groups,DC=domain,DC=com" -Name "GroupA"
    Enable-DistributionGroup -Identity "CN=GroupA,OU=Automated,OU=Groups,DC=domain,DC=com" -Alias "GroupA" -PrimarySmtpAddress "GroupA@domain.com"
}
catch
{
    # Breakpoint here
    Write-Host $_.Exception.SerializedRemoteInvocationInfo
    throw
}

I am getting exceptions like:

The operation couldn't be performed because object 'domain.com/Groups/Automated/GroupA' couldn't be found on 'dc2.domain.com'.

Note that it is talking about dc2, not dc1 that I had set to be default on the DomainController property.

Looking deeper into the error record, I see that the exceptions SerializedRemoteInvocationInfo property shows only Alias, PrimarySmtpAddress, and Identity as bound parameters. It does not look like anything is being passed in for DomainController.

I know that I could just refactor and explicitly define the DomainController parameter or use a script-scoped hashtable and splatting, but that would require changing a whole lot, and I am really curious why this behavior is the way it is.


Solution

  • When you use implicit remoting with those Exchange sessions, the Exchange cmdlets (actually they're proxy functions) are passed to the remote session for execution, and then the result passed back to your local session. That hash table doesn't exist in the remote session.