Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide the PowerShell window when running a .ps1 script in Task Scheduler?

I am trying to run a PowerShell script using Task Scheduler and it pops up a PowerShell command console window.

Is there a way to disable this while running the script and hide the window?

I've tried -WindowStyle Hidden but the PowerShell command console window still pops up.

like image 994
Zulfiqar Dholkawala Avatar asked Oct 18 '17 10:10

Zulfiqar Dholkawala


People also ask

How do I run a PowerShell script without displaying Windows?

If the goal is to start a PowerShell script without a console window, you need to launch powershell.exe from a process that does not itself have a console window. A WSH script launched using wscript.exe does not have a console window, so you can write a WSH script that runs powershell.exe in a hidden window.

How do I hide a window in PowerShell?

Powershell: You use the Start-Process cmdlet with the flag -WindowStyle hidden .

Does closing the PowerShell window stop the script?

Terminating a PowerShell script with exitIf you execute the exit keyword inside of a PowerShell script, it will only terminate the script and the commands that follow it won't be executed.


1 Answers

Since powershell.exe is a console program, you can't execute it normally without its console window appearing (although you can hide it shortly after it starts by using -WindowStyle Hidden, as you have noted).

The trick is to execute powershell.exe itself in a hidden state. One way to do this is by using the WshShell object's Run method to run a PowerShell command line as hidden from inside a WSH script, and execute the WSH script using wscript.exe (which is not a console program, so no console window appears). Example script (JScript):

var wshShell = new ActiveXObject("WScript.Shell");
wshShell.Run('%SystemRoot%\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy Bypass -File "C:\\Scripts\\My Script.ps1"', 0, false);

If this script is C:\Scripts\My Launcher.js, you can now run the following command line:

wscript "C:\Scripts\My Launcher.js"

This runs the launcher script without a console, which then runs the PowerShell command in a hidden window (the Run method's second parameter is 0).

like image 68
Bill_Stewart Avatar answered Nov 14 '22 03:11

Bill_Stewart