Set Paramerters in ScriptBlock when Executing Powershell Commands with C#

点点圈 提交于 2019-12-12 03:04:32

问题


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));

回答1:


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});


来源:https://stackoverflow.com/questions/40013482/set-paramerters-in-scriptblock-when-executing-powershell-commands-with-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!