Hack 35 Put a Logoff Icon on the Desktop

figs/beginner.gif figs/hack35.gif

Here's a script that will enable users to safely reboot their machines when necessary.

Occasionally, users need a way to reboot their machines when applications hang or updates have been installed. Rather than give users instructions about how to do this properly, it would be nice if a user could instead simply click on an icon that would log them off properly and reboot their machine in a way that does not endanger their work.

That's what this script is about?allowing your users to safely reboot their machines from an icon on their desktops. This VBScript prompts the user to make sure he has saved his data, then logs the user off and automatically reboots. This is quite handy when you push updates via SMS but suppress the reboot.

The Code

Just type the following script into Notepad (with Word Wrap disabled) and save it with a .vbs extension as LogoffIcon.vbs:

Set OpSysSet = GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}" & _

"//./root/cimv2").ExecQuery("SELECT * FROM " & _

"Win32_OperatingSystem WHERE Primary = true")



ianswer = MsgBox("Did you save your data first?"+vbLf++vbLf+ " LOGOFF?", _

vbCritical + vbYesNo, _

"Logoff?")



If ianswer = vbYes Then 'If OK, shut down



For Each OpSys In OpSysSet

outParam = OpSys.Reboot



If err.number <> 0 Then

WScript.echo "Error number: " & Err.Number & _ 

vbNewLine & _

"Description: " & Err.Description

End If



Next 



Else ' user selected cancel

MsgBox "Logoff Aborted", , "Logoff Aborted"



End If

Copy the script to a folder on the user's machine and create a shortcut to the folder on his desktop. Then, when the user needs to reboot his machine, he can double-click on the shortcut and a dialog box (see Figure 3-7) will suggest that he save his work before logging off.

Figure 3-7. Logging off and rebooting
figs/wsh_0307.gif

Once he saves his work and clicks OK, he is logged off and his computer shuts down and restarts.

?Chuck Young