使用 C# 执行 Powershell 命令时在 ScriptBlock 中设置参数

Set Paramerters in ScriptBlock when Executing Powershell Commands with C#

我正在尝试在 C# 中执行以下 powershell 命令

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

我尝试使用以下 C# 代码,但无法设置身份和用户参数。

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

当我在创建 ScriptBlock 时对值进行硬编码时,它工作正常。如何动态设置参数。

是否有更好的方法来执行此操作而不是像下面那样连接值。

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

您的 C# 代码的问题在于您将 identityuser 作为参数传递给 Invoke-Command。它或多或少等同于以下 PowerShell 代码:

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

并且由于 Invoke-Command 没有 identityuser 参数,当您 运行 它时它会失败。要将值传递给远程会话,您需要将它们传递给 -ArgumentList 参数。要使用传递的值,您可以在 ScriptBlockparam 块中声明它们,或者您可以使用 $args 自动变量。因此,实际上您需要等效于以下 PowerShell 代码:

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

在 C# 中是这样的:

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