How to Keep a PowerShell Script Running

In this tutorial, we’ll explain the process of keeping a PowerShell script continuously running, which can be especially useful if you have a script that you want to keep running in the background, even after the system experiences interruptions.

Step 1: Setting up the PowerShell Script

To begin with, you need to prepare your PowerShell script. It can be a script you already have or a simple one for testing purposes.

For this example, we’ll use a basic script that continuously outputs the current date-time to a Notepad file. Make sure to save your script as a “.ps1” file, which is the extension for PowerShell scripts.

Step 2: Setting up a Batch File

The next step is to create a batch file (.bat) that will be used to run the PowerShell script. This file will be configured to run indefinitely until you manually stop it.

Replace “C:\Path\Your_Script.ps1” with the actual location of the PowerShell script on your device. The “goto loop” command makes the batch file repeat indefinitely.

Step 3: Running the Batch File

Once you’ve created the batch file, all you have to do is to double-click on it to start running your PowerShell script. As long as this batch file is running, your PowerShell script will keep running continuously.

For a quick check, navigate to the C:\temp directory on your computer and open the “output.txt” file. You should see the current date and time being continuously updated every 10 seconds, just like our script commands.

01/01/2022 15:40:01
01/01/2022 15:40:11
01/01/2022 15:40:21

Step 4: Stopping the Script

To stop your PowerShell script from running, you can simply close the command prompt window where the batch file is executing.

Final PowerShell Code

$filePath = "C:\temp\output.txt"

while ($true) {
    Get-Date | Out-File $filePath -Append
    Start-Sleep -s 10
}

Final Batch Code

@echo off
:loop
powershell -File "C:\Path\Your_Script.ps1"
goto loop

Conclusion

By following these steps, you have now set up a PowerShell script to run continuously using a batch file. This method allows your script to run without interruptions, ensuring a continuous workflow for critical operations.

Feel free to reinforce your knowledge about PowerShell, by visiting the official PowerShell documentation. Remember, it’s always a good practice to check and revise your scripts for efficiency and resource management as running scripts indefinitely can consume system resources over time.