1

I have a module (Impersonation) written by Joel Bennett that allows me to change the active credentials so that I can access file shares on a remote machine, for example. It works within Windows PowerShell 5.1. But, it does not work in Powershell 7.3.4 (or apparently anything 6+). It gives error

Cannot find type [System.Collections.Generic.Stack[System.Security.Principal.WindowsImpersonationContext]]: verify that the assembly containing this type is loaded.

So, neither of those System assemblies/types exists as far as Powershell is concerned. Two years ago Jordan Borean said that one could call a version 5.1 session with something like

$s = New-PSSession -UseWindowsPowerShell
Invoke-Command $s { My-LegacyCmdlet ... }
Remove-PSSession $s

And also, "The behaviour of Add-Type and the referenced assemblies that it implicitly loads has changed between PowerShell 5 and 6+. It is a lot more conservative in what it loads alongside your code and the System.Security.Principal ones are typically one of those. This is an example of this in action and what needs to be done to fix it up https://gist.github.com/jborean93/a7c181b1ea0a4c0c8b815af9a8cbe508#file-start-processex-ps1-L8-L1735." I followed that link, but I think that is beyond me without some explanation. So, should I just try to wrap all of my old scripts in that New-PsSession or is there now a better way to fix the module or make the assemblies available or something?

Roman
  • 344
  • 1
  • 6
  • 19
  • 2
    Why not use Jordan's [`Invoke-WithImpersonation`](https://gist.github.com/jborean93/3c148df03545023c671ddefb2d2b5ffc#file-invoke-withimpersonation-ps1) :) ? It is compatible with 7+ as far as I can tell – Santiago Squarzon Jun 30 '23 at 22:17
  • 1
    Not quite as convenient and I'll have to rewrite my scripts, but it seems to work. Thank you! – Roman Jun 30 '23 at 23:14
  • 1
    Note that you can also use `-UseWindowsPowerShell` in `Import-Module` calls, which implicitly imports a given module via the [Windows compatibility feature](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Windows_PowerShell_Compatibility). – mklement0 Jun 30 '23 at 23:23
  • The Add-Type behavior you reference is in the assemblies implicitly referenced when you call `Add-Type`, and should not interfere with runtime behavior of type resolution - if it's problematic you'll see so when you run `Add-Type`. There is not .NET (Core) version of WindowsImpersonationContext AFAIK, thus you'll have to port to a different implementation. – Stroniax Jul 03 '23 at 22:10

0 Answers0