Search code examples
c#powershellscriptblock

Set Paramerters in ScriptBlock when Executing Powershell Commands with C#


I am trying to executing the following powershell command in C#

Invoke-Command -Session $session -ScriptBlock {
  Get-MailboxPermission -Identity ${identity} -User ${user}
}

I tried with following C# code but couldn't set the identity and user parameters.

var command = new PSCommand();
command.AddCommand("Invoke-Command");
command.AddParameter("ScriptBlock", ScriptBlock.Create("Get-MailboxPermission -Identity ${identity} -User ${user}"));
command.AddParameter("identity", mailbox);
command.AddParameter("user", user);

When I hard code the values when creating the ScriptBlock, it's working fine. How can I set the params dynamically.

Is there a better way to do this rather concatenate values as below.

command.AddParameter("ScriptBlock", ScriptBlock.Create("Get-MailboxPermission -Identity " + mailbox + " -User " + user));

Solution

  • The problem with your C# code is that you pass identity and user as parameters for Invoke-Command. It more or less equivalent to the following PowerShell code:

    Invoke-Command -ScriptBlock {
        Get-MailboxPermission -Identity ${identity} -User ${user}
    } -identity $mailbox -user $user
    

    And since Invoke-Command does not have identity and user parameters, it will fail, when you run it. To pass values to the remote session, you need to pass them to -ArgumentList parameter. To use passed values, you can declare them in ScriptBlock's param block, or you can use $args automatic variable. So, actually you need equivalent of following PowerShell code:

    Invoke-Command -ScriptBlock {
        param(${identity}, ${user})
        Get-MailboxPermission -Identity ${identity} -User ${user}
    } -ArgumentList $mailbox, $user
    

    In C# it would be like this:

    var command = new PSCommand();
    command.AddCommand("Invoke-Command");
    command.AddParameter("ScriptBlock", ScriptBlock.Create(@"
        param(${identity}, ${user})
        Get-MailboxPermission -Identity ${identity} -User ${user}
    "));
    command.AddParameter("ArgumentList", new object[]{mailbox, user});