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

标签 c# powershell scriptblock

我正在尝试在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参数,因此在运行它时将失败。要将值传递给远程 session ,您需要将它们传递给-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});

关于c# - 使用C#执行Powershell命令时在ScriptBlock中设置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40013482/

相关文章:

使用 Set-Item 和 GetNewClosure 创建 Powershell 函数

c# - 看似循环依赖导致 CaSTLe Windsor 出现问题

c# - Microsoft.Office.Interop.Word 中的更改事件

c# - 如何在 Irony.NET 中允许重复

powershell - 如果包含 “*”的代理创建绕过列表失败

html - 呈现 HTML 片段而不将其保存到文件中

powershell - Powershell在ScriptBlock中传递参数

c# - 是否可以调用 win form 而不是 windows 登录窗口?

powershell - 使用 powershell 将文本文件中的特定行复制到单独的文件

variables - 脚本 block 中的 Powershell 扩展变量