2016-03-23 20 views
1

目前,如果我手动连接到我的管理员Windows帐户并启动此代码,它可以正常工作,但如果有人没有管理员凭据,“启用邮箱无法工作,因为它无法工作发现数据库。我做了一些研究,这是因为他不具备权限。有什么办法来运行该代码为其他用户提供的用户名和密码?如何以其他用户身份启动PowerShell

PowerShell powershell = PowerShell.Create(); 
      PSSnapInException ex; 
      powershell.Runspace.RunspaceConfiguration.AddPSSnapIn(
       "Microsoft.Exchange.Management.PowerShell.Admin", out ex); 
      if (ex != null) 
       throw ex; 
      powershell.AddScript(". $env:ExchangeInstallPath\\bin\\RemoteExchange.ps1"); 
      powershell.AddScript("Connect-ExchangeServer -auto"); 
      powershell.Invoke(); 
      powershell.Streams.ClearStreams(); 
      powershell.Commands.Clear(); 
      powershell.AddCommand("Enable-Mailbox"); 
      powershell.AddParameter("Identity", "username"); 
      powershell.AddParameter("Database", @"databasePath"); 
      var result = powershell.Invoke(); 

回答

0
$user = 'xxxxx' 
$PlainPassword = 'xxxxx' 
$SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force 
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $User, $SecurePassword 

您可以使用这样的代码创建用户凭证变量,可用于从用户上下文启动某​​些东西 您也可以提示用户\ pa带有Read-Host的ssword。

+0

这是直接在PowerShell的权利?你知道如何把这段代码放在C# – spnshguy

+0

是的,那是直接在PowerShell中。遗憾的是,我对c#部分一无所知。但是,如果你的代码没有powershell命令(我不确定),你可以尝试像powershell.AddCommand(xxxx)? – 4c74356b41

+0

请不要使用Read-Host来索取凭证。使用'Get-Credentials'。 –

相关问题