这是我第一次尝试从 C# 应用程序执行 PowerShell 脚本。我使用 PowerShell 是因为我需要在远程计算机上执行的 .exe 的输出。我能够使用 WMI 在远程计算机上运行 .exe,但无法获得所需的输出。
无论如何,过去一天左右我一直在研究这个问题,我在网上和这里查找类似的问题,但似乎无法找出问题所在。我正在尝试从远程计算机上的 .NET 4.0 应用程序运行简单的 PowerShell 命令。当我以管理员身份运行 Visual Studio 2013 时,以下代码执行正常:
PowerShell ps = PowerShell.Create();
ps.AddScript(@"Invoke-Command {c:\path\to\file.exe /p} -computername <computerName>");
results = ps.Invoke();
我得到了预期的结果。然而,当我以非管理员身份运行 VS 时,代码似乎执行得很好(没有例外),但我没有得到任何结果。环顾四周后,我添加了模拟,如下所示:
using (var impersonator = new Impersonator("username", "domain", "password"))
{
PowerShell ps = PowerShell.Create();
ps.AddScript(@"Invoke-Command {c:\path\to\file.exe /p} -computername <computerName>");
results = ps.Invoke();
}
但是,ps.Invoke 方法开始抛出 System.Security.SecurityException -“不允许请求的注册表访问”。这是堆栈跟踪:
在 Microsoft.Win32.RegistryKey.OpenSubKey(字符串名称,布尔可写)
在 System.Environment.GetEnvironmentVariable(字符串变量,EnvironmentVariableTarget 目标)
在 System.Management.Automation.ModuleIntrinsics.GetExpandedEnvironmentVariable(字符串名称,EnvironmentVariableTarget 目标)
在 System.Management.Automation.ModuleIntrinsics.SetModulePath()
在 System.Management.Automation.ModuleIntrinsics..ctor(ExecutionContext 上下文)
在 System.Management.Automation.ExecutionContext.InitializeCommon(AutomationEngine 引擎,PSHost 主机接口)
在 System.Management.Automation.ExecutionContext..ctor(AutomationEngine 引擎、PSHost 主机接口、RunspaceConfiguration runspaceConfiguration)
在 System.Management.Automation.AutomationEngine..ctor(PSHost hostInterface、RunspaceConfiguration runspaceConfiguration、InitialSessionState iss)
在 System.Management.Automation.Runspaces.LocalRunspace.DoOpenHelper()
在System.Management.Automation.Runspaces.LocalRunspace.OpenHelper(布尔syncCall)
在System.Management.Automation.Runspaces.RunspaceBase.CoreOpen(布尔syncCall)
在 System.Management.Automation.Runspaces.RunspaceBase.Open()
在 System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndDoWork(运行空间 rsToUse,布尔值 isSync)
在 System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection1 input, PSDataCollection
1个输出,PSInitationSettings设置)
在 System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection1 input, PSDataCollection
1个输出,PSInitationSettings设置)
在 System.Management.Automation.PowerShell.CoreInvoke[TOutput](IEnumerable 输入,PSDataCollection`1 输出,PSInitationSettings 设置)
在 System.Management.Automation.PowerShell.Invoke(IEnumerable 输入,PSInitationSettings 设置)
在 System.Management.Automation.PowerShell.Invoke()
我不确定为什么当我运行的管理员帐户有权访问注册表时,我会收到 SecurityException,不仅在我的计算机上,而且在整个企业的计算机上。我什至不确定哪个注册表出现异常,是我的机器还是远程机器。