Reputation: 424
I want to create a function that displays a message for the user when windows start again after a shutdown.
It is used together with the shutdown command shutdown \s \hybrid
Heres my attempt with the help of AI
import os
def leave_message_on_startup(message):
script_content = f"""
import pymsgbox
message = "{message}"
pymsgbox.alert(message, "Startup Message")
"""
dirname = os.path.dirname
script_path = f"{dirname(dirname(dirname(__file__)))}\\temp\\DisplayMessageOnStartup.pyw"
os.makedirs("temp", exist_ok=True)
with open(script_path, "w+") as script_file:
script_file.write(script_content)
create_task_command = f'schtasks /create /tn "{task_name}" /tr "py {script_path}" /sc onstart /f'
os.system(create_task_command)
def trigger_task(task_name):
trigger_task_command = f'schtasks /run /tn "{task_name}"'
os.system(trigger_task_command)
task_name = "DisplayMessageOnStartup"
message = "Sample message"
leave_message_on_startup(message)
trigger_task(task_name)
After running the code, I double-clicked on the created script in File Explorer and it worked.
Even though the script creation was successful, the task creation seems to have failed.
I can't find the problem.
Please enlighten me on ways to achieve notifications after windows shutdown.
Upvotes: 0
Views: 37
Reputation: 424
Final working version:
import re
import os
import ctypes
def get_startup_folder():
CSIDL_STARTUP = 0x0007
SHGFP_TYPE_CURRENT = 0 # Get current, not default value
buf = ctypes.create_unicode_buffer(260) # Maximum path length
ctypes.windll.shell32.SHGetFolderPathW(None, CSIDL_STARTUP, None, SHGFP_TYPE_CURRENT, buf)
return buf.value
def clean_message(text):
"""Escape special characters for VBScript message content"""
text = text.replace('\\', '\\\\')
text = text.replace('"', '""')
text = text.replace("\n", "\" & vbCrLf & \"")
return text
def leave_notif_on_login(message, title="Python"):
"""
Creates a VBScript in the Startup folder to display
a notification at login. Files will self-delete after execution.
"""
message = clean_message(message)
title = clean_message(title)
# Get Windows Startup folder path
startup_folder = get_startup_folder()
task_name = re.sub(r'[^a-zA-Z0-9-]', '_', title)
# Create path for the VBScript file
vbs_path = os.path.join(startup_folder, f"{task_name}.vbs")
# VBScript content for message display
vbs_content = f'''
Set WshShell = CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")
' Create the PowerShell script file
psScriptPath = FSO.GetSpecialFolder(2) & "\\notification.ps1"
psScriptContent = "[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]" & vbCrLf & _
"$Template = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastImageAndText02)" & vbCrLf & _
"$ToastXml = $Template" & vbCrLf & _
"$ToastXml.GetElementsByTagName('text')[0].AppendChild($ToastXml.CreateTextNode(""{message}""))" & vbCrLf & _
"$Toast = [Windows.UI.Notifications.ToastNotification]::new($ToastXml)" & vbCrLf & _
"$Notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(""{title}"")" & vbCrLf & _
"$Notifier.Show($Toast)"
Set psScriptFile = FSO.CreateTextFile(psScriptPath, True)
psScriptFile.WriteLine psScriptContent
psScriptFile.Close
' Run the PowerShell script
WshShell.Run "powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & psScriptPath & """", 0, True
' Delete the PowerShell script file
FSO.DeleteFile psScriptPath, True
FSO.DeleteFile WScript.ScriptFullName, True
'''
with open(vbs_path, "w", encoding="utf-8") as vbs_file:
vbs_file.write(vbs_content)
return vbs_path
Upvotes: 0
Reputation: 26
Schtasks is assuming that Python is in %systemroot%\System32
(C:\Windows\System32
).
Replace py
with the full path to Python.
Upvotes: 1