![](/img/trans.png)
[英]Error while executing Exchange powershell commands from C# program
[英]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#代碼的問題是您將identity
和user
作為Invoke-Command
參數傳遞。 它或多或少等效於以下PowerShell代碼:
Invoke-Command -ScriptBlock {
Get-MailboxPermission -Identity ${identity} -User ${user}
} -identity $mailbox -user $user
並且由於Invoke-Command
沒有identity
和user
參數,因此在您運行它時將失敗。 要將值傳遞到遠程會話,您需要將它們傳遞到-ArgumentList
參數。 要使用傳遞的值,可以在ScriptBlock
的param
塊中聲明它們,也可以使用$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});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.