【发布时间】:2011-10-10 14:59:54
【问题描述】:
我在 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 }
我得到以下异常:
FileNotFoundException: C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll
调试显示它在RunspaceConfiguration.Create() 失败。不知道为什么。
尽管 DLL 已经在 GAC 中注册,并且在项目本身中被引用。还确认路径和版本是正确的。
参考资料来自:
有人能解释一下吗?
【问题讨论】:
标签: c# powershell impersonation windows-identity