-
-
Save Jeff-Lewis/1b48c543824b0a37035b56ba656eeb4d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param ( | |
[ValidateNotNullOrEmpty()] | |
[string] $ScriptPath, | |
[ValidateNotNullOrEmpty()] | |
[string] $TaskName | |
# Pass in as many arguments as you want.... | |
) | |
# Setup error handling. | |
Trap | |
{ | |
$_ | |
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 | |
do{ | |
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