Home > front end >  How to wait until all commands are executed and only then have a prompt to restart your PC in powers
How to wait until all commands are executed and only then have a prompt to restart your PC in powers

Time:05-10

I am writing a powershell script for enabling some Windows Features. It looks like something like this:

...
Enable-WindowsOptionalFeature -Online -FeatureName "IIS-WebServerRole"
Enable-WindowsOptionalFeature -Online -FeatureName "IIS-WebServer"
Enable-WindowsOptionalFeature -Online -FeatureName "IIS-FTPServer"
...

In this script, there are multiple commands where I enable windows features which require a restart. So what I noticed is that in powershell it's enabling stuff, and then the last 4 lines where I enable stuff that requires restart, it's constantly prompting me to restart the computer in powershell. So I have to constantly say "No" because otherwise it'll restart the computer before all the commands in the script are executed:

enter image description here

My question is, in my script, how do I wait until all commands are executed, and only then have a prompt about restarting my PC? I tried adding "Wait-Process" and "-Wait" tags to the commands, but I got errors like this: enter image description here

Does anyone know a way I could wait for all the commands to execute and only then have a restart prompt? Thanks in advance!

CodePudding user response:

Enable-WindowsOptionalFeature has a -NoRestart switch. Described as:

Suppresses reboot. If a reboot is not required, this command does nothing. This option will keep the application from prompting for a restart or keep it from restarting automatically.

CodePudding user response:

To build on @zdan's answer, use the -NoRestart flag. You could either omit -NoRestart to the final feature, or do the prompt yourself which leaves you open to alternative logic patterns to install a list of desired features:

'IIS-WebServerRole', 'IIS-WebServer', 'IIS-FTPServer' | ForEach-Object {
  Enable-WindowsOptionalFeature -Online -FeatureName $_ -NoRestart
}

if( ( Read-Host -Prompt "Would you like to reboot to complete feature installation? (y/n)" ) -match '^y' ) {
  Restart-Computer -Force
}

Or if you want to keep it simple and don't need custom prompt text before prompting for the reboot, simply use the -Confirm switch with Restart-Computer in order to get a reboot prompt:

'IIS-WebServerRole', 'IIS-WebServer', 'IIS-FTPServer' | ForEach-Object {
  Enable-WindowsOptionalFeature -Online -FeatureName $_ -NoRestart
}

Restart-Computer -Confirm -Force
  • Related