Skip to content

Instantly share code, notes, and snippets.

@Juanito99
Created March 27, 2018 03:59
Show Gist options
  • Select an option

  • Save Juanito99/a672eb9bf4433591c8ff6b780a1740bb to your computer and use it in GitHub Desktop.

Select an option

Save Juanito99/a672eb9bf4433591c8ff6b780a1740bb to your computer and use it in GitHub Desktop.
Start a program on interactive session
Function Invoke-ScheduledTaskCreation {
<#
.Synopsis
Creates a temporary scheduled task to run the cmd-file privously created.
Required work-around as PowerShell limitation to run in the User's session interactivly.
.Example
Invoke-ScheduledTaskCreation -filenName $serverStartFile
#>
param(
[Parameter(Mandatory = $true)]
[string]$fileName
)
$section = "Invoke-ScheduledTaskCreation"
try {
$taskName = "Temporary Guardus Server Starter"
$taskValidStartTime = (Get-Date).AddSeconds(30) | Get-date -Format "yyyy-MM-ddTHH:mm:ss"
$taskValidEndTime = (Get-Date).AddMinutes(4) | Get-date -Format "yyyy-MM-ddTHH:mm:ss"
$command = $fileName
$taskRunAsUserName = "CONTOSO\" + (Get-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon").DefaultUserName
$taskRunAsUserPwd = (Get-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon").DefaultPassword
$service = New-Object -ComObject("Schedule.Service")
$service.Connect($env:COMPUTERNAME)
$rootFolder = $service.GetFolder("\")
$taskDefinition = $service.NewTask(0)
$regInfo = $taskDefinition.RegistrationInfo
$regInfo.Author = $taskRunAsUserName
$regInfo.Description = "Starting both Guardus Servers, task will be deleted automatically."
$settings = $taskDefinition.Settings
$settings.Enabled = $true
$settings.MultipleInstances = $false
$settings.AllowDemandStart = $true
$settings.MultipleInstances = $false
$settings.DeleteExpiredTaskAfter = "PT1M"
$settings.Hidden = $false
$triggers = $taskDefinition.Triggers
$trigger = $triggers.Create(2)
$trigger.StartBoundary = $taskValidStartTime
$trigger.EndBoundary = $taskValidEndTime
$trigger.Enabled = $true
$trigger.Id = "TasksId"
$action = $taskDefinition.Actions.Create(0)
$action.Path = $command
$rootFolder.RegisterTaskDefinition($taskName, $taskDefinition, 6, $taskRunAsUserName , $taskRunAsUserPwd , 0)
if ($error) {
$txt = "Error occured while $section"
$error.Clear()
} else {
$txt = "No occured while $section"
Write-EventLog -Source "SCOMGuardusMonitor" -LogName "Application" -EntryType Information -Message "Information on $scriptName; $txt" -EventId 11
}
} catch {
$txt = "Exception occured while $section"
Write-EventLog -Source "SCOMGuardusMonitor" -LogName "Application" -EntryType Error -Message "Exception in $scriptName; $txt; $_.Exception.ToString()" -EventId 15
}
Start-Sleep -Seconds 1
} #end Function Invoke-ScheduledTaskCreation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment