【问题标题】:Impersonation throws FileNotFoundException with WindowsIdentity in Powershell模拟在 Powershell 中使用 WindowsIdentity 引发 FileNotFoundException
【发布时间】: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


    【解决方案1】:

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

    作为一个快速尝试,尝试为用户(您正在模拟)授予本地管理员权限,以查看它是否可以正常工作。它可以工作,撤销本地管理员权限并根据需要添加文件权限。

    【讨论】:

      猜你喜欢
      • 2020-07-05
      • 1970-01-01
      • 2010-12-08
      • 2012-02-22
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      相关资源
      最近更新 更多