Created
May 3, 2024 17:24
-
-
Save TiloGit/e2cf398fcc0cae1b3d61a87a8abed692 to your computer and use it in GitHub Desktop.
win task scheduler powershell direct command (no script)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##some examples how to run PS direct command in win task scheduler | |
##run in admin shell | |
##simple style | |
$Trigger = New-ScheduledTaskTrigger -Daily -At "10:15pm" # Specify the trigger settings | |
$User = "NT AUTHORITY\SYSTEM" # Specify the account to run the script | |
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument '-Command Get-ChildItem C:\myapp\config\tmp -Recurse | Where LastWriteTime -lt (Get-Date).AddDays(-2) | Remove-Item -Recurse -Force 2>&1 > C:\myapp\logs\ps-script-out.log' # Specify what program to run and with its parameters | |
Register-ScheduledTask -TaskName "myappcleanup-tmp-dir1" -Description "myapp cleanup of tmp directory" -Trigger $Trigger -User $User -Action $Action #consider -RunLevel Highest # Specify the name of the task | |
##end | |
##base64 way | |
$command = '-Command Get-ChildItem C:\myapp\config\tmp -Recurse | Where LastWriteTime -lt (Get-Date).AddDays(-2) | Remove-Item -Recurse -Force 2>&1 > C:\myapp\logs\ps-script-out.log' | |
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command) | |
$encodedCommand = [Convert]::ToBase64String($bytes) | |
$Trigger = New-ScheduledTaskTrigger -Daily -At "10:15pm" # Specify the trigger settings | |
$User = "NT AUTHORITY\SYSTEM" # Specify the account to run the script | |
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-NoProfile -EncodedCommand $encodedCommand" # Specify what program to run and with its parameters | |
Register-ScheduledTask -TaskName "myappcleanup-tmp-dir2" -Description "myapp cleanup of tmp directory" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest # Specify the name of the task | |
##base64 end | |
##ps job style, create a Win Task scheduler with a wrapper. seems odd. | |
$PSTrigger = New-JobTrigger -Daily -At "10:15pm" | |
Register-ScheduledJob -Name "myappcleanup-tmp-dir3" -Trigger $PSTrigger -ScriptBlock { | |
Get-ChildItem C:\myapp\config\tmp -Recurse | Where LastWriteTime -lt (Get-Date).AddDays(-2) | Remove-Item | |
} | |
##check job | |
Get-ScheduledJob | |
##delete with | |
Get-ScheduledJob myappcleanup-tmp-dir3 | Unregister-ScheduledJob |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Register-ScheduledJob creates a Win Schedule Task with that parameter:
location of an xml file:
C:\Users\tilos\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs