Continuous Windows server operation could lead to problems in the core OS and deployed applications.
In addition, garbage files build up in critical memory areas, and the system starts running out of available memory.
In this case, restarting your Windows Server 2016 is a straightforward fix for all these issues.
In this tutorial, we will discuss the process of restarting the Windows Server 2016 machine. We will cover four methods that you can use to restart the server from the command line and the GUI.
Table Of Contents
- Restart Windows Server 2016
- Conclusion
- FAQs
Restart Windows Server 2016
Let’s go into the details of the methods of restarting the Windows server.
The Prerequisites
- A Windows Server 2016 system with a graphical interface
- Access via a command line
- A connection to a remote server (Optional)
- Access to Windows PowerShell (Optional)
Method #1: Restart Windows Server From the GUI
Method #2: How to Use the Reboot Command Prompt to Restart a Windows Server
In some scenarios, the GUI component might not be installed (usually to conserve space). In this case, you might only have access to the command prompt. Here are the steps of the process:
Step #1: Start by Launching the Command Prompt
- CtrlAltDel to bring up the context menu.
- Task Manager from this menu.
- More Details button in the Task Manager
- Click on the File menu and choose Run new task
- cmd.exe OK.
Step #2: Restart the Windows Server
–r option causes Windows to restart instead of just shutting down with the system.
Method #3: Use PowerShell to Restart the Windows Server
Like a Linux shell, it has a scripting language and is built on the solid .NET foundation. You can carry out all tasks that you can carry out in the GUI in the Windows PowerShell.
Here are the steps in the process of restarting Windows Server 2018.
Step #1: Open PowerShell
- To open the Task Manager, use Ctrl+Shift+Esc.
- Run new task from the File menu.
- powershell.exe OK.
Step #2: Restarting the System
PS > Restart-Computer
The system will start the restart process after the default countdown of five seconds.
PS > Restart-Computer –delay 15
Method #4: Rebooting a Remote Server Windows Using PowerShell
There are scenarios where you might not be physically present at the Windows Server. In this case, you can easily access your server machine via SSH or RDP. Here are the steps of the process:
Step #1: Launch the PowerShell
Step #2: Remotely Restart the Server
PS > Restart-Computer –ComputerName “NAME_OF_SYSTEM”
Remember to replace NAME_OF_SYSTEM with the server’s name. Don’t forget to include the quotation marks.
Effective restarting Windows Server 2016 is essential for maintenance and peak efficiency. PowerShell’s ‘Restart-Computer’ cmdlet and a variety of command prompt utilities, including shutdown option and reboot,’ as well as graphical interfaces, have all been thoroughly addressed in this article.
Opt for RedSwitches for unparalleled global dedicated hosting. Elevate your hosting experience with our reliable services, mirroring the assurance of excellent server performance through proper restarts. Explore our customizable hosting solutions tailored to your unique requirements.
So, If you’re looking for a robust server for your Linux projects, we offer the best dedicated server pricing and deliver instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.
Q. Why is it necessary to restart Windows Server 2016 regularly?
Regular restarts are essential for applying system updates, resolving issues, and ensuring optimal performance. It helps refresh system resources and maintain stability.
Q. What are the different methods for restarting Windows Server 2016 mentioned in the guide?
The guide covers various methods, including the graphical interface, command prompt using ‘shutdown’ and ‘reboot,’ and PowerShell’s ‘Restart-Computer’ cmdlet.
Q. Can I use remote commands to restart a Windows Server 2016 machine?
Yes, remote commands, such as PowerShell remoting, can be used to restart a server from another machine in the network.
Q. Are there any differences in the impact of a restart based on the method used?
Q. How can I schedule a regular physical server restart for Windows Server 2016?
Task Scheduler or PowerShell scripts can schedule regular server restarts for routine maintenance and updates.
Q. Are there any considerations for restarting a physical server in a production environment?
Q. Can I check if a server requires a restart before initiating the process?
Yes, PowerShell cmdlets like ‘Get-PendingReboot’ can be used to check if a server has pending reboots due to installed updates.
Q. What happens if a physical server restart is abruptly interrupted or fails to complete?
Incomplete restarts may lead to system instability or the application of incomplete updates. It is crucial to troubleshoot and complete the restart process to avoid potential issues.
Q. Can I restart specific services without restarting the entire server?
Yes, using the ‘services.msc’ console or PowerShell cmdlets, you can restart specific services without impacting the entire server.
Q. Is there a recommended method for restarting a Windows Server 2016 machine in a remote computer desktop environment?
As IT professionals and Managed Service Providers (MSPs), the task of managing and optimizing system services is an integral part of our roles. PowerShell, a robust scripting language, provides an efficient way to perform these tasks. It enables task automation, simplifies complex operations with just a few lines of code, and facilitates services management on multiple machines simultaneously.
The Script
<# .SYNOPSIS Restart one or more services. .DESCRIPTION Restart one or more services. This also try three more times to get the service(s) to start, all the while waiting 15 seconds between each attempt. .EXAMPLE -Name "ServiceName" Restarts a service with the name ServiceName .EXAMPLE -Name "ServiceName","AnotherServiceName" -WaitTimeInSecs 15 Restarts two services with the names ServiceName and AnotherServiceName and waits 15 Seconds for them all to start .EXAMPLE PS C:> Restart-Service.ps1 -Name "ServiceName" Restarts a service with the name ServiceName .EXAMPLE PS C:> Restart-Service.ps1 -Name "ServiceName","AnotherServiceName" -WaitTimeInSecs 15 Restarts two services with the names ServiceName and AnotherServiceName and waits 15 Seconds for them all to start .NOTES Exit Code 0: All service(s) restarted Exit Code 1: Some or all service(s) failed to restart Release Notes: Initial Release By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use. Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA). #> [CmdletBinding()] param ( # Name of service(s), either Name or DisplayName from Get-Service cmdlet [Parameter(Mandatory = $true)] [String[]] $Name, # The number of attempts to restart the service before giving up [Parameter()] [int] $Attempts = 3, # Duration in Seconds to wait for service(s) to start between each attempt [Parameter()] [int] $WaitTimeInSecs = 15 ) begin { function Test-Service { [CmdletBinding()] param ( [Parameter()] [String[]] $Services ) if ((Get-Service | Where-Object { ($_.Name -in $Services -or $_.DisplayName -in $Services) -and $_.Status -like "Running" }).Count -gt 0) { $true } else { $false } } $FailedToStart = 0 } process { # Get service(s) $Services = Get-Service | Where-Object { $_.Name -in $Name -or $_.DisplayName -in $Name } if ($Services.Count -eq 0) { Write-Error "No service(s) found." exit 1 } # Restart service(s) $Services | ForEach-Object { $AttemptCounter = $Attempts # Restart the service $Service = $_ | Restart-Service -PassThru # Wait till status of service reaches Running, timeout after $WaitTimeInSecs seconds $Service.WaitForStatus([System.ServiceProcess.ServiceControllerStatus]::Running, [timespan]::FromSeconds($WaitTimeInSecs)) | Out-Null # Loop till either the service is in a running state or our $AttemptCounter reaches 0 or less while ($(Get-Service -Name $Service.ServiceName).Status -ne [System.ServiceProcess.ServiceControllerStatus]::Running -or $AttemptCounter -le 0) { # Start service Start-Service -Name $Service.ServiceName # Wait $WaitTimeInSecs seconds Start-Sleep -Seconds $WaitTimeInSecs $AttemptCounter = $AttemptCounter - 1 } if ($((Get-Service -Name $Service.ServiceName).Status -ne [System.ServiceProcess.ServiceControllerStatus]::Running)) { # Add 1 to later show the count of services that failed to reach the running state $FailedToStart = $FailedToStart + 1 Write-Error -Message "Failed to start service( $($Service.ServiceName) ) after $Attempts attempts." } } # Print out services with their status Get-Service | Where-Object { $_.Name -in $Name -or $_.DisplayName -in $Name } # Check if service(s) have started if ($FailedToStart -eq 0) { # All service(s) have been restarted Write-Host "All Service(s) restarted." exit 0 } else { # Some or all Service(s) failed to restart Write-Error -Message "Failed to start $FailedToStart service(s)." exit 1 } } end {}
Access over 300+ scripts in the NinjaOne Dojo
Exploring the Restart-Service Cmdlet
The `Restart-Service` cmdlet in PowerShell is a powerful tool that allows you to restart a service on a local or a remote computer. This command consolidates the processes of stopping and starting a service, simplifying service management.
Extending the Use of Our Restart-Service Script
Our PowerShell script, designed to leverage the `Restart-Service` cmdlet, provides a comprehensive solution for restarting one or more services. This script, apart from restarting a service, also makes three attempts to start a service if it doesn’t initialize immediately, incorporating a 15-second pause between each attempt
Applications of the Script
Our Restart-Service script is not only handy for immediate service restarts but can also be used in various scenarios, such as:
Scheduled Restarts
You can use Task Scheduler in conjunction with our script to restart services on a schedule. This can be beneficial for services that need periodic restarts to free up resources or maintain optimal performance.
Post-Update Restarts
After a system update, some services may need to be restarted. Our script can be used in a post-update script to ensure all necessary services are restarted and running correctly.
Troubleshooting the Script
Despite the robustness of PowerShell scripts, there can be instances when things don’t go as planned. Here are some ways to troubleshoot issues with our Restart-Service script:
Error Logs
PowerShell provides detailed error logs that can be used to troubleshoot issues. If our script fails to restart a service, check the error logs for any error messages or exceptions that can provide insights into what went wrong.
Debugging the Script
PowerShell provides debugging features that can be used to step through the script and identify where the issue is occurring. Use the `Set-PSDebug -Trace 1` command to enable script tracing, and then run the script to see a line-by-line display of the commands being executed.
Final Thoughts
With NinjaOne’s comprehensive IT operations management platform, you can integrate and scale the use of custom scripts like our PowerShell service restart script across numerous endpoints. The platform’s capability to deploy and manage scripts centrally makes executing complex tasks across multiple devices seamless. This means you can use our script to manage services across your entire network, from a single dashboard, enhancing efficiency and ensuring consistency in your IT operations.
The PowerShell cmdlet Restart-Service provides a simple way to stop and start a service on a local or remote computer. In this article, we will cover the basics of using Restart-Service to restart services in PowerShell. You’ll learn the basic syntax, how to target local or remote services, restart multiple services at once, and even how to script and schedule automated restarts.
Why Should You Use PowerShell to Restart Services?
You might need to restart a service on a computer or server for several reasons. Restarting services is necessary when troubleshooting issues, applying updates, or restarting processes. Doing this manually through the Windows Services console can be time-consuming, especially if you need to restart multiple services across many computers. Some of these reasons include:
1. Service Failure
Services can fail for various reasons, including hardware failure, software bugs, and configuration errors. When a service fails, the system can become unavailable or unstable. Restarting the service can sometimes resolve the problem.
2. Software Updates
When installing software updates on a computer or server, you might need to restart services to ensure the changes take effect.
3. Performance Issues
Services can sometimes consume too much memory or CPU, causing performance issues. Restarting the service can help free up resources and improve system performance.
Understanding the PowerShell Restart-Service cmdlet
The Restart-Service
cmdlet is used to restart services in PowerShell. This command can be used to restart services on the local computer or remote computers. Here are the important parameters of the Restart-Service command:
Parameter | Description | Example Usage |
---|---|---|
-Name | Specifies the name of the service you want to restart. | Restart-Service -Name "ServiceName" |
-DisplayName | Allows you to specify the service by its display name instead of its service name. | Restart-Service -DisplayName "Display Name" |
-Force | Restarts the service and any dependent services. | Restart-Service -Name "ServiceName" -Force |
-Exclude | Excludes specified services from being restarted, useful when using wildcard characters. | Restart-Service -Name * -Exclude "ServiceToExclude" |
-Include | The -Include parameter of the Restart-Service cmdlet is used to specify an array of service names to include in the operation. | Restart-Service -Name 'win*' -Include 'WinRM','Winmgmt' |
More info on the syntax and parameters for Restart-Service is here: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/restart-service?view=powershell-7.4
Restarting a Service via the Services Console
- Open the Services console by searching for “Services” in the Windows start menu. You can do this by pressing the Windows key + R and typing “services.msc” in the Run dialog box.
- Locate the service you want to restart in the list of services.
- Right-click on the service and select “Restart” from the context menu. The service status will change to “Stopping” and then to “Starting” as the service restarts.
- Alternatively, you can stop the service by selecting “Stop” from the context menu and then start it again by selecting “Start”.
When the restart is complete, the service status will display as “Running”. If you prefer to use the command line, you can use the “net stop” and “net start” commands to stop and start a service, respectively. You can also restart a service through Task Manager >> Services.
Restart-Service -Name <ServiceName>
Replace <ServiceName>
with the name of the service you want to restart. For example, to restart the Print Spooler service, type:
Restart-Service -Name Spooler -PassThru
This will restart the Print Spooler service on the local computer. Here, -Name
specifies the name of the service that you want to restart. The service name is different from the display name, which is generally what you see in the services manager. To specify a service by its display name, use the -displayname
parameter. The -PassThru
parameter waits until the service is restarted and displays its running status.
Alternatively, You can use Get-Service to find the service name and pipeline the service object to the Restart-Service cmdlet.
Get-Service Spooler | Restart-Service
Please note that the services can be started only if the start type is set to automatic, manual, and automatic (delayed start). You can’t start the service if it’s disabled. You can change the startup type of the service using:
Set-Service -Name "Service Name" -StartupType Automatic
Use -Force Parameter to Immediately Restart a Service
By default, Restart-Service
sends a stop message and waits for the service to enter the stopped state before restarting. This helps ensure proper restart but can take more time. You can use the -Force
parameter to immediately restart the service after sending a stop message to the Windows service manager:
Restart-Service -Name Spooler -Force
This bypasses the waiting and restarts the service as soon as possible. Use -Force
when you need to quickly restart a service.
How do you identify the name of the service you want to restart?
Not sure about the name of the service you need to restart? Use the Get-Service
cmdlet to find it. This will return an object representing each service, helping you identify them by their service name or display name of the services. Just open the PowerShell console and type Get-Service to list all services:
Apart from the Name column from the above cmdlet, You can also get the service name from the services console:
You can use wildcards to get multiple services. Say, for example, let’s find all the services on the computer (starting with “Samsung Mobile”) and restart any that are stopped:
Get-service -DisplayName "Samsung*" | where {$_.Status -eq "Stopped"} | Restart-Service
You can also filter services by their other properties using the Where-object cmdlet:
Get-Service | Where-Object {$_.Name -like "*print*"} | Restart-Service
Stop and Start Windows Service using PowerShell
Here is how to stop and start Windows services using PowerShell:
Stop a Windows Service
To stop a service, you use the Stop-Service cmdlet. Specify the service name or display name using the -Name parameter:
Stop-Service -Name "Spooler"
This sends a stop message to the Windows Service controller. You can also pipe the Get-Service to stop or start a service. E.g.,
Get-Service -Name 'ServiceName' | Stop-Service
Alternatively, You can use the InputObject parameter as:
#Get the specific service $Service = Get-service -DisplayName "Print Spooler" #Stop the service Stop-Service -InputObject $Service -Verbose
Start a Windows Service
To start a service, you use the Start-Service cmdlet, again specifying the service name with -Name:
Start-Service -Name "Spooler"
This sends a start message to restart the service. You can check the status using Get-Service to confirm it stopped:
Get-Service -Name Spooler
Stop/Start Multiple Services
You can target multiple services using an array:
$services = @("Spooler", "Wsearch") Restart-Service -Name $services
This provides an easy way to stop and start multiple Windows services with PowerShell.
Restarting Services with PowerShell on Remote Computer
#Enter into a new session $Session = New-PSsession -Computername "RemoteComputer" #Execute PowerShell script remotely Invoke-Command -Session $Session -ScriptBlock {Restart-Service "webClient"} #Disconnect the Session Remove-PSSession $Session
Remote PowerShell Execution – Requirements
Please note, that the PowerShell remoting has below requirements:
- WinRM: The Windows Remote Management (WinRM) service must be running on the remote computer and properly configured to allow remote connections. You can configure it by running
winrm quickconfig
on the remote computer. - Firewall: Make sure the firewall allows for WinRM traffic (usually HTTP over port 5985 or HTTPS over port 5986).
- Permissions: Make sure you have the necessary permission to run commands on the remote computer. You might need administrative privileges, depending on what you’re trying to do.
- Network: Both the local and remote computers must be reachable over the network.
PowerShell Script to Restart Services on Multiple Computers
You can also use a PowerShell script to restart services on multiple computers. The script can be used to restart services on a list of computers or on all computers in a domain. Here is an example script that restarts the Print Spooler service on a list of computers:
$Computers = Get-Content "C:\temp\computers.txt" $ServiceName = "Spooler" foreach ($Computer in $Computers) { Write-Host "Restarting service on $Computer" Invoke-Command -ComputerName 'RemoteServerName' -ScriptBlock { Restart-Service -Name $ServiceName -Force } }
In this script, the Get-Content
cmdlet reads a list of computer names from a file, and the foreach
loop restarts the Print Spooler service on each computer.
Restarting IIS Services with PowerShell
Restart-Service -Name W3SVC
Invoke-Command -ComputerName 'RemoteServerName' -ScriptBlock { iisreset } -Credential (Get-Credential)
Restarting a Specific Website Remotely
If you want to restart a specific website on a remote computer, you can use Invoke-Command to run the necessary cmdlets.
Invoke-Command -ComputerName 'RemoteServerName' -ScriptBlock { Import-Module WebAdministration Stop-WebSite -Name 'Default Web Site' Start-WebSite -Name 'Default Web Site' }
How to Restart Multiple Services using PowerShell?
While individual cmdlets are powerful, a PowerShell script can help you perform more complex tasks like restarting multiple services in a specific order. You can create a script to restart services based on custom conditions and even apply it to multiple computers.
Having to restart services one by one can become tedious. Luckily, Restart-Service makes it easy to restart multiple services at the same time.
You have a few different options for restarting multiple services:
- Use wildcards: The
-Name
parameter accepts wildcard characters to target multiple services. For example:
Restart-Service -Name *print*
Input object: You can pipe a collection of services from Get-Service
to target multiple services:
Get-Service | Where-Object {$_.Name -like "*print*"} | Restart-Service
Specify service names: You can provide a comma-separated list of services:
Restart-Service Spooler,Wsearch
This provides flexibility for restarting groups of related services.
PowerShell to Restart multiple services if they are in the stopped state
To restart multiple services only if they are stopped, you can use PowerShell to first check the status of each service. If a service is stopped, you can restart it. Here’s how you can do this:
# Define an array of service names you want to restart $serviceNames = @('seclogon', 'WAS', 'TermService') # Loop through each service name in the array Try { ForEach ($ServiceName in $serviceNames) { # Retrieve the current status of the service $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue # Check if the service exists if ($service -ne $null) { # Check if the service is stopped if ($service.Status -eq 'Stopped') { # Restart the service Restart-Service -Name $serviceName -ErrorAction Stop Write-Host -f Yellow "Restared the service $serviceName because it was stopped" } else { # Output the current status of the service Write-Host -f Green "Service $serviceName is currently $($service.Status)" } } else { Write-Host -f Yellow "Service $ServiceName does not exist!" } } } catch { Write-Host -f Red "An error occurred: $_" }
How to Schedule Restarting Services?
You can easily create PowerShell scripts to automate restarting Windows services. This allows you to schedule restart tasks using tools like Windows Task Scheduler.
Here is an example script that restarts two services every day at 1 AM:
# Daily service restart script $services = @("Spooler","Wsearch") foreach ($service in $services) { Restart-Service -Name $service -Force }
Save this script as Restart-Services.ps1
and call it from Task Scheduler. This automates the task!
Best Practices for Restarting Services with PowerShell
1. Verify Service Name and Status
Before restarting a service, verify the service name to ensure you restart the correct service. Check the current status of the service using Get-Service
. Make sure the service has not been stopped before trying to restart it.
2. Stop Dependent Services
If a service has dependent services, stop the dependent services before restarting the main service.
3. Check the Service Status
After restarting a service, check the service status to ensure that it is running.
4. Test Service Functionality
Test the service functionality after restarting to ensure that it is working as expected.
5. Error Handling
try { Restart-Service -Name 'ServiceName' -ErrorAction Stop } catch { Write-Host "An error occurred: $_" }
Troubleshooting Common Issues with Service Restart
Sometimes, restarting services with PowerShell can encounter errors. Here are some common issues and their solutions:
- Access Denied – If you get an access denied error when restarting a service, ensure you have administrative credentials on the local or remote computer.
- Service Not Found: If you get a service not found error, verify that you have entered the correct service name.
- Service Dependencies: If a service has dependent services, stop the dependent services before restarting the main service.
- PowerShell Version: Ensure you are using the latest version of PowerShell to avoid compatibility issues.
- Verify that the service name is spelled correctly.
- Ensure that the remote computer is accessible and that you have the necessary network permissions.
- Check the event logs for any error messages related to the service restart failure.
Tail: How to Create a New Service and delete existing services using PowerShell?
PowerShell provides some more cmdlets for efficient service management. You can provision new services and remove existing services through PowerShell. Here is a quick example:
#Create a New service to Execute PowerShell script New-Service -name SiteBackupScript -binaryPathName "C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -File C:\Scripts\BackupScript.ps1" #Delete existing service (Get-WmiObject win32_service -Filter "name='SiteBackupScript'").delete() #From PowerShell 6 onwards, You can use: Remove-Service -Name "SiteBackupScript"
Conclusion and Next Steps
Restarting Windows services is a common task required for managing servers and workstations. However, doing this manually through the Services console is slow and tedious. The Restart-Service cmdlet in PowerShell provides a quick, flexible method for restarting services. This comprehensive guide has explored how to restart services with PowerShell. We have covered various scenarios, including restarting services on the local and remote computers, using scripts to restart services, and restarting IIS services.
How do I restart a service using PowerShell?
How can I restart a service on a remote computer?
Can I restart multiple services at once using PowerShell?
How can I check if a service was successfully restarted?
Can I restart a service using the service’s display name instead of its service name?
What if the service does not stop and start within a reasonable time?
If a service does not stop or start within a reasonable time, you may need to investigate further to understand the issue. You can use the Stop-Service
and Start-Service
cmdlets separately to have more control over the process: Stop-Service -Name "ServiceName"
Start-Service -Name "ServiceName"
How do I restart a service from the command line?
To restart a Windows service from the command line, you can use the net
command:
Stop the service with: net stop <service_name>
Start the service with: net start <service_name>
How do I stop a service?
How do I stop and disable a service?
To disable a service, you can use the Set-Service cmdlet with the -StartupType parameter set to “Disabled” after stopping the service. For example: Set-Service -Name "SERVICE-NAME" -StartupType Disabled
How do I check if a Service is running in PowerShell?
To check if a service is running in PowerShell, use the Get-Process
cmdlet. For example: $Drive = Get-Process -Name "GoogleDriveFS" -ErrorAction SilentlyContinue
I’m currently modifying some code, and below is what the current unmodified code is. For privacy reasons, actual file paths are replaced with “File Path”.
Clear-Host
$YN = Read-Host -Prompt "CONFIRM REBOOT [Y/N]"
if(($YN -eq "Y") -or ($YN -eq "y"))
{
Get-ChildItem -Path "File Path" -Recurse -File | Move-Item -Destination "File Path\Archive" -Force
$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
$Log = New-Item "File Path\$(Get-Date -f yyyy-MM-dd_hh-mm-ss) Restarts.txt" -ItemType File -Force
$date = Get-Date -Format "dd-MMM-yyyy hh:mm:ss"
Clear-Host
Write-Host `n `n `n
Write-Host "Rebooting all servers and verifying reboot status..." `n `n
Write-Host "Please standby, process may take up to 30 minutes..." `n `n
Restart-Computer -ComputerName $Servers -Wait -For PowerShell -Delay 2 -Force -Timeout 1800
"----------------------------------Script executed on $date----------------------------------" + "`r`n" | Out-File $Log -Append
foreach($computer in $Servers)
{
$PingRequest = Test-Connection -ComputerName $computer -Count 1 -Quiet
if($PingRequest -eq $true)
{
Add-Content -Path $Log -Value "$computer`: Reboot Successful." # Issue is here
}
else
{
Add-Content -Path $Log -Value "$computer`: Please manually check server."
}
}
Add-Content -Path $Log -Value "`n"
Clear-Host
Write-Host `n `n `n
Write-Host "All done!" `n
Write-Host "Please review logs, as script may have run into problems." `n `n
Log-Location
Pause
}
else
{
Clear-Host
Write-Host `n `n `n
Write-Host "Server Reboots Aborted." `n `n
Pause
}
My issue is the script as it currently stands, it simply does a ping request, which only confirms if the server is turned ON, not if it actually restarted. Is there a way for me to get PowerShell to check if the server has actually been restarted, or is this the best that PowerShell can do?
Key Takeaways
- Restarting your computer with PowerShell can be achieved using different methods, including scripts, scheduled tasks, and shortcuts.
- Understanding the PowerShell
Restart-Computer
command and its various parameters and flags are crucial to customize your restart process. - Troubleshooting common issues and following best practices can help ensure a smooth and successful restart process.
- While PowerShell is a recommended option, there are alternative methods available to restart your computer.
Understanding the PowerShell Restart-Computer Command
Restarting your computer is often necessary to apply updates or resolve issues caused by programs freezing or crashing. Instead of manually restarting the computer, you can use PowerShell to restart the computer from the command line. PowerShell provides a simple yet powerful command Restart-Computer cmdlet that allows you to restart the current or target computers.
The basic syntax for using the Restart-Computer command with the most common parameters is:
Restart-Computer [-ComputerName <String[]>] [-Force] [-Wait] [-Timeout <Int32>] [-For <WaitForServiceTypes>] [-Delay <Int32>] [-Credential <PSCredential>] [-WsmanAuthentication <String>] [-Protocol <String>] [-Confirm]
Here is the most common usage of the PowerShell Restart-Computer command to restart the computer:
Command | Description |
---|---|
Restart-Computer | Restarts the local computer Immediately |
Restart-Computer -ComputerName <name> | Restarts the remote computer specified by <name> |
Restart-Computer -Force | Restarts the computer forcibly, without gracefully shutting down running applications |
The Restart-Computer command also has many other parameters and flags that can be used to customize the restart process according to specific needs. For example, the -Wait
parameter can be used to wait for the restart process to complete before returning control to the console.
In the next sections, we will explore how to restart the computer using PowerShell in different scenarios, both locally and remotely.
Step 1: Open a PowerShell Session
Step 2: Verify Your Execution Policy
Set-ExecutionPolicy RemoteSigned
After running this command, you should be able to execute PowerShell scripts on your machine.
Step 3: Restart Your Computer
After executing this command, your computer will start the restart process. You may need to save any unsaved work before proceeding. If you want to get the confirmation, use the -confirm switch.
Restart-Computer -Confirm
By default, PowerShell will wait for the computer to finish any tasks and close all applications before restarting. If you want to force the restart without waiting for these tasks to complete, you can use the “-Force” parameter:
This will force the computer to restart immediately, bypassing any active tasks or open applications.
Restarting a Remote Computer using PowerShell
Restart-Computer -ComputerName <computer-name>
Replace computername
with the name or IP address of the remote computer you want to restart.
#Get credentials to connect $cred = Get-Credential #Restart remote computer Restart-Computer -ComputerName <Computer-Name> -Credential $Creds -Force
This command will prompt you to enter your credentials. Once done, the Restart-Computer command initiates the restart process.
Restart-Computer -ComputerName "Server1","Server2","Server3" -Force
This restarts the computers Server1, Server2, and Server3 without confirmation prompts.
Writing a PowerShell Script to Restart the Computer
If you need to restart your computer frequently, creating a PowerShell script can save you time and effort. A script is a set of commands that can be executed together, automating a specific process. In this section, we will guide you on how to create a simple PowerShell script to restart your computer with ease.
Step 1: Open PowerShell ISE or Visual Studio Code (Or any other text editor)
Step 2: Write the Script
Once PowerShell ISE is open, you can start writing your script. In this case, we want to create a script that restarts the computer. To do so, we will use the Restart-Computer command, which we discussed in the previous section.
This command will restart the computer immediately without any warning.
Step 3: Save the Script
Once you have written your script, you need to save it. To do so, click on File > Save As in PowerShell ISE, and choose a name and location for your script. It is recommended to save the file with a .ps1 extension, which identifies it as a PowerShell script.
For example, you can save the file as “Restart-Computer.ps1” in the Documents folder.
Step 4: Run the Script
This command will execute the Restart-Computer script that you just created. Alternatively, you can create a shortcut to the script on your desktop or taskbar for easy access.
Restarting the Computer using a Shortcut with PowerShell
If you find yourself needing to restart your computer frequently, creating a shortcut on your desktop can be a convenient way to initiate the process quickly and easily. This section will guide you through the steps to create a desktop shortcut that executes a PowerShell command to restart your computer.
Step 1: Create a PowerShell Script
Save the file as Restart.ps1
on your desktop.
Step 2: Create a Desktop Shortcut
Right-click on an empty area of your desktop and select New and then Shortcut. This will open the Create Shortcut wizard.
powershell.exe -ExecutionPolicy Bypass -File C:\Users\YourUserName\Desktop\Restart.ps1
Click Next and give your shortcut a name, such as “Restart Computer”. Click Finish to create the shortcut.
You can pin the shortcut to the Start menu or taskbar for quick access. Right-click on the shortcut and select Pin to Start or Pin to Taskbar.
Using the Shortcut to Restart Your Computer
Now that you have created the shortcut, using it to restart your computer is as simple as double-clicking on the icon. PowerShell will execute the Restart.ps1
script and restart your computer.
Restarting the Computer with PowerShell and a Scheduled Task
If you want to schedule a computer restart for a specific time or condition, PowerShell combined with a scheduled task can help you achieve that. This section will guide you through the steps to create a scheduled task that will automatically restart your computer.
Step 1: Creating a Scheduled Task
To create a scheduled task, open the Task Scheduler on your local computer by searching for “task scheduler” in the Start menu. Click on “Create Task” in the right-hand panel and give your task a name and a description.
Step 2: Configuring the Scheduled Task
Under the “Triggers” tab, create a new trigger for the task by clicking “New.” Choose the start date and time for the restart, and select the appropriate options for how often the task should run. Set the trigger to begin the task “At log on” or “On a schedule,” depending on your needs.
Under the “Actions” tab, add a new action to the task by clicking “New.” In the “Action” field, enter “powershell.exe” and in the “Arguments” field, enter the restart command for the remote computer using the “Restart-Computer” cmdlet.
Step 3: Testing and Troubleshooting
Once you have configured the scheduled task, test it by running the task manually or waiting for the scheduled time to arrive. If the task encounters any issues, use the Task Scheduler’s “History” tab to view the task’s status and any error messages that may have been generated.
Troubleshooting Common Issues with Restarting Computers using PowerShell
Restarting computers using PowerShell is generally a straightforward process, but there may be instances where you encounter issues that prevent a successful restart. In this section, we will outline some common problems that you may face and provide solutions to help you overcome them.
Error Messages
When attempting to restart your computer with PowerShell, you may encounter error messages such as “Access is denied” or “The service cannot accept control messages at this time.” These can often indicate that you do not have the necessary permissions to restart the computer or that a particular service is not responding.
Connectivity Issues
If you are attempting to restart a remote computer using PowerShell, connectivity issues can arise that prevent a successful restart. These issues can include network problems, firewalls, or incorrect credentials.
To resolve connectivity issues, you can try checking your network settings, verifying your credentials, and ensuring that the target computer is connected to the network. You can also try using the Test-Connection command to troubleshoot network connectivity.
Hanging or Frozen System
In some cases, attempting to restart the computer with PowerShell may cause the system to hang or become frozen. This can be caused by processes or applications that are not responding or services that are preventing a clean restart.
To resolve this issue, you can try closing any open applications or processes manually before using PowerShell to restart the computer. You can also try using the -Force flag with the Restart-Computer command to terminate all running processes and services forcefully.
Insufficient Resources
If your computer does not have sufficient resources to complete a restart process, you may encounter issues such as slow performance or system crashes. This can be caused by low memory or disk space, or by too many running applications or processes.
To resolve this issue, you can try closing any unnecessary applications or processes before using PowerShell to restart the computer. You can also try freeing up disk space or adding more memory to your system.
Best Practices for Restarting Computers with PowerShell
1. Understand the Restart-Computer Command
Before executing the restart process, it is crucial to understand the PowerShell Restart-Computer command and its different parameters. By knowing the command, you can customize the restart process according to your specific needs. Some of the commonly used parameters include -Force, -Credential, -Timeout, and -Wait.
2. Test the Restart Process in a Safe Environment
Prior to restarting a computer using PowerShell, it is advisable to test the restart process in a safe environment. This can help you identify any issues or errors that may arise during the process. For instance, you can test the restart process on a virtual machine or a non-critical device before executing it on the actual computer.
3. Use the -Force Parameter with Caution
The -Force parameter in the Restart-Computer command can be helpful in some scenarios, such as when there are unresponsive programs or services that prevent a normal restart. However, it should be used with caution as it can result in data loss or other complications. Before using the -Force parameter, ensure that you have saved all important files and closed all necessary applications.
4. Add a Timeout Value
When executing the restart process with PowerShell, it is recommended to add a timeout value to avoid any unexpected delays or errors. The -Timeout parameter allows you to specify the time duration in seconds for the computer to complete the restart process.
5. Verify the Restart Status
To ensure that the restart process is successful, it is important to verify the restart status of the computer. You can do this by using the Test-Connection command or by checking the event log for any relevant entries. Verifying the restart status can help you identify any issues that may have occurred during the process.
6. Use PowerShell Scripts for Automating the Restart Process
If you need to restart computers frequently, it can be helpful to create PowerShell scripts that automate the restart process. This can save time and increase efficiency. However, ensure that the script is tested in a safe environment before executing it on multiple computers.
Exploring Alternatives to Restarting Computers with PowerShell
While PowerShell is a robust tool for restarting computers, there are alternative methods worth considering. In some cases, you may need to use other methods due to limitations or specific requirements.
Using the traditional Restart Method
The most straightforward approach to restart a computer is to use the traditional method of the Start menu. Click on the Start button, then select the Power icon, and finally choose Restart. This method is simple, convenient, and does not require any technical skills or commands.
Using the Command Prompt
If you prefer a command-line interface over PowerShell, you can use the Command Prompt to restart your computer. Open the Command Prompt by typing “cmd” in the Start menu search box, and hit Enter. Type the command “shutdown /r” to restart the computer instantly. You can also specify a time delay by adding the time value in seconds after the /t switch, like this: “shutdown /r /t 60” to restart the computer after 60 seconds.
Using Third-Party Tools
There are various third-party tools available that can help you restart your computer. Some of the popular examples include Reboot, Shutdown Timer, and Auto Power-on & Shutdown, among others. These tools offer additional features like scheduling, customization, and automation, which can be useful for specific scenarios.
Using the BIOS or UEFI Settings
If you are experiencing issues with the operating system or need to reset the computer entirely, you can use the BIOS or UEFI settings to restart the computer. Restarting from the BIOS or UEFI settings will erase all the data on the hard drive and restore the computer to its default settings. However, this method requires technical knowledge and can be risky if incorrectly executed.
Conclusion
I hope this guide has provided you with the necessary knowledge to use PowerShell to restart your computer. By applying the methods and best practices outlined in this guide, you can confidently resolve technical issues and improve system performance.
How can I restart my computer using PowerShell?
What is the PowerShell Restart-Computer command?
The PowerShell Restart-Computer command is a built-in cmdlet that allows you to restart a computer from within a PowerShell session. It provides various parameters and flags that allow you to customize the restart process.
How do I write a PowerShell script to restart the computer?
How can I create a shortcut to restart the computer using PowerShell?
Can I schedule a computer restart using PowerShell?
How do I troubleshoot common issues when restarting computers using PowerShell?
How to Shutdown a Computer using PowerShell?
To shut down a computer using PowerShell, you can use the Stop-Computer
cmdlet: Stop-Computer -ComputerName localhost
. Similarly, to Shut down a remote computer, use: Stop-Computer -ComputerName "Server01"