Invoke-Command wrapper function that passes Cmdlet name and parameters

Hi

I am building an Azure Runbook helper function, that ultimately executes on a Hybrid Runbook Worker.

To generalize my code as much as possible I came up with the idea to have a function dynamically build a scriptblock that defines the Exchange Cmdlet name and parameter.This is what I have so far - the comments are experiments that reveal some of the steps I tried before posting this thread.

function Invoke-BSExchangeCommand
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $CmdletName,

        [Parameter(Mandatory = $false)]
        [hashtable]
        $ArgumentList,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.Management.Automation.Runspaces.PSSession]
        $Session
    )

    $scriptBlock = {
        param ($invokeParams)
        # Get-DistributionGroup @invokeParams
        # $_::$CmdletName.Invoke($invokeParams)
        # $cmdlet = Get-Command -Name $CmdletName
        # & $cmdlet @ArgumentList
        & $CmdletName @argumentList
    }

    $params = @{
        Session      = $Session
        ArgumentList = $ArgumentList
        ScriptBlock  = $scriptBlock
    }

    Invoke-Command @params
}

The error I am getting is a generic one and gives many different (irrelevant) Google search results:

A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section

Thank you!

-Anders

  • Edit: My starting point that I am trying to improve is that this scriptblock with the defined Cmdlet name works:

    $scriptBlock = {
        param ($invokeParams)
        Get-DistributionGroup @invokeParams
    }


    I have found that the "Get-Command" cmdlet is exposed/not restricted on the Exchange endpoint.

    My original code example (that I can't edit) makes more sense with the following code (only the $scriptBlock code is changed though):

    function Invoke-BSExchangeCommand{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $CmdletName,
        [Parameter(Mandatory = $false)]
        [hashtable]
        $ArgumentList,
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [System.Management.Automation.Runspaces.PSSession]
        $Session
    )
    
    $scriptBlock = {
        param ($invokeParams)
        # Get-DistributionGroup @invokeParams
        # $_::$CmdletName.Invoke($invokeParams)
        # $cmd = Get-Command -Name $CmdletName
        & $cmd @invokeParams
    }
    
    $params = @{
        Session      = $Session
        ArgumentList = $ArgumentList
        ScriptBlock  = $scriptBlock
    }
    
    Invoke-Command @params
    }