Scheduling PowerShell tasks without a console window

Have you every wanted to use Windows Task Scheduler to run a PowerShell script on a frequent schedule, but hated how the console window would flash on the screen every time the script ran? Yeah, me too.

 

Apparently the task scheduler API supports hiding the console window, but the command line and visual interface don't expose it. My solution, rather than working with the API, is to create the world's smallest PowerShell host and compile it as a windows mode executable.

static class PoshExec
{
    static void Main(string[] args)
    {
        (new System.Management.Automation.RunspaceInvoke()).Invoke(args[0]);
    }
}
> csc  /target:winexe PoshExec.cs /r:"c:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll"

 

Once that's done you have what you need to schedule silent tasks

SCHTASKS /Create /SC MINUTE /MO 15 /TN ATaskName /TR "c:\devtools\PoshExec '& c:\devtools\myscript.ps1'"
kick it on DotNetKicks.com

No Comments