i have saved a script at path : C:\Test\RealScript.ps1
with the following content
Add-Type -AssemblyName PresentationFramework
# Create the prompt
$messageBoxText = "Do you want to restart the PC?"
$caption = "Restart Confirmation"
$buttonType = [System.Windows.MessageBoxButton]::YesNo
$iconType = [System.Windows.MessageBoxImage]::Warning
# Show the message box
$result = [System.Windows.MessageBox]::Show($messageBoxText, $caption, $buttonType, $iconType)
# Check the user's response
if ($result -eq [System.Windows.MessageBoxResult]::Yes) {
# Force restart the PC
Restart-Computer -Force
}
And i want to execute this script every "x" mins, right now i am gonna choose 1 minute ,
# Define variables
$scriptPath = "C:\Test\RealScript.ps1"
$taskName = "RunScriptEveryMinute"
$taskDescription = "This task runs the specified script every minute."
# Create the action for the task
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -File `"$scriptPath`""
# Create the trigger for the task to run every 1 minute with a reasonable repetition duration
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration (New-TimeSpan -Days 365)
# Create task settings to run the task whether the user is logged on or not
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances Parallel
# Register the scheduled task
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $taskName -Description $taskDescription -Settings $settings -User "SYSTEM"
The respective task was formed in Task Scheduler but the script wasnt executed and nothing was prompted onto my device
Apparently you can use the quser
command to fetch the user dynamically and create a scheduled task accordingly. However, this has its own limitation as quser
is not supported in every Windows version.
The script above needs to render a window by executing that with a scheduled task. Since its a UI element that needs to get rendered the scheduled task is created for the active user using the system. One way to dynamically fetch that is to use the quser command (heres some documentation) once fetched in the script.
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $taskName -Description $taskDescription -Settings $settings -User "ReplaceWithFetchedUsername"
And that Should do it