Schedule Hidden PowerShell Tasks

I’ve had some questions lately about scheduling a PowerShell script. This is something we’ve covered a little bit. You recall that you can run a PowerShell command from CMD:

powershell -nologo -command "& {c:\scripts\myps.ps1}"

You can include commands like this into a batch file or use the expression as a scheduled task. If you want to completely hide the PowerShell output you can use an expression like this:

powershell -nologo -noninteractive -command "& {c:\scripts\myps.ps1}"

This works great when running PowerShell directly from CMD or in a batch file. However if you are trying to hide the window when running as a scheduled task, this doesn’t have any effect. In order to hide the window, you need to wrap your PowerShell command in a VBScript and use the Run method of the Shell object. This method lets you specify a Window style, including hiding it.  Here’s a wrapper script you can use.

Dim objShell,objFSO,objFile

Set objShell=CreateObject("WScript.Shell")
Set objFSO=CreateObject("Scripting.FileSystemObject")

'enter the path for your PowerShell Script
 strPath="e:\documents and settings\jhicks\my documents\scripts\posh\Get-DiskSize.ps1"

'verify file exists
 If objFSO.FileExists(strPath) Then
   'return short path name
   set objFile=objFSO.GetFile(strPath)
   strCMD="powershell -nologo -command " & Chr(34) & "&{" &_
    objFile.ShortPath & "}" & Chr(34)
   'Uncomment next line for debugging
   'WScript.Echo strCMD

  'use 0 to hide window
   objShell.Run strCMD,0

Else

  'Display error message
   WScript.Echo "Failed to find " & strPath
   WScript.Quit

End If

The only thing you need to do is put in the path and filename to your PowerShell script. Because of the way PowerShell and CMD struggle with long filenames, the wrapper script gets the short path of your script. This removes the need to struggle with quotes, which trust me, which you don’t want to deal with. Save the VBScript and create your scheduled task. Be sure to specify WSCRIPT to run your script and not CSCRIPT, otherwise you’ll still get a command window popping up.

I know it seems like a lot of work, but I’ve done most of it for you.  All you need to do is put your PowerShell script path in the wrapper. IMPORTANT: This wrapper assumes you want to run a PowerShell script. It will not work with a PowerShell cmdlet or expression. I’ll see what I can do about that another day.

(I’ve attached a copy of the script as a text file. It’s less than 1K so it shows up as 0)