2016-06-09 50 views
2

我試圖通過c#控制檯應用程序遠程使用PowerShell來添加域和發件人到阻止列表。使用Set-SenderFilterConfig添加而不是替換

我試圖使用https://technet.microsoft.com/en-us/library/aa996920(v=exchg.160).aspx的語法來添加而不是替換集合(我已經完成了,很有趣),但我似乎無法做到。

parameter的值是走出正確的,因爲每個語法@ {添加=「[email protected]」}但我得到的錯誤:

Cannot convert value "@{Add="[email protected]"}" to type "Microsoft.Exchange.Data.MultiValuedProperty`1[Microsoft.Exchange.Data.SmtpAddress]". 
Error: "Failed to convert @{Add="[email protected]"} from System.String to Microsoft.Exchange.Data.SmtpAddress. 
Error: Error while converting string '@{Add="[email protected]"}' to result type Microsoft.Exchange.Data.SmtpAddress: "@{Add="[email protected]"}" is not a valid SMTP address" 

這是很明顯,這,它是,不是一個有效的SMTP地址,但 是否有一些標誌我失蹤,迫使'添加'工作?

if (acceptedDomains.Contains(item.Subject.Split('@').Last())) 
{ 
    var parameter = new CommandParameter("BlockedSenders", @"@{Add=""" + item.Subject + @"""}"); 
    command.Parameters.Add(parameter); 
} 
else 
{ 
    var parameter = new CommandParameter("BlockedDomainsAndSubdomains", @"@{Add=""" + item.Subject.Split('@').Last() + @"""}"); 
    command.Parameters.Add(parameter); 
} 
pipeline = runspace.CreatePipeline(); 
pipeline.Commands.Add(command); 
results = pipeline.Invoke(); 

回答

1

@{Add="[email protected]"}是創建Hashtable有效的PowerShell語法,但你是構建在C#中的參數。因此,該命令將通過字符串@{Add="[email protected]"}而無需進一步評估,然後無法將其轉換爲該cmdlet接受的內容。相反,嘗試

var parameter = new CommandParameter(
    "BlockedSenders", 
    new Hashtable { { "Add", item.Subject } } 
); 

對於多個發送者,傳遞一個數組:

var parameter = new CommandParameter(
    "BlockedSenders", 
    new Hashtable { { "Add", new[] { item1.Subject, item2.Subject } } } 
); 

(雖然,考慮到PowerShell的這一靈活性,任何實現IEnumerable應該做的。)

+0

它的工作原理!謝謝。我真的希望有更多的文件。添加多個只是'新的哈希表{{「添加」,item.Subject},{「添加」,item2.Subject}}或'''「添加」,item.Subject,item2.Subject}? – Blinx

相關問題