Search code examples
powershellpinvoke

P/Invoke during PSSession


For some reason, P/Invoke via PSSession is not working. I have a client side script which I run from a server through a PSSession. Here's the code for the client-side script:

$signature = @"
  [DllImport("user32.dll")]
  public static extern bool BlockInput(bool fBlockIt);
"@

$block = Add-Type -MemberDefinition $signature -Name DisableInput -Namespace DisableInput -PassThru
$unblock = Add-Type -MemberDefinition $signature -Name EnableInput -Namespace EnableInput -PassThru

$block::BlockInput($true)
Start-Sleep -Seconds 10
$unblock::BlockInput($false)

I'm basically testing blocking/unblocking keyboard and mouse access, based off a walkthrough I found here. I can successfully get the script to run, and the account I'm running it with should have elevated permissions, but for some reason, the call to $block::BlockInput and $unblock::BlockInput are both returning False, and neither the keyboard nor the mouse are blocked.

When I run the exact same script with the same account directly on the client machine, the script does exactly what it should - locks the keyboard and mouse for 10 seconds, and both calls to BlockInput return True. What am I doing wrong? Is it possible to P/Invoke via a PSSession?


Solution

  • My explanation : As far as I understand when you run a remote script in a PSSession it executes in a workspace totaly separate from the user one. For example if you start notepad, you can see that the notepad is executed on the remote computer but you can't see it on the UI. Your script block the console keyboard of the PSSession workspace, but not the one of the user.


    More explanation :

    The diagrams below show the relationships between sessions, windows stations, desktops and services in Windows Vista and newest versions. Begining in Windows Vista Session 0 is the base session where services run, the console session is typically Session 1.

    enter image description here

    When you use as PSSession a remote process is created WSMPROVHST.EXE. As you can see in the following capture, this process run in session 0, and your user interact with session 1.

    enter image description here

    In Sessions, Desktops and Windows Stations blog you will find the whole explanation.