0

I need to impersonate logged on user. It's required because of ps security context.

Let me explain. I have one win service. And one dll library with whole logic. And two different clients(.exe and ps) which use this service via dll.

When I start .exe and call win service everything is ok. But when i start ps and try to use the same win service method with the same arguments it gives me this error: (and also i start exe and ps with the same user on the same machine)

Either a required impersonation level was not provided, or the provided impersonation level is invalid.

Actually I try to use current account for impersonation. So I've found following method:

function ImpersonateLoggedOnUser
{
param
    (
        [Parameter(Mandatory = $true)]
        [IntPtr]
        $TokenHandle
    )

    $SUCCESS = $Advapi32::ImpersonateLoggedOnUser($TokenHandle); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()

    if(-not $SUCCESS)
    {
        throw "ImpersonateLoggedOnUser Error: $(([ComponentModel.Win32Exception] $LastError).Message)"
    }
}

But I can't call it. It gives me following error: You cannot call a method on a null-valued expression.

isxaker
  • 8,446
  • 12
  • 60
  • 87
  • Where is `$Advapi32` defined / what is it? It looks like this code is missing a large chunk of P/Invoke code, probably written in C# and in-lined with `Add-Type` or in a module that needs importing, wrapping around the advapi32.dll. – TessellatingHeckler Apr 27 '18 at 10:41
  • yes, you right. I defined it with error. so it helps me. thanks. – isxaker Apr 30 '18 at 10:08

0 Answers0