Не удается запустить командлет Disable-Mailbox Powershell на языке C#



Я пытаюсь воспроизвести следующий рабочий фрагмент Powershell в C#.
Мы подключаемся к экземпляру Exchange2010.



$ExURI = "http://ExchangeUrl/PowerShell/"

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ExURI -Authentication Kerberos
$userName = "patatem"

Import-PSSession $Session -AllowClobber -EA SilentlyContinue | Out-Null

Get-Recipient $userName

Disable-Mailbox -Identity $userName -Confirm:$False
#enable-mailbox -identity $userName -Alias $userName -database "AnExchangeDatabase"

remove-PSSession $Session


Я следовал шагам, упомянутым здесь : https://blogs.msdn.microsoft.com/wushuai/2016/09/18/access-exchange-online-by-powershell-in-c/



В следующем блоке кода я получаю положительные результаты при вызове Get-Mailbox, Get-Recipient.



При вызове Disable-Mailbox я получаю следующую ошибку




Термин "отключить почтовый ящик" не распознается как имя командлета,
функция, файл сценария или действующая программа. Проверьте правильность написания
имя, или если путь был включен, убедитесь, что путь правильный и
попробовать еще раз.




Почему он распознает Get-Mailbox, но не Disable-Mailbox?



(я попытался добавить еще один фрагмент кода, чтобы сделать раздел сеанса импорта Powershell, но это ничего не изменило.)



   public void EnableCommand(string identity, string database)
{
if (!string.IsNullOrWhiteSpace(identity))
{
using (var runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
var powershell = PowerShell.Create();

var command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", new Uri(Constants.DefaultOutLookUrl));
command.AddParameter("Authentication", "Kerberos");
powershell.Commands = command;

powershell.Runspace = runspace;
var result = powershell.Invoke();
if (powershell.Streams.Error.Count > 0 || result.Count != 1)
{
throw new Exception("Fail to establish the connection");
}

powershell = PowerShell.Create();
command = new PSCommand();
command.AddCommand("Invoke-Command");
command.AddParameter("ScriptBlock", System.Management.Automation.ScriptBlock.Create("Get-Mailbox"));
command.AddParameter("Session", result[0]);
powershell.Commands = command;
powershell.Runspace = runspace;
var mailBoxes = powershell.Invoke();

// This will give me a result
var returnValue = new StringBuilder();
foreach (var item in mailBoxes)
{
returnValue.AppendLine(item.ToString());
}


// check the other output streams (for example, the error stream)
if (powershell.Streams.Error.Count > 0)
{
returnValue.AppendLine($"{powershell.Streams.Error.Count} errors: ");
foreach (var err in powershell.Streams.Error)
{
returnValue.AppendLine($"{err.ToString()}");
}
}

// This will also work
powershell = PowerShell.Create();
command = new PSCommand();
command.AddCommand("Invoke-Command");
command.AddParameter("ScriptBlock", System.Management.Automation.ScriptBlock.Create("Get-Recipient SomeEmail"));
command.AddParameter("Session", result[0]);
powershell.Commands = command;
powershell.Runspace = runspace;
var mailBoxes2 = powershell.Invoke();

foreach (var item in mailBoxes2)
{
returnValue.AppendLine(item.ToString());
}


if (powershell.Streams.Error.Count > 0)
{
returnValue.AppendLine($"{powershell.Streams.Error.Count} errors: ");
foreach (var err in powershell.Streams.Error)
{
returnValue.AppendLine($"{err.ToString()}");
}
}

// this will give me The term 'Disable-Mailbox' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

powershell = PowerShell.Create();
command = new PSCommand();
command.AddCommand("Invoke-Command");
command.AddParameter("ScriptBlock", System.Management.Automation.ScriptBlock.Create("Disable-Mailbox -Identity patatem -Confirm:$False"));
command.AddParameter("Session", result[0]);
powershell.Commands = command;
powershell.Runspace = runspace;
var mailBoxes3 = powershell.Invoke();

foreach (var item in mailBoxes3)
{
returnValue.AppendLine(item.ToString());
}

// check the other output streams (for example, the error stream)
if (powershell.Streams.Error.Count > 0)
{
returnValue.AppendLine($"{powershell.Streams.Error.Count} errors: ");
foreach (var err in powershell.Streams.Error)
{
returnValue.AppendLine($"{err.ToString()}");
}
}

Console.WriteLine(returnValue);
}
}
657   1  

1 ответ:

Термин "Disable-Mailbox" не распознается как имя командлета, функция, файл сценария или действующая программа. Проверьте правильность написания имя, или если путь был включен, убедитесь, что путь правильный и попробовать еще раз.

Если у пользователя, пытающегося выполнить командлет Disable-Mailbox, недостаточно прав для отключения почтового ящика ( RBAC), выдается это неспецифическое сообщение об ошибке.

Запустите код с достаточными разрешениями, и он должен работа.

Статья TechNet: понимание управления доступом на основе ролей

Comments

    Ничего не найдено.