Search This Blog

Friday, October 9, 2009

OLKAway Now With Vista support

Long overdue update.

Added Vista support, removed old AutoIT declarations, and set the temp folder to be recreated after deletion to avoid random errors.

#NoTrayIcon
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_outfile=OLKaway.exe
#AutoIt3Wrapper_Compression=4
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#cs
    This script will delete the Outlook temp folder under
    c:\documents and settings\%username%\local settings\temporary internet files\OLKxxx (Windows XP/2000)
    or 
    C:\Users\%username%\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook (Windows Vista)
    It will check for the presense of the OutlookSecureTempFolder entry in the registry
    starting with Outlook 2007, all the way to Outlook 2000 working backwards.
    Once found, it will delete the contents.
    /install option will add a shortcut to the startup folder.
    /uninstall option will delete the shortcut.
    no option will just execute the removal without installing.
    created 01/07/2008
    updates 10/09/2009
        Added Vista support
        Removed old AutoIT declarations
        Corrected random Outlook issues due to the temp folder not being recreated, by creating it manually after each delete.
    
    ab@nyitsupport.com
#ce
 
dim $InstallPath
$InstallPath = "C:\Program Files\NYITSupport\OLKaway\"
 
Select
    case @OSVersion = "WIN_VISTA"
        #requireadmin
        Call ("StartSequence")
    case @OSVersion = "WIN_XP"
        Call ("StartSequence")
    case @OSVersion = "WIN_2000"
        $ver = RegRead("HKLM\SYSTEM\CurrentControlSet\Control\ProductOptions", "ProductType")
        If $ver = "ServerNT" then Exit
        Call ("StartSequence")
    case Else
        Exit
EndSelect    
    
Func StartSequence()
    if $CmdLine[$CmdLine[0]] = "" then 
        call ("CleanUp")
    Else
        Select
            case $CmdLine [1] = "/uninstall"
                if not IsAdmin() then Exit
                call ("Uninstall")
                
            case $CmdLine [1] = "/install" 
                if not IsAdmin() then Exit
                if FileExists($InstallPath) then Exit
                Call ("Install")
        
            case Else
                Exit
                
        EndSelect
    EndIf
EndFunc
 
func CleanUp()
    $OSTF = RegRead("HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Outlook\Security", "OutlookSecureTempFolder") ; Outlook 2007
    if @error then $OSTF = RegRead("HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Outlook\Security\", "OutlookSecureTempFolder") ; Outlook 2003
    if @error then $OSTF = RegRead("HKEY_CURRENT_USER\Software\Microsoft\Office\10.0\Outlook\Security", "OutlookSecureTempFolder") ; Outlook XP
    if @error then $OSTF = RegRead("HKEY_CURRENT_USER\Software\Microsoft\Office\9.0\Outlook\Security", "OutlookSecureTempFolder") ; Outlook 2000
    DirRemove($OSTF,1)
    DirCreate($OSTF)
EndFunc
 
Func Install()
    FileCopy (@ScriptFullPath, $InstallPath,8)
    ShellExecute("cacls.exe", '"' & StringLeft($InstallPath, StringLen($InstallPath)-1) & '" /e /c /g BUILTIN\Users:F')
    FileCreateShortcut($InstallPath &; "OLKaway.exe", @StartupCommonDir & "\NYITSUPPORT OLKaway.lnk", $InstallPath, "", "NYITSUPPORT OLKaway")
    call ("CleanUp")
EndFunc
 
Func Uninstall()
    FileDelete (@StartupCommonDir &; "\NYITSUPPORT OLKaway.lnk")
    DirRemove($InstallPath,1)
EndFunc

Tuesday, July 14, 2009

WSUS Problems On Cloned Machines

I ran into an interesting issue the other day. A machine registered in WSUS would appear and then dissapear from the WSUS 3 SP1 console.

Found the solution to the problem on the following links:

http://blog.netnerds.net/2006/12/wsus-force-registration-of-clients-that-are-not-showing-up/ – best source

https://www.experts-exchange.com/questions/23550840/Computers-disappearing-from-WSUS.html

Here is a script that will run only once if completed successfully. It will also write a log in either case to a subfolder where it ran from with a computer name in the file name.

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_outfile=WSUSFix.exe
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#cs
    WSUSFix
        This application will repair WSUS issues that may have been caused by the machine being imaged.
        
        Referrenced from:
            http://www.wsuswiki.com/ClientFAQ
            http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Server/2003_Server/Q_23550840.html
            http://blog.netnerds.net/2006/12/wsus-force-registration-of-clients-that-are-not-showing-up/
    Alex Belenkiy
    ab@nyitsupport.com
    07/15/2009
#ce
 
If Not IsAdmin() then Exit ; check for admin rights
if @OSVersion <> "WIN_XP" then Exit ; Only install on Windows XP
 
if FileExists("c:\windows\WSUS\WSUSFixComplete.txt") then Exit
 
dim $error, $File, $log, $logText
 
$command = RunWait(@ComSpec & " /c " & "net stop wuauserv")
if @error then 
    call("Logger", "net stop wuauserv FAILED")
    $error = 1
Else
    call("Logger", "net stop wuauserv SUCCESSFUL")
EndIf
 
Call("RegFix", "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate", "AccountDomainSid") 
Call("RegFix", "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate", "PingID") 
Call("RegFix", "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate", "SusClientId") 
Call("RegFix", "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update", "LastWaitTimeout")
Call("RegFix", "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update", "DetectionStartTime")
Call("RegFix", "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update", "NextDetectionTime")
Call("RegFix", "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update", "AUState")
 
$command = RunWait(@ComSpec & " /c " & "net start wuauserv")
if @error then 
    call("Logger", "net start wuauserv FAILED")
    $error = 1
Else
    call("Logger", "net start wuauserv SUCCESSFUL")
EndIf
 
$command = RunWait(@ComSpec & " /c " & "wuauclt /resetauthorization /detectnow")
if @error then 
    call("Logger", "wuauclt /resetauthorization /detectnow FAILED")
    $error = 1
Else
    call("Logger", "wuauclt /resetauthorization /detectnow SUCCESSFUL")
EndIf
 
if $error <> 1 then ; install completed successfully don't run again.
    $File = FileOpen("c:\windows\WSUS\WSUSFixComplete.txt",9)
    call ("Logger", "WSUS Fix completed successfully")
Else ; install did not complete successfully, write a log and allow for another try
    call ("Logger", "WSUS Fix encountered errors. Will try again at next startup.")
EndIf
 
Func Logger($logText) ; write a log
    $log = FileOpen(@ScriptDir & "\Logs\" & @ComputerName & ".log", 9)
    if not @error Then
        FileWriteLine($log, @CRLF & $logText & " - " & @MON & "/" & @MDAY & "/" & @YEAR & " - " & @HOUR & ":" & @MIN)
        FileClose($log)
    EndIf
EndFunc
 
Func RegFix($RegKey, $RegVal)
    $Command = RegRead($RegKey, $RegVal)
    if not @error Then
        call("Logger", "RegRead " & $RegKey & " " & $RegVal & " " & "LOCATED")
        $Command = RegDelete($RegKey, $RegVal)
        if @error then 
            $error = 1
            call("Logger", "RegDelete " & $RegKey & " " & $RegVal & " " & "FAILED")
        Else
            call("Logger", "RegDelete " & $RegKey & " " & $RegVal & " " & "SUCCESSFUL")
        EndIf
    Else
        call("Logger", "REGREAD " & $RegKey & " " & $RegVal & " " & "NOT FOUND")
    EndIf
EndFunc

Wednesday, March 18, 2009

Serial Number Retriever

Yet another serial number generator. Ported from a vbscript found online.
Just feed a machine name to the script to get an output with a serial number into a csv file.
You can also feed a file with all computer names on separate lines. If executed with no options, the current computer info is returned.
If there is no input, the local machine will be used.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_outfile=SerialNumber.exe
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#cs
	Yet another serial number generator. Ported from a vbscript found online.
	Just feed a machine name to the script to get an output with a serial number into a csv file.
	You can also feed a file with all computer names on separate lines. If executed with no options, the current computer info is returned.
	If there is no input, the local machine will be used.
	
	Alex Belenkiy
	09/24/08


#ce
#include <array.au3>
#include <file.au3>

dim $strComputer, $ComputersArray

$OutputFile = FileOpen("ServiceTag " & @MON & "-" & @MDAY & "-" & @YEAR & ".csv", 10)
FileWriteLine($OutputFile, "Machine Name, Manufacturer, Model Number, Serial Number, Part Number, SMBIOSAssetTag, OtherIdentifyingInfo")
If $CmdLine[0] = 0 Then 
	$objWMIService = ObjGet("winmgmts:" & "{impersonationLevel=impersonate}!\\" & @ComputerName & "\root\cimv2")
	$colSMBIOS = $objWMIService.ExecQuery ("Select * from Win32_SystemEnclosure")	
	For $objSMBIOS in $colSMBIOS
		FileWriteLine($OutputFile, @ComputerName & "," & $objSMBIOS.Manufacturer & "," & $objSMBIOS.Model & "," & $objSMBIOS.SerialNumber & "," & $objSMBIOS.PartNumber & $objSMBIOS.SMBIOSAssetTag & $objSMBIOS.OtherIdentifyingInfo)
	Next
Else
	if not FileExists($CmdLine[1]) Then
		$objWMIService = ObjGet("winmgmts:" & "{impersonationLevel=impersonate}!\\" & $CmdLine[1] & "\root\cimv2")
		if not @error Then
			$colSMBIOS = $objWMIService.ExecQuery ("Select * from Win32_SystemEnclosure")	
			For $objSMBIOS in $colSMBIOS
				FileWriteLine($OutputFile, $CmdLine[1] & "," & $objSMBIOS.Manufacturer & "," & $objSMBIOS.Model & "," & $objSMBIOS.SerialNumber & "," & $objSMBIOS.PartNumber & $objSMBIOS.SMBIOSAssetTag & $objSMBIOS.OtherIdentifyingInfo)
			Next
		EndIf
	Else
		_FileReadToArray($CmdLine[1],$ComputersArray)
		For $a = 1 to $ComputersArray[0]
			$objWMIService = ObjGet("winmgmts:" & "{impersonationLevel=impersonate}!\\" & $ComputersArray[$a] & "\root\cimv2")
			if not @error Then
				$colSMBIOS = $objWMIService.ExecQuery ("Select * from Win32_SystemEnclosure")	
				For $objSMBIOS in $colSMBIOS
					FileWriteLine($OutputFile, $ComputersArray[$a] & "," & $objSMBIOS.Manufacturer & "," & $objSMBIOS.Model & "," & $objSMBIOS.SerialNumber & "," & $objSMBIOS.PartNumber & $objSMBIOS.SMBIOSAssetTag & $objSMBIOS.OtherIdentifyingInfo)
				Next
			EndIf
		Next
	EndIf
EndIf
	
		
FileClose($OutputFile)

Folder Duplicator

This script lets you choose a folder and copy it to every subfolder in the chosen destination.

Created it with a specific purpose of updating 200+ Citrix server user folders.

A catalog configuration file for Document Locator had to be placed under c:\documents and settings\username\application data\ColumbiaSoft

I created a folder called Application Data, then ColumbiaSoft under it, and placed the catalog there. Ran the script, selected the new Application Data folder, and chose c:\documents and settings as the destination. The script merged the existing application data with the new one under each username folder. Please pay attention as the script will overwrite existing files without prompting.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_outfile=FolderDuplicator.exe
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#cs
    FolderDuplicator
    03/11/2009
    Alex Belenkiy - ab@nyitsupport.com
    
    This script will duplicate the source directory into every subfolder of the destination, 
    overwriting existing files in it's path.
    Use with caution!!!
    
#ce
 
#Include <File.au3>
 
$Warning = MsgBox(1, "Folder Duplicator", "This application will duplicate the selected" & @CRLF & "source folder into all destination subfolders" & @CRLF & "All existing files will be overwritten")
if $Warning = 2 then Exit
$source = FileSelectFolder("Select Folder to Copy", "")
if @error Then 
    MsgBox(0, "Folder Duplicator", "Invalid Source Folder")
    Exit
EndIf
$destination = FileSelectFolder("Select Destination Folder", "")
if @error then 
    MsgBox (0, "Folder Duplicator", "Invalid Destination Folder")
    Exit
EndIf
 
$sourceSplit = StringSplit($source, "\")
If StringRight($destination, 1) <> "\" Then $destination &= "\"
$FileList = _FileListToArray ($destination, "*.*", 2)
if @error then Exit
 
for $a = 1 to $FileList [0]
    DirCopy ($source, $destination & $FileList[$a] & "\" & $sourceSplit[$sourceSplit[0]], 1)
    
    if @error then
        MsgBox(0, "Folder Duplicator", "Error encountered while copying folders")
        Exit
    EndIf
Next
MsgBox(0,"Folder Duplicator", "Done!!!")

Shutdown 2.0

As it turned out, my first shutdown script did not work unless the user is logged onto the machine.

This new one works without anyone being logged on. It relies on the service.au3 file. It was downloaded from an AutoIt forum http://www.autoitscript.com/forum/index.php?showtopic=80201

Service.au3:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#AutoIt3Wrapper_Change2CUI=y
#include-once
#include<WinApi.au3>
 
#region Defined Variables and Constants
Global $STANDARD_RIGHTS_REQUIRED = 0x000F0000
 
; Service Control Manager access types
Global Const $SC_MANAGER_CONNECT = 0x0001
Global Const $SC_MANAGER_CREATE_SERVICE = 0x0002
Global Const $SC_MANAGER_ENUMERATE_SERVICE = 0x0004
Global Const $SC_MANAGER_LOCK = 0x0008
Global Const $SC_MANAGER_QUERY_LOCK_STATUS = 0x0010
Global Const $SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020
Global Const $SC_MANAGER_ALL_ACCESS = BitOR($STANDARD_RIGHTS_REQUIRED, $SC_MANAGER_CONNECT, $SC_MANAGER_CREATE_SERVICE, $SC_MANAGER_ENUMERATE_SERVICE, $SC_MANAGER_LOCK, $SC_MANAGER_QUERY_LOCK_STATUS, $SC_MANAGER_MODIFY_BOOT_CONFIG)
 
; Service Access Types
Global Const  $SERVICE_QUERY_CONFIG = 0x0001
Global Const $SERVICE_CHANGE_CONFIG = 0x0002
Global Const $SERVICE_QUERY_STATUS = 0x0004
Global Const $SERVICE_ENUMERATE_DEPENDENTS = 0x0008
Global Const $SERVICE_START = 0x0010
Global Const $SERVICE_STOP = 0x0020
Global Const $SERVICE_PAUSE_CONTINUE = 0x0040
Global Const $SERVICE_INTERROGATE = 0x0080
Global Const $SERVICE_USER_DEFINED_CONTROL = 0x0100
Global $SERVICE_ALL_ACCESS = BitOR($STANDARD_RIGHTS_REQUIRED, $SERVICE_QUERY_CONFIG, $SERVICE_CHANGE_CONFIG, $SERVICE_QUERY_STATUS, $SERVICE_ENUMERATE_DEPENDENTS, $SERVICE_START, $SERVICE_STOP, $SERVICE_PAUSE_CONTINUE, $SERVICE_INTERROGATE, $SERVICE_USER_DEFINED_CONTROL)
 
; Service Controls
Global Const $SERVICE_CONTROL_STOP = 0x00000001
Global Const $SERVICE_CONTROL_PAUSE = 0x00000002
Global Const $SERVICE_CONTROL_CONTINUE = 0x00000003
Global Const $SERVICE_CONTROL_INTERROGATE = 0x00000004
Global Const $SERVICE_CONTROL_SHUTDOWN = 0x00000005
Global Const $SERVICE_CONTROL_PARAMCHANGE = 0x00000006
Global Const $SERVICE_CONTROL_NETBINDADD = 0x00000007
Global Const $SERVICE_CONTROL_NETBINDREMOVE = 0x00000008
Global Const $SERVICE_CONTROL_NETBINDENABLE = 0x00000009
Global Const $SERVICE_CONTROL_NETBINDDISABLE = 0x0000000A
Global Const $SERVICE_CONTROL_DEVICEEVENT = 0x0000000B
Global Const $SERVICE_CONTROL_HARDWAREPROFILECHANGE = 0x0000000C
Global Const $SERVICE_CONTROL_POWEREVENT = 0x0000000D
Global Const $SERVICE_CONTROL_SESSIONCHANGE = 0x0000000E
 
; Service Types
Global Const $SERVICE_KERNEL_DRIVER = 0x00000001
Global Const $SERVICE_FILE_SYSTEM_DRIVER = 0x00000002
Global Const $SERVICE_ADAPTER = 0x00000004
Global Const $SERVICE_RECOGNIZER_DRIVER = 0x00000008
Global Const $SERVICE_DRIVER = BitOR($SERVICE_KERNEL_DRIVER, $SERVICE_FILE_SYSTEM_DRIVER, $SERVICE_RECOGNIZER_DRIVER)
Global Const $SERVICE_WIN32_OWN_PROCESS = 0x00000010
Global Const $SERVICE_WIN32_SHARE_PROCESS = 0x00000020
Global Const $SERVICE_WIN32 = BitOR($SERVICE_WIN32_OWN_PROCESS, $SERVICE_WIN32_SHARE_PROCESS)
Global Const $SERVICE_INTERACTIVE_PROCESS = 0x00000100
Global Const $SERVICE_TYPE_ALL = BitOR($SERVICE_WIN32, $SERVICE_ADAPTER, $SERVICE_DRIVER, $SERVICE_INTERACTIVE_PROCESS)
 
; Service Start Types
Global Const $SERVICE_BOOT_START = 0x00000000
Global Const $SERVICE_SYSTEM_START = 0x00000001
Global Const $SERVICE_AUTO_START = 0x00000002
Global Const $SERVICE_DEMAND_START = 0x00000003
Global Const $SERVICE_DISABLED = 0x00000004
 
; Service Error Control
Global Const $SERVICE_ERROR_IGNORE = 0x00000000
Global Const $SERVICE_ERROR_NORMAL = 0x00000001
Global Const $SERVICE_ERROR_SEVERE = 0x00000002
Global Const $SERVICE_ERROR_CRITICAL = 0x00000003
Global Const $SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 0x20
Global Const $SERVICE_ACCEPT_NETBINDCHANGE = 0x10
Global Const $SERVICE_ACCEPT_PARAMCHANGE = 0x8
Global Const $SERVICE_ACCEPT_PAUSE_CONTINUE = 0x2
Global Const $SERVICE_ACCEPT_POWEREVENT = 0x40
Global Const $SERVICE_ACCEPT_SESSIONCHANGE = 0x80
Global Const $SERVICE_ACCEPT_PRESHUTDOWN = 0x100
Global Const $SERVICE_ACCEPT_SHUTDOWN = 0x4
Global Const $SERVICE_ACCEPT_STOP = 0x1
Global Const $SERVICE_ACTIVE = 0x1
Global Const $SERVICE_INACTIVE = 0x2
Global Const $SERVICE_PAUSE_PENDING = 0x6
Global Const $SERVICE_PAUSED = 0x7
Global Const $SERVICE_RUNNING = 0x4
Global Const $SERVICE_START_PENDING = 0x2
Global Const $SERVICE_STOP_PENDING = 0x3
Global Const $SERVICE_STOPPED = 0x1
Global Const $SERVICE_CONTINUE_PENDING = 0x5
 
;
Global $tServiceName,$tServiceCtrl,$tServiceMain,$service_debug_mode = False
Global $tService_Status = DllStructCreate("dword dwServiceType;dword dwCurrentState;dword dwControlsAccepted;dword dwWin32ExitCode;dword dwServiceSpecificExitCode;dword dwCheckPoint;dword dwWaitHint")
Global $tService_Status_handle
Global Const $NO_ERROR = 0
Global Const $NTSL_LOOP_WAIT = -1
Global $service_stop_event
Global $NTSL_ERROR_SERVICE_STATUS = 2
Global Const $WAIT_OBJECT_0 = 0x0
#endregion
 
#region Functions
Func _CreateService($sComputerName, $sServiceName, $sDisplayName, $sBinaryPath, $sServiceUser = "LocalSystem", $sPassword = "", $nServiceType = 0x00000010, $nStartType = 0x00000002, $nErrorType = 0x00000001, $nDesiredAccess = 0x000f01ff, $sLoadOrderGroup = "")
    Local $hAdvapi32
    Local $hKernel32
    Local $arRet
    Local $hSC
    Local $lError = -1   
    $hAdvapi32 = DllOpen("advapi32.dll")
    If $hAdvapi32 = -1 Then Return 0
    $hKernel32 = DllOpen("kernel32.dll")
    If $hKernel32 = -1 Then Return 0
    $arRet = DllCall($hAdvapi32, "long", "OpenSCManager", "str", $sComputerName, "str", "ServicesActive", "long", $SC_MANAGER_ALL_ACCESS)
    If $arRet[0] = 0 Then
        $arRet = DllCall($hKernel32, "long", "GetLastError")
        $lError = $arRet[0]
    Else
        $hSC = $arRet[0]
        $arRet = DllCall($hAdvapi32, "long", "OpenService", "long", $hSC, "str", $sServiceName, "long", $SERVICE_INTERROGATE)
        If $arRet[0] = 0 Then
            $arRet = DllCall($hAdvapi32, "long", "CreateService", "long", $hSC, "str", $sServiceName, "str", $sDisplayName, "long", $nDesiredAccess, "long", $nServiceType, "long", $nStartType, "long", $nErrorType, "str", $sBinaryPath, "str", $sLoadOrderGroup, "ptr", 0, "str", "", "str", $sServiceUser, "str", $sPassword)
            If $arRet[0] = 0 Then            
                $arRet = DllCall($hKernel32, "long", "GetLastError")
                $lError = $arRet[0]
            Else
                DllCall($hAdvapi32, "int", "CloseServiceHandle", "long", $arRet[0])
            EndIf
        Else
            DllCall($hAdvapi32, "int", "CloseServiceHandle", "long", $arRet[0])
        EndIf      
        DllCall($hAdvapi32, "int", "CloseServiceHandle", "long", $hSC)
    EndIf
    DllClose($hAdvapi32)
    DllClose($hKernel32)   
    If $lError <> -1 Then 
        SetError($lError)
        Return 0
    EndIf
    Return 1
EndFunc
 
Func _DeleteService($sComputerName, $sServiceName)
    Local $hAdvapi32
    Local $hKernel32
    Local $arRet
    Local $hSC
    Local $hService
    Local $lError = -1   
 
    $hAdvapi32 = DllOpen("advapi32.dll")
    If $hAdvapi32 = -1 Then Return 0
    $hKernel32 = DllOpen("kernel32.dll")
    If $hKernel32 = -1 Then Return 0
    $arRet = DllCall($hAdvapi32, "long", "OpenSCManager", "str", $sComputerName, "str", "ServicesActive", "long", $SC_MANAGER_ALL_ACCESS)
    If $arRet[0] = 0 Then
        $arRet = DllCall($hKernel32, "long", "GetLastError")
        $lError = $arRet[0]
    Else
        $hSC = $arRet[0]
        $arRet = DllCall($hAdvapi32, "long", "OpenService", "long", $hSC, "str", $sServiceName, "long", $SERVICE_ALL_ACCESS)
        If $arRet[0] = 0 Then
            $arRet = DllCall($hKernel32, "long", "GetLastError")
            $lError = $arRet[0]
        Else
            $hService = $arRet[0]
            $arRet = DllCall($hAdvapi32, "int", "DeleteService", "long", $hService)
            If $arRet[0] = 0 Then
                $arRet = DllCall($hKernel32, "long", "GetLastError")
                $lError = $arRet[0]
            EndIf
            DllCall($hAdvapi32, "int", "CloseServiceHandle", "long", $hService)
        EndIf
        DllCall($hAdvapi32, "int", "CloseServiceHandle", "long", $hSC)
    EndIf
    DllClose($hAdvapi32)
    DllClose($hKernel32)   
    If $lError <> -1 Then 
        SetError($lError)
        Return 0
    EndIf
    Return 1
EndFunc
 
Func _StopService($sComputerName, $sServiceName)
    Local $hAdvapi32
    Local $hKernel32
    Local $arRet
    Local $hSC
    Local $hService
    Local $lError = -1
 
    $hAdvapi32 = DllOpen("advapi32.dll")
    If $hAdvapi32 = -1 Then Return 0
    $hKernel32 = DllOpen("kernel32.dll")
    If $hKernel32 = -1 Then Return 0
    $arRet = DllCall($hAdvapi32, "long", "OpenSCManager", "str", $sComputerName, "str", "ServicesActive", "long", $SC_MANAGER_CONNECT)
    If $arRet[0] = 0 Then
        $arRet = DllCall($hKernel32, "long", "GetLastError")
        $lError = $arRet[0]
    Else
        $hSC = $arRet[0]
        $arRet = DllCall($hAdvapi32, "long", "OpenService", "long", $hSC, "str", $sServiceName, "long", $SERVICE_STOP)
        If $arRet[0] = 0 Then
            $arRet = DllCall($hKernel32, "long", "GetLastError")
            $lError = $arRet[0]
        Else
            $hService = $arRet[0]
            $arRet = DllCall($hAdvapi32, "int", "ControlService", "long", $hService, "long", $SERVICE_CONTROL_STOP, "str", "")
            If $arRet[0] = 0 Then
                $arRet = DllCall($hKernel32, "long", "GetLastError")
                $lError = $arRet[0]
            EndIf
            DllCall($hAdvapi32, "int", "CloseServiceHandle", "long", $hService)         
        EndIf
        DllCall($hAdvapi32, "int", "CloseServiceHandle", "long", $hSC)
    EndIf
    DllClose($hAdvapi32)
    DllClose($hKernel32)   
    If $lError <> -1 Then 
        SetError($lError)
        Return 0
    EndIf
    Return 1
EndFunc
 
Func _ServiceExists($sComputerName, $sServiceName)
    Local $hAdvapi32
    Local $hKernel32
    Local $arRet
    Local $hSC
    Local $hService
    Local $lError = -1
 
    $hAdvapi32 = DllOpen("advapi32.dll")
    If $hAdvapi32 = -1 Then Return 0
    $hKernel32 = DllOpen("kernel32.dll")
    If $hKernel32 = -1 Then Return 0
    $arRet = DllCall($hAdvapi32, "long", "OpenSCManager", "str", $sComputerName, "str", "ServicesActive", "long", $SC_MANAGER_CONNECT)
    If $arRet[0] = 0 Then
        $arRet = DllCall($hKernel32, "long", "GetLastError")
        $lError = $arRet[0]
    Else
        $hSC = $arRet[0]
        $arRet = DllCall($hAdvapi32, "long", "OpenService", "long", $hSC, "str", $sServiceName, "long", $SERVICE_STOP)
        If $arRet[0] = 0 Then
            $arRet = DllCall($hKernel32, "long", "GetLastError")
            $lError = $arRet[0]    
        EndIf
        DllCall($hAdvapi32, "int", "CloseServiceHandle", "long", $hSC)
    EndIf
    DllClose($hAdvapi32)
    DllClose($hKernel32)   
    If $lError <> -1 Then 
        SetError($lError)
        Return 0
    EndIf
    Return 1
EndFunc
 
Func _Service_Cleanup()
    $service_error = _WinAPI_GetLastError()
    If ($tService_Status_handle) Then _Service_ReportStatus($SERVICE_STOPPED, $service_error, 0);
EndFunc
 
Func _Service_Ctrl($ctrlCode)
    Switch ($ctrlCode)
        Case $SERVICE_CONTROL_PAUSE
            DllStructSetData($tService_Status, "dwCurrentState", $SERVICE_PAUSED)
        Case $SERVICE_CONTROL_CONTINUE
            DllStructSetData($tService_Status, "dwCurrentState", $SERVICE_RUNNING)
        Case $SERVICE_CONTROL_STOP
            _Service_ReportStatus($SERVICE_STOP_PENDING, $NO_ERROR, 0);
            _Service_SetStopEvent();
            _Service_Cleanup()
            Exit
        Case $SERVICE_CONTROL_INTERROGATE
            ;break;
            ; invalid control code
            ;
        Case Else
            ;
    EndSwitch
    _Service_ReportStatus(DllStructGetData($tService_Status, "dwCurrentState"), $NO_ERROR, 0);
EndFunc
 
Func _Service_Halting()
    Return (_WinAPI_WaitForSingleObject($service_stop_event, $NTSL_LOOP_WAIT) == $WAIT_OBJECT_0);
EndFunc
 
Func _Service_Init($sServiceName)    
    $tServiceCtrl = DllCallbackRegister("_Service_Ctrl", "int", "uint")
    $tServiceMain = DllCallbackRegister("_Service_ServiceMain", "int", "int;str")    
    $tdispatchTable = DllStructCreate("ptr[2];ptr[2]")
    $tServiceName = DllStructCreate("char[128]")
    DllStructSetData($tServiceName, 1, $sServiceName)
    DllStructSetData($tdispatchTable, 1, DllStructGetPtr($tServiceName), 1)
    DllStructSetData($tdispatchTable, 1, DllCallbackGetPtr($tServiceMain), 2)
    DllStructSetData($tdispatchTable, 2, 0, 1)
    DllStructSetData($tdispatchTable, 2, 0, 2)
    $ret = DllCall("advapi32.dll", "int", "StartServiceCtrlDispatcher", "ptr", DllStructGetPtr($tdispatchTable))
    ;If $ret[0] = 0 Then MsgBox(0, "", " Error " & _WinAPI_GetLastError() & @CRLF)
EndFunc 
 
Func _Service_ReportStatus($currentState, $exitCode, $waitHint)
    Local $checkPoint = 1;
    Local $rc = True;
    If Not ($service_debug_mode) Then ;when debugging we don't report to the SCM
        If ($currentState == $SERVICE_START_PENDING) Then
            DllStructSetData($tService_Status, "dwControlsAccepted", 0);
        Else
            DllStructSetData($tService_Status, "dwControlsAccepted", $SERVICE_ACCEPT_STOP)
        EndIf
        
        DllStructSetData($tService_Status, "dwCurrentState", $currentState)
        DllStructSetData($tService_Status, "dwWin32ExitCode", $exitCode)
        DllStructSetData($tService_Status, "dwWaitHint", $waitHint)
        If $currentState == $SERVICE_RUNNING Or $currentState == $SERVICE_STOPPED Then
            DllStructSetData($tService_Status, "dwCheckPoint", 0)
        Else
            DllStructSetData($tService_Status, "dwCheckPoint", $checkPoint + 1);
        EndIf
        ; report the status of the service to the service control manager.
        If Not ($rc = _Service_SetServiceStatus($tService_Status_handle, DllStructGetPtr($tService_Status))) Then ConsoleWrite("+ " & $NTSL_ERROR_SERVICE_STATUS & @TAB & _WinAPI_GetLastError() & @CRLF)
    EndIf
    Return ($rc);
EndFunc
 
Func _Service_ServiceMain($iArg, $sArgs)
    $ret = DllCall("advapi32.dll", "hwnd", "RegisterServiceCtrlHandler", "ptr", DllStructGetPtr($tServiceName), "ptr", DllCallbackGetPtr($tServiceCtrl));register service
    If $ret[0] = 0 Then
        MsgBox(0, "Error", _WinAPI_GetLastError())
        Exit
    EndIf
    $tService_Status_handle = $ret[0]
    If Not ($tService_Status_handle) Then
        _Service_Cleanup()
        Return
    EndIf
 
    DllStructSetData($tService_Status, "dwServiceType", $SERVICE_WIN32_OWN_PROCESS)
    DllStructSetData($tService_Status, "dwServiceSpecificExitCode", 0);
    ; report the status to the service control manager.
    If Not (_Service_ReportStatus($SERVICE_START_PENDING, $NO_ERROR, 3000)) Then
        _Service_Cleanup()
        Return
    EndIf
    _Service_Start($iArg, $sArgs);
    _Main()
    Return;
EndFunc
 
Func _Service_SetServiceStatus($hServiceStatus, $lpServiceStatus)
    $ret = DllCall("advapi32.dll", "int", "SetServiceStatus", "hwnd", $hServiceStatus, "ptr", $lpServiceStatus)
    Return $ret[0]
EndFunc
 
Func _Service_SetStopEvent()
    If ($service_stop_event) Then _WinAPI_SetEvent($service_stop_event) 
EndFunc 
 
Func _Service_Start($argc, $argv)
    If Not (_Service_ReportStatus($SERVICE_START_PENDING, $NO_ERROR, 3000)) Then Return
    $service_stop_event = _WinAPI_CreateEvent(0, True, False, 0);
    If Not ($service_stop_event) Then Return;
    ;report the status to the service control manager.
    If Not _Service_ReportStatus($SERVICE_START_PENDING, $NO_ERROR, 3000) Then Return;
    ;report the status to the service control manager.
    If Not _Service_ReportStatus($SERVICE_RUNNING, $NO_ERROR, 0) Then Return;
EndFunc
 
#endregion

Shutdown.au3

 

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#NoTrayIcon
 
#cs
    NYITSUPPORTShutdown 2.0
    This script will shut down a machine on a schedule.
    The program should be launched as a domain computer startup policy as follows
    \\SERVER\SHARE\NYITSUPPORTShutDown.exe /install
    A policy should be put in that adds a registry key "HKEY_LOCAL_MACHINE\SOFTWARE\NYITSUPPORT\Shutdown", "Shutdown"=2300
    The time is specified in a 4 digit military time format (2330 = 11:30 PM)
    /uninstall will remove the application and registry key
    
    Service.au3 was downloaded from http://www.autoitscript.com/forum/index.php?showtopic=80201
 
; Alex Belenkiy ab@nyitsupport.com
; 02/02/2009
#ce
 
AutoItSetOption ("TrayIconHide",1)
#include <Date.au3>
#include <array.au3>
#include <service.au3>
if not IsAdmin() then Exit
 
Dim $InstallPath
Global $sServiceName = "NYITSUPPORTShutdown"
if $CmdLine[0] = "" then Exit
 
$InstallPath = "C:\Program Files\NYITSUPPORT\ShutDown\"
 
Select
    case $CmdLine [1] = "/uninstall"
        if not FileExists($InstallPath) then Exit
        
        call ("Uninstall")
        
    case $CmdLine [1] = "/install" 
        if $CmdLine[0] <> 2 then Exit
        if $CmdLine [2] = "" then Exit
        if not StringIsDigit ($CmdLine[2]) then Exit
        if stringlen($CmdLine[2]) <> 4 then Exit
        if StringLeft($CmdLine[2], 2) > 23 then Exit
        if StringRight($CmdLine[2], 2) >59 then Exit
 
        Call ("Install")
                            
    case $CmdLine [1] = "/NYITSUPPORTShutdown"
        _Service_init($sServiceName)
        
EndSelect
    
Func Install()
    $ShutdownSplit = StringSplit(RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NYITSUPPORTShutdown", "ImagePath"), " ")
    $Shutdown = $ShutdownSplit[$ShutdownSplit[0]]
    if not @error Then
        if $Shutdown = $CmdLine[2] then Exit
        RunWait (@SystemDir & '\net stop "NYITSUPPORT Shutdown"', "")
        FileCopy (@ScriptFullPath, $InstallPath,9)
        $NewShutdown = $ShutdownSplit[1] & " " 
         for $a = 2 to ($ShutdownSplit[0] - 1)
            $NewShutdown = $NewShutdown & $ShutdownSplit[$a] & " "
        Next
        $NewShutdown = $NewShutdown & $CmdLine[2]
        RegWrite("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NYITSUPPORTShutdown", "ImagePath", "REG_EXPAND_SZ", $NewShutdown)
        RunWait (@SystemDir & '\net start "NYITSUPPORT Shutdown"', "")
        Exit
    Else
        FileCopy (@ScriptFullPath, $InstallPath,9)
        $log = FileOpen("\\server\NYITSUPPORT\ShutDown\Logs\" & @ComputerName & ".log",9)
        _CreateService("",$sServiceName, "NYITSUPPORT Shutdown", $InstallPath & "NYITSUPPORTShutdown.exe /NYITSUPPORTShutdown " & $CmdLine[2])
        If @error Then
            FileWriteLine($log, @CRLF & "_CreateService failed - " & @MON & "/" & @MDAY & "/" & @YEAR & " - " & @HOUR & ":" & @MIN)
        EndIf
        FileWriteLine($log, @CRLF & "Installed - " & @MON & "/" & @MDAY & "/" & @YEAR & " - " & @HOUR & ":" & @MIN)
        RunWait (@SystemDir & '\net start "NYITSUPPORT Shutdown"', "")
        FileClose($log)
        Exit        
    EndIf    
 
EndFunc   ;==>InstallService
 
Func Uninstall()
    $log = FileOpen("\\server\NYITSUPPORT\ShutDown\Logs\" & @ComputerName & ".log",9)
    _StopService(".", $sServiceName)
    if @error then 
        FileWriteLine($log, @CRLF & "_StopService failed - " & @MON & "/" & @MDAY & "/" & @YEAR & " - " & @HOUR & ":" & @MIN)
    EndIf
    _DeleteService(".", $sServiceName)
    if @error then 
        FileWriteLine($log, @CRLF & "_DeleteService failed - " & @MON & "/" & @MDAY & "/" & @YEAR & " - " & @HOUR & ":" & @MIN)
    EndIf
    DirRemove($InstallPath,1)
    FileWriteLine($log, @CRLF & "Uninstalled - " & @MON & "/" & @MDAY & "/" & @YEAR & " - " & @HOUR & ":" & @MIN)
    FileClose($log)
    Exit
EndFunc
 
Func _main()
    if $CmdLine[0] <> 2 then Exit
    if $CmdLine [2] = "" then Exit
    if not StringIsDigit ($CmdLine[2]) then Exit
    if stringlen($CmdLine[2]) <> 4 then Exit
    if StringLeft($CmdLine[2], 2) > 23 then Exit
    if StringRight($CmdLine[2], 2) >59 then Exit
    $H = StringLeft($CmdLine[2],2)
    $M = StringRight($CmdLine[2],2)
 
    While 1
        if @MIN = $M And @HOUR = $H then 
            Run (@SystemDir & '\shutdown.exe /s /f /t 300 /c "Scheduled shutdown in progress. ' & @CRLF & 'Please close all open applications and save your data.' & @crlf & 'The system will shut down in 5 minutes."', "")
            Exit
        EndIf
        sleep (60000)
    WEnd
EndFunc
 

Enjoy!!!