Run a PowerShell task silently
When a scheduled task runs a PowerShell script in the end user context the console window is visible. Even with the -WindowStyle Hidden flag the console window will be visible for a second or so.
VB scripts can be run in the user context with no visible window at all. When a VB script calls PowerShell.exe with -WindowStyle Hidden the brief console pop up is completely suppressed.
Set objShell = CreateObject("Wscript.Shell")
objShell.Run("powershell.exe -WindowStyle hidden -File MyScript.ps1"),0
The secret to suppressing the console window is the ,0 at the end of the second line.
This code sample is not very flexible. A better approach is to accept the script path as a command line argument so the script can be reused.
Set objShell = CreateObject("Wscript.Shell")
Set args = Wscript.Arguments
For Each arg In args
Dim PSRun
PSRun = "powershell.exe -WindowStyle hidden -ExecutionPolicy bypass -NonInteractive -File " & arg
objShell.Run(PSRun),0
Next
To use the script create a scheduled task with wscript.exe as the command and the following argument:
<path>\PsRun.vbs <Path>\MyScript.ps1
As shown:
The complete code can be found here:
https://github.com/gbuktenica/PsRun