advapi32/OpenProcessToken.ps1

function OpenProcessToken
{ 
    <#
    .SYNOPSIS
 
    The OpenProcessToken function opens the access token associated with a process.
 
    .PARAMETER ProcessHandle
 
    A handle to the process whose access token is opened. The process must have the PROCESS_QUERY_INFORMATION access permission.
 
    .PARAMETER DesiredAccess
 
    Specifies an access mask that specifies the requested types of access to the access token. These requested access types are compared with the discretionary access control list (DACL) of the token to determine which accesses are granted or denied.
    For a list of access rights for access tokens, see Access Rights for Access-Token Objects.
 
    .NOTES
     
    Author: Jared Atkinson (@jaredcatkinson)
    License: BSD 3-Clause
    Required Dependencies: PSReflect
    Optional Dependencies: TOKEN_ACCESS (Enumeration)
 
    (func advapi32 OpenProcessToken ([bool]) @(
        [IntPtr], #_In_ HANDLE ProcessHandle
        [UInt32], #_In_ DWORD DesiredAccess
        [IntPtr].MakeByRefType() #_Out_ PHANDLE TokenHandle
    ) -EntryPoint OpenProcessToken -SetLastError)
         
    .LINK
 
    https://msdn.microsoft.com/en-us/library/windows/desktop/aa379295(v=vs.85).aspx
     
    .LINK
 
    https://msdn.microsoft.com/en-us/library/windows/desktop/aa374905(v=vs.85).aspx
 
    .EXAMPLE
    #>


    [OutputType([IntPtr])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [IntPtr]
        $ProcessHandle,
        
        [Parameter(Mandatory = $true)]
        [ValidateSet('TOKEN_ASSIGN_PRIMARY','TOKEN_DUPLICATE','TOKEN_IMPERSONATE','TOKEN_QUERY','TOKEN_QUERY_SOURCE','TOKEN_ADJUST_PRIVILEGES','TOKEN_ADJUST_GROUPS','TOKEN_ADJUST_DEFAULT','TOKEN_ADJUST_SESSIONID','DELETE','READ_CONTROL','WRITE_DAC','WRITE_OWNER','SYNCHRONIZE','STANDARD_RIGHTS_REQUIRED','TOKEN_ALL_ACCESS')]
        [string[]]
        $DesiredAccess  
    )
    
    # Calculate Desired Access Value
    $dwDesiredAccess = 0

    foreach($val in $DesiredAccess)
    {
        $dwDesiredAccess = $dwDesiredAccess -bor $TOKEN_ACCESS::$val
    }

    $hToken = [IntPtr]::Zero
    $Success = $Advapi32::OpenProcessToken($ProcessHandle, $dwDesiredAccess, [ref]$hToken); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()

    if(-not $Success) 
    {
        throw "OpenProcessToken Error: $(([ComponentModel.Win32Exception] $LastError).Message)"
    }
    
    Write-Output $hToken
}