Impersonation throws a FileNotFoundException with WindowsIdentity in Powershell

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) { // 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.

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?

+6
source share
1 answer

The user you impersonate may not have sufficient permissions to access the required powershell files in the GAC.

As a quick snapshot, try to give the user (you impersonate) the rights of the local administrator to find out if he works then. This works, revokes local administrator privileges and adds file permissions as needed.

0
source

Source: https://habr.com/ru/post/893316/


All Articles