Execution Order Shutdown Windows and GPEDIT.MSC Scripts - vbscript

I have a question regarding the execution order while shutting down/logoff Windows and the scripts shutdown/logoff in the GPEDIT.MSC.
When I shutdown/logoff will the scripts in the gpedit.msc be executed before Windows closes everything or is it the other way around, that Windows closes every other running process and then starts the script?
Thank you.

Logoff scripts are run in the security context of the user that is logging off. That is important to remember as their rights are limited accordingly. As a log off doesn't necessarily require a shutdown, the system is still up and running. More info: https://technet.microsoft.com/en-us/library/cc753583%28v=ws.11%29.aspx?f=255&MSPPError=-2147217396
Shutdown scripts run in the security context of LocalSystem. They still need the command shell or script host to be running to execute, so the operating system is still running. To find out exactly what processes are still running, you could try dumping a process list to a text file in a shutdown script. You can find a little more info here: https://technet.microsoft.com/en-us/library/cc770300%28v=ws.11%29.aspx?f=255&MSPPError=-2147217396
Hope this helps.

After a few tests I found the answer.
Windows first closes all running applications and then starts the scripts in the GPEDIT.MSC.

Related

Make a PowerShell script run on startup in the OOBE Sysprep environment

Thanks for stopping by, I've searched the corners of the internet but haven't gotten anywhere.
To provision devices for my organization, we must manually run PowerShell commands using SHIFT + F10 in the Windows 11 OOBE as we have multiple methods, one of which being legacy. I'm sure there are better methods but I'm unfortunately working within these limitations. So far, to automate the imaging process, I've created an autounattend.xml which makes WinPE completely silent and some pages of the OOBE also.
Recently, I combined all the PowerShell commands we had been running prior into a script that, after running repeated checks for a network connection, prompts users with a GUI and effectively automates everything we had been doing manually before:
Message box with radio buttons
I need to make this run when the OOBE Sysprep starts, but I really need some help.
The script contains GUI, so it cannot run silently and the user needs to interact with it.
The script must start with the OOBE Windows Welcome Screen, (i.e. select region screen). This is a limitation of the modules used and I therefore can't include it as a synchronous command in FirstLogonCommands or include it in SetupComplete.cmd, as those both execute after the OOBE is completed.
I've tried configuring the answer file to boot into audit mode and have the script run there, but the script requires several reboots and I get an installation failed message after any reboot (despite later making the script enable the Administrator account and call "sysprep /audit /reboot"). Additionally, the Audit Administrator account takes ~15 minutes to log in so it defeats the whole purpose of time saving.
I've tried using Task Scheduler, running both on System Start Up and User Log On, as defaultuser0, BUILTIN\Administrators and SYSTEM. Task scheduler seems to either queue tasks or not call them at all in the OOBE
I've tried placing the script, and then a shortcut of the script, in the common start up folder but that didn't work either.
To reiterate, I need a way to automatically run a script when the OOBE Sysprep starts. Furthermore, I need it to run every time the OOBE is launched as sometimes, we have to manually reboot if something glitches or goes wrong so the script will need to run again when the OOBE is resumed.
I know this is a tough one due to the limitations, but this will make the device rollout significantly easier.
Thanks,
Jake

Get linenumber of hanging script

I recently "inherited" a complex PowerShell script that performs tasks in the background via task scheduler. Now we're seeing that the script hangs in some occasions, but until now I'm unable to identify the root cause.
Is there a way to pol or attach a debugger to an already running script so i can get the current line-number without rewriting large portions? In it's current state, the maintainability of the script is sub-par with 20k lines of code.
I tried checking WMI for properties, but found nothing useful. I did found a chronograph script that may be useful https://powershellexplained.com/2017-02-05-Powershell-Chronometer-line-by-line-script-execution-times/ .
I also wrote a debugging wrapper, but the hang only happens in some occasions. I am unable to reproduce on demand.
Thanks
Have you looked at Enter-PSHostProcess ?
The Enter-PSHostProcess cmdlet connects to and enters into an interactive session with a local process. Instead of creating a new process to host PowerShell and run a remote session, the remote, interactive session is run in an existing process that is already running PowerShell. When you are interacting with a remote session on a specified process, you can enumerate running runspaces, and then select a runspace to debug by running either Debug-Runspace or Enable-RunspaceDebug
Enter-PSHostProcess

windows scheduling of a power-shell script is unreliable

I'm attempting to run an automated powershell script all day, everyday. But I'm have problems getting it to run consistently and reliably, the script itself runs fine, it's getting the windows scheduler to run it consistently that's the problem.
The script is invoked every morning by windows scheduler at 1am as powershell.exe with the command arguments:
-windowstyle Normal -NoExit -file "d:\work\PwrShellScripts\FlmToDb_010.ps1"
Once invoked, the script will run continuously until 11pm at night when it will exit.
The script itself works reliably, but the scheduling only works nine times out of ten, once in a while it fails with the error:
Task Scheduler did not launch task "\DailyFlm" because instance "{aa18e048-d8b2-4e16-8737-fc7babbb609e}" of the same task is already running.
The question is, how to get the script to run reliably every day?
Other info that may be relevant…....
The arguments -windowstyle Normal -NoExit mean that the powershell script runs in a command window (rather than as background process) and the window will remain open if the session ends.
This is done for two reasons, firstly it provides a visual indication that the process is actually running, and secondly if the process fails, it allows the error message to be inspected. The powershell script doesn’t include any file logging, so running it in a command prompt also allows me to confirm that the previous days session made a clean exit when it stopped.
One of the issues is that because the process works 90% of the time, if I make any tweaks I have to wait 10 days or more to confirm if they’ve really worked!
I suspect that the issue may be related to the fact that the console remains open (-NoExit) when the script exits. Most of the time windows seems to recognise that although the console is still open, the associated script has exited.
My guess is that occasionally it decides that since the console is open the process is still running. I'm unable to spot any difference between those occasions when the scheduling works fine and those when it doesn't.
Any suggestions?
Updates...
The scheduler fails to start the job on average once every 10 days. I would prefer to keep the script running in the foreground, it makes monitoring it's progress so much easier, and makes it so obvious if it does fail.
the same task is already running.
The script may do what it's supposed while it runs, but there is one flaw... it's not closing properly. It's exactly the -NoExit issue you talk about. When you run a powershell task, the process name is powershell.exe, with it's associated process id, and that's how the task scheduler knows if it's finished or not.
To fix this, I suggest writing a script to kill all powershell.exe processes and scheduling it to run right at 12:55am every day.

Powershell: how to pause or delay or block shutdown to give time for cleanup tasks?

I have a powershell script that is running all the time on windows 7. If user does computer shutdown or reboot, I need a little time to do cleanup tasks such as updating log file.
Is there a way to delay shutdown from within script?
Solutions I've found from searching don't work well:
*Listening for events such as SessionEnding are too late and powershell is closed before script has time to do anything
*I'm looking for a solution within the script that runs at startup instead of separate solution such as adding a 2nd script to group policy that runs on shutdown
I've looked at WM_QUERYENDSESSION but I can't get it to work for powershell script.
Add the script on GPE on your local computer, So the script will run while shutdown.

How to restart program automatically if it crashes in Windows?

How can I start my program automatically if it crashes on windows 2003 server? Sometimes my program just crashes, is there a way in windows or settings that I can set?
There are several ways to create a process supervisor/guardian process on Windows.
First, is to leverage windows command line capabilities. Create a bat file:
#echo off
:start
start /w "your app to watch.exe"
goto start
start /w will wait for the process to exit. When the process crashes and exits, the bat script will relaunch it.
Another option is to use free supervisor tool https://github.com/chebum/Supervisor. It allows to restart the crashed app, plus it allows to monitor two or more apps at once and it will automatically close these apps when supervisor's window is closed.
The usual approach is to run what is known as a guardian process. This is a separate process, often a service, that monitors the state of the main process. When the guardian detects that the main service has died, it re-spawns it.
To the very best of my knowledge, there is not built in Windows functionality to do this for you.
Notice: running self-looping bat files can be useful, but unless you know what you're doing, they can wreak all kinds of havoc. This goes especially if you run them on startup. You have been warned.
Anyway. I just remembered something from my 286 days, when I played around a lot with BAT files. If you write the file
yourprogram.exe
some other event
the BAT file will run yourprogram, and then pause and wait around in the background until the program exits. After that it will run "some other event". This used to be kind of annoying if you wanted to run multiple things at once, but here it's actually useful. Using this, it's possible to make it run a loop that restarts the program (and reruns the bat file) as soon as it exits. Combine this with https://superuser.com/questions/62525/run-a-completly-hidden-batch-file, and you'll never even see it happening.
The final BAT file ("restart.bat" in this example) will look something like:
c:\[location]\yourprogram.exe
wscript "C:\[location]\invisible.vbs" "C:\[location]\restart.bat"
That's about it. Start the program (on startup via task or even just startup folder) with line 2, and this ought to solve your problem :)
Oh, if you want to stop the loop, just rename the bat file or put "// " in front of the two lines, save it, and exit the program.
If the program you are running requires admin rights, the solution I found was using psexec (http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx) to run both the program and the bat with elevated privileges. In that case the BAT will look like:
c:\[location]\psexec -h c:\[location]\yourprogram.exe
c:\[location]\psexec -h wscript "C:\[location]\invisible.vbs" "C:\[location]\restart.bat"
Then you run the bat as administrator, or run the second line (without the psexec part) from task scheduler with elevated privileges. BEWARE: running it as a normal user and clicking "no" on the UAC prompt gave me a BSOD, probably because it looped "can't run program because of lacking privileges" a couple of billion times or something :)
You can use RegisterApplicationRestart.
"If you register for restart and the application encounters an
unhandled exception or is not responsive, the user is offered the
opportunity to restart the application; the application is not
automatically restarted without the user's consent. "
For automatic restart without user intervention, there is also RestartOnCrash. Works with all Windows versions.
I was looking for something similar. There are two options to handle this - either you can write a small script by yourself or use something that is already existing.
After some googling I came across this nice list. The blogger has compiled about 8 tools to automatically restart a crashed or closed application.
Unfortunately there are no settings in Windows to automatically restart a regular program when it crashes.
Do you need to actively interact with your application's GUI? Some of the Service Wrappers (designed to run any application as a Windows Service) will monitor your application and restart it when it fails, but be sure investigate Session 0 Isolation to ensure that it won't get in the way.
You may use some special app like BDV SystemEvents or any other. It allows you to specify application which will be started if some another application is closed. Specify the same application as a Condition and as an Action and you will get expected results.

Resources