模拟抛出FileNotFoundException与WindowsIdentity在Powershell

本文关键字:WindowsIdentity Powershell FileNotFoundException 模拟 | 更新日期: 2023-09-27 18:03:09

我在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中注册,但在项目本身中也被引用。同时确认路径和版本是否正确。

引用自:

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

有谁能给点启发吗?

模拟抛出FileNotFoundException与WindowsIdentity在Powershell

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

作为一个快速尝试给用户(您正在冒充)本地管理员权限,看看它是否工作。如果有效,撤销本地管理员权限并根据需要添加文件权限。