Search This Blog

Wednesday, March 18, 2009

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!!!

Monday, October 6, 2008

Outlook CSV Import

OutlookCSVImport - Import a CSV file into Outlook. 


Match up the necessary fields and modify the script if needed. Remove or add any additional fields.

Download Microsoft Outlook VBA Language Reference for other properties that were not listed here.

There were 4 properties in an export i originally created this for that do not have a corresponding field in Outlook. I added them as part of the Body field (notes field).

The script will add the excel file into the default Outlook Contacts folder. Something to keep in mind while testing :)

Sort the Excel file by the FileAs field. My export came from http://www.codetwo.com/ Outlook export tool. 


The client this was made for had custom fields that Outlook would not export out. The third party tool did a great job.
Renamed a few of the custom contact fields to what was needed and set the rest to be part of notes.
Outlook's natural import/export function with the "Map Custom Fields" does not work correctly. Quite a few existing Outlook fields,
do not export or import, even while it creates a csv column entry for the field (nickname is one example).
Called Microsoft on this issue. Will see what answer they come up with.

If the program crashes at any point look for the contact that crashed it, i had a field with a #name? in it that caused a crash.

 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
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_outfile=OutlookCSVImport.exe
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#cs
	OutlookCSVImport - Import a CSV file into Outlook.
	Match up the necessary fields and modify the script if needed. Remove or add any additional fields.
	
	Based on http://tinyurl.com/4uce9k
	Download Microsoft Outlook VBA Language Reference for other properties that were not listed here.
	
	There were 4 properties in an export i originally created this for that do not have a corresponding field in Outlook.
	I added them as part of the Body field (notes field).
	
	The script will add the excel file into the default Outlook Contacts folder. Something to keep in mind while testing :)
	
	Sort the Excel file by the FileAs field. My export came from http://www.codetwo.com/ Outlook export tool.
	The client this was made for had custom fields that Outlook would not export out. The third party tool did a great job.
	Renamed a few of the custom contact fields to what was needed and set the rest to be part of notes.
	Outlook's natural import/export function with the "Map Custom Fields" does not work correctly. Quite a few existing Outlook fields,
	do not export or import, even while it creates a csv column entry for the field (nickname is one example).
	Called Microsoft on this issue. Will see what answer they come up with.
	Visit http://nyitsupport.blogspot.com for an update.
	
	If the program crashes at any point look for the contact that crashed it, i had a field with a #name? in it that caused a crash.
		
	Alex Belenkiy 
	ab@nyitsupport.com
	10/06/08
	
#ce


Const $olContactItem = 2

$objOutlook = ObjCreate("Outlook.Application")

$objExcel = ObjCreate("Excel.Application")
$ExcelFile = FileOpenDialog("Please choose an Excel file to open", @WorkingDir, "Excel Files (*.xls;*.xlsx;*.csv)",1)
$objWorkbook = $objExcel.Workbooks.Open($ExcelFile)

$x = 2

Do 
	$objContact = $objOutlook.CreateItem($olContactItem)
	;---------------------------------------------------------------------------------------------
	$objContact.AssistantName = $objExcel.Cells($x,2).Value
	$objContact.AssistantTelephoneNumber = 	$objExcel.Cells($x,3).Value
	$objContact.Body = "Assistant's Email: " & $objExcel.Cells($x,1).Value & @CRLF & "Contact Type: " & $objExcel.Cells($x,13).Value & @CRLF & "Contacts: " & $objExcel.Cells($x,14).Value & @CRLF & "Cross Street: " & $objExcel.Cells($x,15).Value & @CRLF & "Private Number: " & $objExcel.Cells($x,49).Value & @CRLF & @CRLF & @CRLF & $objExcel.Cells($x,4).Value
	$objContact.BusinessAddress = $objExcel.Cells($x,5).Value
	$objContact.BusinessAddressCity = $objExcel.Cells($x,6).Value
	$objContact.BusinessAddressPostalCode = $objExcel.Cells($x,7).Value
	$objContact.BusinessAddressState = $objExcel.Cells($x,8).Value
	$objContact.BusinessAddressStreet = $objExcel.Cells($x,9).Value
	$objContact.Categories = $objExcel.Cells($x,10).Value
	$objContact.CompanyName = $objExcel.Cells($x,11).Value
	$objContact.PrimaryTelephoneNumber = $objExcel.Cells($x,12).Value
	$objContact.Email1Address = $objExcel.Cells($x,16).Value
	$objContact.Email1DisplayName = $objExcel.Cells($x,17).Value
	$objContact.Email2Address = $objExcel.Cells($x,18).Value
	$objContact.Email2DisplayName = $objExcel.Cells($x,19).Value
	$objContact.Email3Address = $objExcel.Cells($x,20).Value
	$objContact.Email3DisplayName = $objExcel.Cells($x,21).Value
	$objContact.BusinessFaxNumber = $objExcel.Cells($x,22).Value
	$objContact.HomeFaxNumber = $objExcel.Cells($x,23).Value
	$objContact.OtherFaxNumber = $objExcel.Cells($x,24).Value
	$objContact.FileAs = $objExcel.Cells($x,25).Value
	$objContact.FirstName = $objExcel.Cells($x,26).Value
	$objContact.FullName = 	$objExcel.Cells($x,27).Value
	$objContact.HomeAddress = $objExcel.Cells($x,28).Value
	$objContact.HomeAddressCity = $objExcel.Cells($x,29).Value
	$objContact.HomeAddressPostalCode = $objExcel.Cells($x,30).Value
	$objContact.HomeAddressState = $objExcel.Cells($x,31).Value
	$objContact.HomeAddressStreet = $objExcel.Cells($x,32).Value
	$objContact.JobTitle = $objExcel.Cells($x,33).Value
	$objContact.LastName = $objExcel.Cells($x,34).Value
	$objContact.MiddleName = $objExcel.Cells($x,35).Value
	$objContact.Nickname = $objExcel.Cells($x,36).Value
	$objContact.OtherAddress = $objExcel.Cells($x,37).Value
	$objContact.OtherAddressCity = $objExcel.Cells($x,38).Value
	$objContact.OtherAddressPostalCode = $objExcel.Cells($x,39).Value
	$objContact.OtherAddressState = $objExcel.Cells($x,40).Value
	$objContact.OtherAddressStreet = $objExcel.Cells($x,41).Value
	$objContact.BusinessTelephoneNumber = $objExcel.Cells($x,42).Value
	$objContact.Business2TelephoneNumber = $objExcel.Cells($x,43).Value
	$objContact.CarTelephoneNumber = $objExcel.Cells($x,44).Value
	$objContact.CompanyMainTelephoneNumber = $objExcel.Cells($x,45).Value
	$objContact.HomeTelephoneNumber = $objExcel.Cells($x,46).Value
	$objContact.MobileTelephoneNumber = $objExcel.Cells($x,47).Value
	$objContact.OtherTelephoneNumber = $objExcel.Cells($x,48).Value
	$objContact.Spouse = $objExcel.Cells($x,50).Value
	$objContact.Subject = $objExcel.Cells($x,51).Value
	$objContact.Title = $objExcel.Cells($x,52).Value
	$objContact.WebPage = $objExcel.Cells($x,53).Value
	;---------------------------------------------------------------------------------------------
	$objContact.Save
	$x = $x + 1
Until $objExcel.Cells($x,25).Value = ""
$objExcel.Quit

Tuesday, August 5, 2008

DirList – Directory enumerator / Excel report maker

This script will enumerate a folder and create an Excel spreadsheet based on it
Run the script, select a starting folder, and the script will dump the folder contents into an Excel spreadsheet
 
 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
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_outfile=DirList.exe
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#cs
    DirList
        Alex Belenkiy - ab@nyitsupport.com
        08/05/2008
        
        This script was created with the purpose of enumerating a folder and its contents into an excel file.
        To use just select the starting path and wait for the Excel sheet to show up.
        Make sure the machine this is executed on has Excel installed.
        
        RecursiveFileSearch function was modified from http://www.autoitscript.com/forum/index.php?showtopic=58558&st=0
#ce
 
#include <array.au3>
#include <file.au3>
#include <GUIConstants.au3>
 
;AutoItSetOption("TrayIconHide", 1)
 
$Path = FileSelectFolder("Please select the folder to enumerate", "",4)
if @error then Exit
$excel = ObjCreate("Excel.Application")
$excel.visible = 0
$excel.workbooks.add
$row = 1
$col = 1
with $excel.activesheet
    .cells($row,$col).value = "Listing of " & $Path
    .cells($row,$col).font.bold = True
    .cells($row,$col).font.size = 20
    .cells($row + 3,$col).value = $Path
    .cells($row + 3,$col).font.bold = True
    $row = $row + 4
    $col = $col + 1
EndWith
 
 
$Array = RecursiveFileSearch($Path)
;_ArrayDisplay($Array)
$excel.visible = 1
;$excel.activeworkbook.saveas("Shared.xls")
$excel = 0
 
Func RecursiveFileSearch($RFSstartDir, $RFSpattern = ".", $RFSdepth = 0)
    ;Ensure starting folder has a trailing slash
    If StringRight($RFSstartDir, 1) <> "\" Then $RFSstartDir &= "\"
 
    If $RFSdepth = 0 Then
        ;Get count of all files in subfolders for initial array definition
        $RFSfilecount = DirGetSize($RFSstartDir, 1)
        Global $RFSarray[$RFSfilecount[1] + 1]
    EndIf
   
    $RFSsearch = FileFindFirstFile($RFSstartDir & "*.*")
    If @error Then Return
 
    ;Search through all files and folders in directory
    While 1
        $RFSnext = FileFindNextFile($RFSsearch)
        If @error Then ExitLoop
       
        ;If folder, recurse
        If StringInStr(FileGetAttrib($RFSstartDir & $RFSnext), "D") Then
            with $excel.activesheet
                .cells($row,$col).font.bold = True
                .cells($row,$col).value = $RFSnext
                $row = $row + 1
                $col = $col + 1
            EndWith
            RecursiveFileSearch($RFSstartDir & $RFSnext, $RFSpattern, $RFSdepth + 1)
            $col = $col - 1
        Else
            If StringRegExp($RFSnext, $RFSpattern, 0) Then
                with $excel.activesheet
                    .cells($row,$col).value = $RFSnext
                    $row = $row + 1
                EndWith
            EndIf
        EndIf
    WEnd
    FileClose($RFSsearch)
 
    If $RFSdepth = 0 Then
        Redim $RFSarray[$RFSarray[0] + 1]
        Return $RFSarray
    EndIf
EndFunc   ;==>RecursiveFileSearch