I am encountering a somewhat weird error with performing impersonation in PowerShell and C#. Executing the folowing code does not show any errors.
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());
where the PS script for CmdletMap[PSVocab.OsBootTime]
is simply:
$info = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computer
; $info.ConvertToDateTime($info.LastBootUpTime)
The above C# code works fine locally. However, once I had this same block with Windows impersonation like so:
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 }
I get the following exception:
FileNotFoundException: C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll
and debugging shows that it fails at RunspaceConfiguration.Create()
. Not sure why though.
The DLL though is already registered in the GAC though as well as being referenced in the project itself. Also confirmed that the paths and version are correct.
References taken from:
Can someone give an insight to this?
The user you are impersonating into may not have enough permissions to access the necessary powershell files in the GAC.
As a quick shot try to give the user (you are impersonating into) local admin rights to see if it works then. It this works, revoke local admin rights and add file permissions as needed.