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

Yas*_*tha 1 c# powershell scriptblock

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

Invoke-Command -Session $session -ScriptBlock {
  Get-MailboxPermission -Identity ${identity} -User ${user}
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下 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);
Run Code Online (Sandbox Code Playgroud)

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

有没有更好的方法来做到这一点,而不是像下面那样连接值。

command.AddParameter("ScriptBlock", ScriptBlock.Create("Get-MailboxPermission -Identity " + mailbox + " -User " + user));
Run Code Online (Sandbox Code Playgroud)

use*_*407 6

您的 C# 代码的问题在于您将identityuser作为Invoke-Command. 它或多或少相当于以下 PowerShell 代码:

Invoke-Command -ScriptBlock {
    Get-MailboxPermission -Identity ${identity} -User ${user}
} -identity $mailbox -user $user
Run Code Online (Sandbox Code Playgroud)

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

Invoke-Command -ScriptBlock {
    param(${identity}, ${user})
    Get-MailboxPermission -Identity ${identity} -User ${user}
} -ArgumentList $mailbox, $user
Run Code Online (Sandbox Code Playgroud)

在 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});
Run Code Online (Sandbox Code Playgroud)