Skip to content

Instantly share code, notes, and snippets.

@dev-rowbot
Last active March 11, 2021 13:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dev-rowbot/fa8b8dadf1b3731067a93065db3e1bba to your computer and use it in GitHub Desktop.
Save dev-rowbot/fa8b8dadf1b3731067a93065db3e1bba to your computer and use it in GitHub Desktop.
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