Last post Jun 10, 2015 03:56 AM by hemaanshu
Jun 09, 2015 03:05 AM|hemaanshu|LINK
I am writing a web service which needs to execute remote powershell in logged-on user context.
The application works fine if the logged-in user is a member of administrators group on remote machine, else the RunspaceFactory.CreateRunspace API fails with PSInvalidOperationException.
I have tried adding user to remote powershell users (using Set-PSSessionConfiguration), which I believe is the only required permission to run remote powershell.
Also, when I try this in a C# console application it works fine. I see the issue only with my web service.
I have also tried setting aspnet.config to allow flow of impersonation but still no luck.
I want to know if there are any additional settings required for IIS or ASP .NET to make it work?
Jun 10, 2015 03:56 AM|hemaanshu|LINK
Well, I seem to have found the problem...
With the first call to powershell (wsman), WSMan API Initialize (WSManInitialize function) is called which returns a handle unique to the user. Later, WSMan Session Initilize (WSManCreateSession function) is called which takes the handle and establishes
the powershell session.
If this goes well, the user gets the remote session and can execute remote commands...
Later, when the user wants to close the session, user can call runspcace.Close or runspace.Dispose methods. This should ideally do cleanup and close session and deinitialize WSMAN API.
But, I observed that, calling runspace.Dispose or runspace.Close only closes the session but does not deinitialize the WSMan API.
Hence, when the second user logs in, the create session API fails as the handle corresponds to previous (different) user...
If I re-cycle the IIS Application pool and, then login the calls are successful.
Now I am searching for means to ensure that the WSMan API is deinitialized properly when a user logs off (terminates their remote powershell session)
Here, either I am doing something very silly or it is a bug with Powershell SDK or IIS.