Create a scheduled task for Windows using a script

Create a scheduled task for Windows using a script

Create the log folder if it does not exist

$logFolder = “C:\getLog”
if (-Not (Test-Path $logFolder)) {
New-Item -ItemType Directory -Path $logFolder
}

Define the action for the scheduled task: execute PowerShell script to perform GET request and log results

$actionScript = @”
$logFolder = ‘C:\getLog’
$logFile = Join-Path -Path $logFolder -ChildPath (‘log_’ + (Get-Date).ToString(‘yyyyMMdd’) + ‘.txt’)

try {
$response = Invoke-WebRequest -Uri ‘https://ip.ifgo.top’ -UseBasicParsing
$content = $response.Content
Add-Content -Path $logFile -Value (‘[‘ + (Get-Date).ToString(‘yyyy-MM-dd HH:mm:ss’) + ‘] ‘ + $content)
Write-Output (‘[‘ + (Get-Date).ToString(‘yyyy-MM-dd HH:mm:ss’) + ‘] ‘ + $content)
} catch {
Add-Content -Path $logFile -Value (‘[‘ + (Get-Date).ToString(‘yyyy-MM-dd HH:mm:ss’) + ‘] Error: ‘ + $_.Exception.Message)
Write-Output (‘[‘ + (Get-Date).ToString(‘yyyy-MM-dd HH:mm:ss’) + ‘] Error: ‘ + $_.Exception.Message)
}
“@

Write the action script to a temporary file

$tempScriptPath = [System.IO.Path]::GetTempFileName() + “.ps1”
Set-Content -Path $tempScriptPath -Value $actionScript

Define the scheduled task action: execute the temporary PowerShell script

$action = New-ScheduledTaskAction -Execute “powershell.exe” -Argument “-NoProfile -File "$tempScriptPath“”

Define the scheduled task trigger: run once and then repeat every minute for 1 year

$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).DateTime -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration (New-TimeSpan -Days 365)

Define the principal for the scheduled task: run with highest privileges as SYSTEM account

$principal = New-ScheduledTaskPrincipal -UserId “SYSTEM” -LogonType ServiceAccount -RunLevel Highest

Define the settings for the scheduled task

$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Hidden -StartWhenAvailable

Register the scheduled task

Register-ScheduledTask -TaskName “MyMinuteTask” -Action $action -Trigger $trigger -Principal $principal -Settings $settings

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply