【问题标题】:Set Paramerters in ScriptBlock when Executing Powershell Commands with C#使用 C# 执行 Powershell 命令时在 ScriptBlock 中设置参数
【发布时间】:2016-10-15 00:43:55
【问题描述】:

我正在尝试在 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));

【问题讨论】:

  • command.AddParameter("ScriptBlock", ScriptBlock.Create("param(${identity}, ${user}) Get-MailboxPermission -Identity ${identity} -User ${user}")); command.AddParameter("ArgumentList", new object[]{mailbox, user});
  • 谢谢@PetSerAl 正是我在寻找。您为什么不将此作为答案发布?可以帮助正在寻找相同解决方案的人。

标签: c# powershell scriptblock


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2010-10-06
    • 2013-07-09
    • 2021-11-20
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    相关资源
    最近更新 更多