Skip to content

Instantly share code, notes, and snippets.

@trondhindenes
Created October 4, 2015 10:43
Show Gist options
  • Select an option

  • Save trondhindenes/6ecb829057e01a6da568 to your computer and use it in GitHub Desktop.

Select an option

Save trondhindenes/6ecb829057e01a6da568 to your computer and use it in GitHub Desktop.
Script that will execute itself as a scheduled task
Function Exit-Json($obj)
{
# If the provided $obj is undefined, define one to be nice
If (-not $obj.GetType)
{
$obj = New-Object psobject
}
echo $obj | ConvertTo-Json -Compress -Depth 99
Exit
}
Function RunAsScheduledTask
{
Param ([System.Management.Automation.PSCredential]$Credential)
if ((Get-Variable -Name IsScheduledTask -ValueOnly -ErrorAction SilentlyContinue) -eq $true)
{
#we're already running as a scheduled task
}
Else
{
$Currentfilename = $PSCommandPath
$CurrentFOlder = (Get-item $PSCommandPath).Directory
$ScriptFileName = Join-Path $CurrentFOlder "ScheduledTask.ps1"
Copy-item $Currentfilename -Destination $ScriptFileName -Force
$Contents = get-content $ScriptFileName
$FirstLine = 'Set-Variable -scope Global -name IsScheduledTask -value $true'
$SecondLine = "Set-Variable -scope Global -name OriginalScriptFile -value $Currentfilename"
Set-content $ScriptFileName -Value $FirstLine,$SecondLine,$Contents -Force
if (test-path "$CurrentFOlder\scheduledtaskoutput.json")
{
remove-item "$CurrentFOlder\scheduledtaskoutput.json"
}
#Configure the task runner
$action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-executionpolicy bypass -command $ScriptFileName >> $CurrentFOlder\scheduledtaskoutput.json"
$trigger = New-ScheduledTaskTrigger -At (get-date).AddMilliseconds(1000) -Once
#$taskuser = "$env:USERDOMAIN\$env:USERNAME"
$S = New-ScheduledTaskSettingsSet
Register-ScheduledTask -TaskName "Install-ADFSFarm" `
-Action $action `
-Trigger $trigger `
start-scheduledtask "Install-ADFSFarm"
Do {start-sleep -Milliseconds 1000}
Until ((get-scheduledtask "Install-ADFSFarm").State -eq "Ready")
#unregister-scheduledtask "Install-ADFSFarm" -confirm:$false
if (get-scheduledtask "Install-ADFSFarm" -ErrorAction 0) { unregister-scheduledtask "Install-ADFSFarm" -confirm:$false}
}
}
RunAsScheduledTask
if ($IsScheduledTask -eq $true)
{
#The code in this block will run inside a scheduled task
$myobj = "" | Select msg
$myobj.msg = "Completed Successfully"
exit-json $myobj
}
Else
{
#This code will run after the scheduled task has been executed and completed
$CurrentFOlder = (Get-item $PSCommandPath).Directory
$exitobject = get-content "$CurrentFOlder\scheduledtaskoutput.json" | ConvertFrom-Json
exit-json $exitobject
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment