I encounter a somewhat strange error with performing impersonation in PowerShell and C #. The following code does not contain 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] simple:
$info = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computer ; $info.ConvertToDateTime($info.LastBootUpTime)
The above C # code works fine locally. However, as soon as I had the same block with Windows impersonation, for example:
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) {
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.
DLL, although it is already registered in the GAC, although it is mentioned in the project itself. It is also confirmed that the paths and version are correct.
Links taken from:
Can someone make this clear?
source share