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 task Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue # Create new Register-ScheduledTask -TaskName $taskName -InputObject $task -TaskPath '\' https://stackoverflow.com/questions/65729944/powershell-and-task-scheduler-trigger-script-if-file-directory-has-not-changed January 15, 2021 at 11:07AM
没有评论:
发表评论