1

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));
Yasitha
  • 2,233
  • 4
  • 24
  • 36
  • 1
    `command.AddParameter("ScriptBlock", ScriptBlock.Create("param(${identity}, ${user}) Get-MailboxPermission -Identity ${identity} -User ${user}")); command.AddParameter("ArgumentList", new object[]{mailbox, user});` – user4003407 Oct 13 '16 at 08:02
  • Thanks @PetSerAl Exactly I was looking for. Why don't you post this as an answer? May help who is looking for a same solution. – Yasitha Oct 13 '16 at 09:42

1 Answers1

6

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});
user4003407
  • 21,204
  • 4
  • 50
  • 60