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));
2
  • 1
    command.AddParameter("ScriptBlock", ScriptBlock.Create("param(${identity}, ${user}) Get-MailboxPermission -Identity ${identity} -User ${user}")); command.AddParameter("ArgumentList", new object[]{mailbox, user}); Commented Oct 13, 2016 at 8: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. Commented Oct 13, 2016 at 9:42

1 Answer 1

7

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});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.