Quantcast
Channel: Active questions tagged powershell-3.0 - Stack Overflow
Viewing all articles
Browse latest Browse all 122

Powershell and Task Scheduler - Trigger script if file directory has not changed since last 30 minutes

$
0
0

I've following code to trigger $powershell_code_to_run when file location is not updated for last 30 mins. However, Script is not triggering Start-Process 'C:\windows\system32\mspaint.exe' or Start-Process 'C:\windows\system32\calc.exe'.

My $task variable is coming blank. Not sure if that's an issue

    $powershell_code_to_run = {    # ALL CODE TO RUN GOES HERE    $DIR = "C:\Scripts\ASA"        Write-Host "Start"    $LastWriteTime = (Get-Item $Dir).LastWriteTime    IF ($LastWriteTime -lt (Get-Date).AddMinutes(-30)) {        Start-Process 'C:\windows\system32\calc.exe'    } ELSE {        Start-Process 'C:\windows\system32\mspaint.exe'    }    # AND END HERE.}# Base64 encode code to run.$encodedCommand = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($powershell_code_to_run.ToString()))$encodedCommand# Action, using EncodedCommand removes the need to escape quotes etc.$action = New-ScheduledTaskAction -Execute 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' -Argument "-WindowStyle Hidden -EncodedCommand $encodedCommand"$action# Task trigger                                  Start :00 next hour                             Repeat every 30 minutes, repeat forever$triggers = New-ScheduledTaskTrigger -Once -At ((Get-Date)) -RepetitionInterval (New-TimeSpan -Minutes 30)# $triggers = New-ScheduledTaskTrigger -Once -At ([datetime]::Now.AddMinutes(1)) -RepetitionInterval (New-TimeSpan -Minutes 2)Write-Host "Triggers"$triggers# Settings for the task.$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable$settings# Other settings$principal = New-ScheduledTaskPrincipal -RunLevel Highest -UserId "LOCALSERVICE" -LogonType ServiceAccount$principal# Name of the task$taskName = 'Check folder for changes'$taskName# The actual task object$task = New-ScheduledTask -Action $action -Settings $settings -Trigger $triggers -Description 'Check a folder if there has been any changes in the last 30 minutes.' -Principal $principal$task# Remove the old taskUnregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue#  Create newRegister-ScheduledTask -TaskName $taskName -InputObject $task -TaskPath '\'

Viewing all articles
Browse latest Browse all 122

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>