模拟在Powershell中使用WindowsIdentity抛出FileNotFoundException

我在PowerShell和C#中执行模拟遇到了一些奇怪的错误。 执行以下代码不会显示任何错误。

PSObject result = null; using (PowerShell powershell = PowerShell.Create()) { RunspaceConfiguration config = RunspaceConfiguration.Create(); powershell.Runspace = RunspaceFactory.CreateRunspace(config); powershell.Runspace.Open(); powershell.AddScript(String.Format(CmdletMap[PSVocab.OsBootTime], this.ComputerName)); result = powershell.Invoke().First(); powershell.Runspace.Close(); } return DateTime.Parse(result.ToString()); 

CmdletMap[PSVocab.OsBootTime]的PS脚本只是:

 $info = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computer ; $info.ConvertToDateTime($info.LastBootUpTime) 

上面的C#代码在本地工作正常。 但是,一旦我使用Windows模拟这样的块,就像这样:

 WindowsIdentity ImpersonatedIdentity = new WindowsIdentity(ImpersonateUserName); WindowsImpersonationContext impersonatedContext = ImpersonatedIdentity.Impersonate(); try { PSObject result = null; using (PowerShell powershell = PowerShell.Create()) { RunspaceConfiguration config = RunspaceConfiguration.Create(); powershell.Runspace = RunspaceFactory.CreateRunspace(config); powershell.Runspace.Open(); powershell.AddScript(String.Format(CmdletMap[PSVocab.OsBootTime], this.ComputerName)); result = powershell.Invoke().First(); powershell.Runspace.Close(); } return DateTime.Parse(result.ToString()); } catch (Exception ex) { // do logging here } 

我得到以下exception:

 FileNotFoundException: C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll 

和调试显示它在RunspaceConfiguration.Create()失败。 虽然不知道为什么。

虽然DLL已经在GAC中注册,但在项目本身中被引用。 还确认路径和版本是正确的。

参考文献来自:

  • 模拟和托管PowerShell
  • ASP.NET PowerShell模拟

有人可以对此有所了解吗?

您模拟的用户可能没有足够的权限来访问GAC中必需的PowerShell文件。

作为快速尝试,尝试向用户(您模仿)本地管理员权限,以查看它是否有效。 它可以工作,撤消本地管理员权限并根据需要添加文件权限。