Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
param (
[string] $ScriptPath,
[string] $TaskName
# Pass in as many arguments as you want....
# Setup error handling.
Write-Output "Trapped an Error"
Exit 1
# Stop On Error
$ErrorActionPreference = "Stop"
# Disable progress bar
$ProgressPreference = "SilentlyContinue"
# Run script as Vagrant User
$username = "vagrant"
$password = "vagrant"
# Generate a Unique ID for this execution
$guid = [guid]::NewGuid()
$logFile = "c:\Windows\Temp\$guid.log"
# ScriptArgs is the catch-all for undeclared arguments that must be passed
# to the script being executed. For example:
# ./RunScriptAsScheduledTask.ps1 -ScriptPath a:/MyScript.ps1 -TaskName PackerTask -Much -Arguments -So -Packer
$ScriptArgs = $args
$argument = "-NoProfile -ExecutionPolicy unrestricted -Command ""& {""$ScriptPath"" $ScriptArgs} 2>&1 > $logFile"""
Write-Output "Creating Scheduled Task - $TaskName - for Script $ScriptPath"
Write-Output "Scheduled Task Command: powershell.exe $argument"
$a = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $argument
Register-ScheduledTask -TaskName $TaskName -RunLevel Highest -User $username -Password $password -Action $a | Start-ScheduledTask
Start-Sleep -Seconds 30
$task = Get-ScheduledTask -TaskName $TaskName
}while($task.State -eq 4)
Write-Output "Scheduled Task $TaskName - Execution Finished"
if ( (Test-Path $logFile)) {
Write-Output "Scheduled Task $TaskName Log Output:"
Get-Content $logFile
Exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment