How do I (administrator) gracefully close a window process running in another user session using powershell on Windows 2008 R2 Remote Desktop Services - powershell

If I run the following command in my session...
(Get-Process -Id $pid).CloseMainWindow()
I am able to gracefully shut down a process (no modal windows or other popups arise).
If, however, the pid is in another user's session on the same machine (running RDS), the process does not close, and CloseMainWindow() returns FALSE (it returns TRUE if it's running in my own session). It also works if I run the powershell from the other user's session.
I specifically need a way to gracefully shut down the program as the program has a few important cleanup actions required to keep its database in order. So stop-process or process.kill() will not work.

After lengthy research, it does not seem possible to do this. There is, however, a solution which met at least some of my requirements.
You can create a Windows Scheduled Task which is triggered on session disconnect. This allows you to run a cleanup job as the user, rather than as the administrator, which allows programs to exit gracefully.
It has two major drawbacks....
It is called even if the user just has a minor network interruption (so you have to build a wait() function in the script to sleep for a bit and then check if it is still disconnected - not a clean solution.
It isn't called during a log-off event. For that you need to use a logoff script triggered by GPO.
Hope this helps someone in the future.

Related

TaskKill Explorer.exe also kills PS1 launched via Registry Run key?

I am trying to hack together an automated Icon Cache delete, and everything is working fine when I initiate the scripts manually. In PowerShell I use TaskKill to kill Explorer.exe, Sleep for 10 seconds so the icon cache DB files are no longer in use, then delete them and restart Explorer.exe with Start-Process. I am also using a VBScript to launch the PowerShell script as I want this to happen transparently to the user.
The final implementation involves running everything by way of the Run key in the Windows registry. That triggers my script that has a mechanism for running this only once, but for every user who logs on to the machine.
The problem SEEMS to be that killing Explorer.exe also kills the script that was launched via Run, so it never has a chance to write to the registry in Current User that this task has completed. Thus Explorer.exe is restarted on every single logon, which is not desirable.
Is this a known interaction between Explorer.exe and things launched via the Run key? Or might there be something else going on?

How to restart an exe when it is exits in windows 10?

I have a process in windows which i am running in startup. Now i need to make it if somehow that process get killed or stopped i need to restart it again in Windows 10?
Is there any way. Process is a HTTP server which if somehow stopped in windows i need to restart it. I have tried of writing a power-shell in which I'll check task-list status of process and then if not found I'll restart but that is not a good way. Please suggest some good way to do it.
I have a golang exe; under a particular scenario my process got killed or stopped i need to start it up again automatically. This has to be done imediately after the exe got killed. What is the best way to achieve this?
I will give you a brief rundown. You can enable Audit Process Termination in local group policy of the machine as shown below. In your case, success audits would be enough. Please note that the pic is for Windows 7. It may change with OS.
Now every time a process gets terminated, a success event will be generated and written to the security eventlog.
This will allow you to create a task scheduler that triggers on the generation of this event that calls a script that would run the process again. Simple right?
Well, you might have some trouble setting that task up especially when you want to pass details about the generating event to the script. This should help you get through that.
You can user Task scheduler for this purpose. There is a option of "restart on failure" which can be selected and whenever your process get failed it will restart again.
Reference :- https://social.technet.microsoft.com/Forums/windowsserver/en-US/4545361c-cc1f-4505-a0a1-c2dcc094109a/restarting-scheduled-task-that-has-failed?forum=winserverManagement

Scheduled Job & Balloon tip

I am looking for a way to run a job on a schedule and also alert the user to that running job. Specifically, I am using PowerShell to manage a computer lab scenario, and between sessions I want to refresh the environment, clean off the desktop, reset shortcuts pinned to the task bar for the next session, etc. But I want to warn anyone sitting at the machine that this is about to happen. However, my scripts that use Balloontips very successfully as regular scripts don't work as scheduled jobs. They run, and I have verified they run as the user in question, by creating a Scheduled Job that rights a text file to the user desktop. But Balloon Tips don't actually appear. Is there some secret to getting this to work, or is this a form of "interaction" that a scheduled job just can't do?
I also tried an alternative approach, launching the browser with a web page warning of the impending cleanup. That also didn't work. Suggesting some limits to what can be done as a Scheduled Job.
I would much rather go the very "integrated with the OS" route of the balloon tips, but for the life of me it seems like that just isn't an option. So, any other suggestions for providing user info by way of a scheduled job?
Since this runs in Session 0 where GUI interaction doesn't exist you must resort to some other mechanism.
You say this happens between sessions. You could show your ballon via another "notification script" that is executed from within your ScheduledJob. You have options here. For example:
Add entry to registry Run key that will self delete on run. Shows popup when user logs in (session change ? ). Entry executes posh script which parameters you could craft, i.e. (powershell -File notify.ps1 -ArgumentList "Operation bla bla..")
Add ScheduledTask that doesn't run in Session 0 (regular task). You need to do that only once. Every next time you run this job to show notification to the user from within main script via schtasks run or ScheduledTasks module depending on your system.
Add a ScheduledTask that check periodically EventLog for the input of your main script. The task would start on logon and subscribe to event log notifications. I don't like this as the script must run non-stop.

A user can close a script running by killing powershell task

How can I prevent a user from killing powershell process which ends the action of the script. and how can I restart powershell by a piece of code to resume its action?
If the script is being run under the users account, you can't stop them from being able to kill the process.
To get around this, you could have the script run as another user (as a service, or invoking as another user) which will launch the Powershell session under their credentials, in which case only admins will be able to kill the process.
Speaking from experience here:
In our environment we run SCCM, we have several powershell scripts that open a verbose window to let the user know that something is running. This script is running as SYSTEM. The user can still close the window even if they're not a member of the administrators group.
To get around crucial scripts that can't be closed I would suggest running the script silently, so that way it runs without the user even knowing. Or, if you indeed need a GUI, use VB.NET / C# to create a form and use the form closing event to prevent the user from closing it until you're well and ready.

Powershell how to run a program and waiting in a remote session

I have a command line program that listen to a tcp port until user type Q to exist. It works fine in local powershell window. But when I try to run it on another machine using powershell remote session, it just starts and quit. Is there a way to keep it running?
The remote script runs in a PowerShell that never becomes visible so AFAICT it doesn't even got a console handle by which to handle reading keyboard input.
You can take a look at the SysInternals utility - psexec. From my testing, that utility works for what you are trying to do.
Ensure you have Powershell 3 or higher since it adds support for detached sessions/background jobs.
Use a Remote Disconnected Session, described on Technet