(C#)创建远程Powershell会话时出现“访问被拒绝”错误

时间:2018-10-01 20:57:57

标签: c# powershell iis permissions exchange-server

我对C#和powershell有问题。我有一台运行在服务器上的ASP.net WebApi,我需要它来与Microsoft Exchange打开远程powershell会话,以从会议室邮箱中获取一些数据。我使用以下代码进行连接:

PowerShell instance = PowershellHelper.Instance;

instance.AddScript("$passUnsafe = \"" + Password + "\";" +
"$pass = $passUnsafe | convertto-securestring -AsPlainText -Force;" +
"$UserCredential = new-object -typename System.Management.Automation.PSCredential -argumentlist \"" + Username + "\",$pass;" +
"if (!(Get-PSSession | Where { $_.ConfigurationName -eq \"Microsoft.Exchange\" })) { $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection; }" +
"else { $Session = (Get-PSSession | Where { $_.ConfigurationName -eq \"Microsoft.Exchange\" })[0]; }" +
"Import-PSSession $Session -DisableNameChecking;");

PowershellHelper.Instance.Streams.Error.Clear();
instance.Invoke();

这在我的本地计算机上正常工作,但在远程服务器上却无法正常工作。尝试执行“ New-PSSession”时,脚本崩溃,并显示以下错误:

[outlook.office365.com] Connecting to remote server outlook.office365.com failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.

经过研究,我发现发生这种情况是因为不允许非管理员用户执行远程会话命令。如果我将IIS应用程序池用户添加到Administrators组,则可以正常工作,但是如果可能的话,我希望避免这种情况。 有人说您可以将用户添加到内置的“远程管理用户”组中,但是它不适用于我。我什至尝试直接更改用户权限,以授予其完全访问权限,但是它也不起作用。仅当我将其添加到Administrators组时,它才有效。似乎还有其他障碍阻止执行,或者IIS忽略了用户组。凭据很好。有人知道没有管理员权限还有其他方法可以执行远程PowerShell命令吗?

2 个答案:

答案 0 :(得分:0)

根据Simon Li的评论,您可以使用以下PowerShell脚本为您的帐户授予远程PowerShell执行权限:

Set-User "XXXXX" -RemotePowerShellEnabled $true

https://docs.microsoft.com/en-us/powershell/exchange/exchange-server/control-remote-powershell-access-to-exchange-servers?view=exchange-ps

答案 1 :(得分:0)

上周,我在将基于Web的用户配置应用程序从其Exchange 2010目标迁移到Exchange 2016时遇到了此问题。最终,问题是应用程序服务器上的权限问题。 IIS APPPOOL\DefaultAppPool身份正在尝试向HKU:\.DEFAULT\Software\Microsoft\CurrentVersion\WSMAN\Client\ConnectionCookies写一个值。

我授予了ConnectionCookies键的IIS APPPOOL\DefaultAppPool身份完全控制权限,该应用程序能够成功调用New-PSSession

我在一个名为Mike's Ramblings here(Blogspot)的博客中发现了此解决方案:http://codermike.blogspot.com/2016/06/new-pssession-access-denied.html

Mike发现了Process Monitor的问题。通过运行Process Monitor,重现问题并搜索具有ACCESS DENIED结果的事件,我能够做到这一点。双击事件并单击“处理”选项卡将显示正在调用的用户。

当我的应用程序使用带有服务帐户标识的专用应用程序池时,我仍然不明白为什么IIS APPPOOL\DefaultAppPool标识试图创建此值。

用Mark Russinovich的话说:“如有疑问,请使用Process Monitor。”