Search code examples
c#powershellvagrantpowershell-remoting

EventWaitHandle "No handle of the given name exists" Vagrant remote Virtual Machine C# PowerShell


I have some code running on a Vagrant Hyper-V Virtual Machine that waits until it gets contacted before it starts. I'm attempting to tell the EventWaitHandler to continue through a remote PowerShell session. The code that waits is C#, and the code that activates is PowerShell. Here is the code that waits:

var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
var rule = new EventWaitHandleAccessRule(users, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow);
var security = new EventWaitHandleSecurity();
security.AddAccessRule(rule);
bool created;

var wh = new EventWaitHandle(false, EventResetMode.AutoReset, "EventName", out created, security);
Console.WriteLine("Waiting to be started...");

wh.WaitOne();

The issue I am having is that when I try to get the eventwaithandler through a remote powershell session, it tells me that it doesn't exist. Here is the powershell code that gets the waithandler:

Enter-PSSession -ComputerName MyVm
# This works unless it is run in a remote session
$Mutex = [System.Threading.EventWaitHandle]::OpenExisting("EventName")

When I run this code on the remote session, I get the following error:

Exception calling "OpenExisting" with "1" argument(s): "No handle of the given name exists."

Then it gives me the code that's failing and it points to the "OpenExisting" line above.

Just wanted to add as a note that it works perfectly fine all on the same machine, so I know that it SHOULD work, but doesn't through the remote session.

Any help/pointers would be appreciated.

Thanks


Solution

  • Found the answer, thought I'd post it here:

    The only thing I needed to do was put "global\" in front of the process name Initialize like this (C#):

    var wh = new EventWaitHandle(false, EventResetMode.AutoReset, "Global\\EventName", out created, security);
    

    And access it through PowerShell like this:

    $Mutex = [System.Threading.EventWaitHandle]::OpenExisting("Global\EventName")
    

    Works like a charm, even with the remote session...