arfey сказал(а):Подскажите, как возможностями AutoIt запустить и остановить системную службу?
Func _Service_Start($sService, $Computer = ".")
Local $objWMI = ObjGet("winmgmts:\\" & $Computer & "\root\cimv2")
If Not(IsObj($objWMI)) Then Return SetError(-2)
Local $strQuery = "Select * from Win32_Service Where State = 'Stopped' And " & _
"Mame Like '"& $sService & "'"
Local $colItems = $objWMI.ExecQuery($strQuery)
If Not(IsObj($colItems)) Then Return SetError(-2)
For $objItem in $colItems
Return $objItem.StartService($objItem.Name)
Next
Return SetError(-1)
EndFunc ;==> _Service_Start()
Func _Service_Stop($sService, $Computer = ".")
Local $objWMI = ObjGet("winmgmts:\\" & $Computer & "\root\cimv2")
If Not(IsObj($objWMI)) Then Return SetError(-2)
Local $strQuery = "Select * from Win32_Service Where State = 'Running' And " & _
"name like '"& $sService &"'"
Local $colItems = $objWMI.ExecQuery($strQuery)
If Not(IsObj($colItems)) Then Return SetError(-2)
For $objItem In $colItems
Return $objItem.StopService($objItem.Name)
Next
Return SetError(-1)
EndFunc ;==> _Service_Stop()
0 Success
1 Not Supported
2 Access Denied
3 Dependent Services Running
4 Invalid Service Control
5 Service Cannot Accept Control
6 Service Not Active
7 Service Request Timeout
8 Unknown Failure
9 Path Not Found
10 Service Already Running
11 Service Database Locked
12 Service Dependency Deleted
13 Service Dependency Failure
14 Service Disabled
15 Service Logon Failure
16 Service Marked For Deletion
17 Service No Thread
18 Status Circular Dependency
19 Status Duplicate Name
20 Status Invalid Name
21 Status Invalid Parameter
22 Status Invalid Service Account
23 Status Service Exists
24 Service Already Paused
$aRet_Info = _Service_Proc("iPod Service", "stop")
$sFoematted_Info = StringFormat("Std Out Return:\t%s\nStd Error Return:\t%s\n", $aRet_Info[0], $aRet_Info[1])
MsgBox(64, 'Title', $sFoematted_Info)
$aRet_Info = _Service_Proc("iPod Service", "start")
$sFoematted_Info = StringFormat("Std Out Return:\t%s\nStd Error Return:\t%s\n", $aRet_Info[0], $aRet_Info[1])
MsgBox(64, 'Title', $sFoematted_Info)
Func _Service_Proc($sService, $sAction)
Local $iPID = Run('net ' & $sAction & ' "' & $sService & '"', '', @SW_HIDE, 2 + 4)
Local $sStdRead, $sStdErrRead, $stBuffer, $aRet, $aRet[2]
While 1
$sStdRead &= StdoutRead($iPID)
If @error Then ExitLoop
$sStdErrRead &= StderrRead($iPID)
If @error Then ExitLoop
WEnd
$aRet[0] = $sStdRead
$aRet[1] = $sStdErrRead
For $i = 0 To 1
$stBuffer = DllStructCreate("char[" & StringLen($aRet[$i])+1 & "]")
$aOemToChar = DllCall("User32.dll", "int", "OemToChar", "str", $aRet[$i], "ptr", DllStructGetPtr($stBuffer))
If Not IsArray($aOemToChar) Then ContinueLoop ;ошибка DLL
If $aOemToChar[0] = 0 Then ContinueLoop ;ошибка функции
$aRet[$i] = DllStructGetData($stBuffer, 1)
Next
Return $aRet
EndFunc
У меня возвращает 1 при попытке запустить только что остановленную службу :(при успехе возвращается 0, иначе:
#cs ----------------------------------------------------------------------------
AutoIt Version : 3.3.0.0
Author : Sriptonize
File name : _WinServices.au3
UDF Version : 1.3
Updated on : 21-08-2009 (dd-mm-yyyy)
Function(s) : _IsPossiblePauseService($nService)
_IsPossibleStopService($nService)
_IsServiceState($nService,$nServiceState)
_PauseService($nService)
_ServiceExists($nService)
_StartService($nService)
_StopService($nService)
Requirements : WindowsXP Pro, SP-3 (other OS versions and/or service-packs may work, but havn't been tested)
Source : http://msdn.microsoft.com
#ce ----------------------------------------------------------------------------
#include-once
Global $DebugMode = 0
Func _IsPossiblePauseService($nService)
#cs ----------------------------------------------------------------------------
AutoIt Version : 3.3.0.0
Author : Sriptonize
UDF Version : 1.3
Updated on : 21-08-2009 (dd-mm-yyyy)
Function : Checks if a service can be paused
Return values : 0 (It is possible to set this service in a pause state)
1 (It is not possible to set this service in a pause state)
110 (Object error: Not an Object)
Requirements : WindowsXP Pro, SP-3 (other OS versions and/or service-packs may work, but havn't been tested)
Source : http://msdn.microsoft.com
#ce ----------------------------------------------------------------------------
Local $objWMIService ; Main object
Local $objQueryCollection ; Result of query
Local $hObj ; Current selected Object in $objQueryCollection
If $DebugMode = 1 Then ConsoleWrite(@CR)
If $DebugMode = 1 Then ConsoleWrite("_IsPossiblePauseService($nService)" & @CR)
If $DebugMode = 1 Then ConsoleWrite("_IsPossiblePauseService($nService)= " & $nService & @CR)
;Before proceeding, first check if the service exists
If _ServiceExists($nService) = -1 Then
Return 4
EndIf
$objWMIService = ObjGet("winmgmts:\\" & @ComputerName & "\root\CIMV2")
If IsObj($objWMIService) then
If $DebugMode = 1 Then ConsoleWrite("$objWMIService is an Object" & @CR)
$objQueryCollection = $objWMIService.ExecQuery("SELECT * FROM Win32_Service Where AcceptPause = True AND Where Name = '" & $nService & "'")
Else
Return 110
EndIf
If IsObj($objQueryCollection) then
If $DebugMode = 1 Then ConsoleWrite("Collection returned by Query on $objWMIService)" & @CR)
For $hObj In $objQueryCollection
If $hObj.Name = $nService Then ;If we have found the service and the service can be paused, return 0
If $DebugMode = 1 Then ConsoleWrite("Current $objWMIService.Name= " & $objWMIService.Name() & " Current $objWMIService.AcceptPause= " & $objWMIService.AcceptPause() & " Returning 0" & @CR)
Return 0 ;If we have found the service and the service can be paused, return 0
Else
If $DebugMode = 1 Then ConsoleWrite("Current $objWMIService.Name= " & $objWMIService.Name() & " Current $objWMIService.AcceptPause= " & $objWMIService.AcceptPause() & " Returning 1" & @CR)
Return 1
EndIf
Next ;$hObj In $objQueryCollection
Else
Return 110 ;Obj error
EndIf
EndFunc
Func _IsPossibleStopService($nService)
#cs ----------------------------------------------------------------------------
AutoIt Version : 3.3.0.0
Author : Sriptonize
UDF Version : 1.3
Updated on : 21-08-2009 (dd-mm-yyyy)
Function : Checks if a service can be stopped
Return values : 0 (It is possible to set this service in a stopped state)
1 (It is not possible to set this service in a stopped state)
110 (Object error: Not an Object)
Requirements : WindowsXP Pro, SP-3 (other OS versions and/or service-packs may work, but havn't been tested)
Source : http://msdn.microsoft.com
#ce ----------------------------------------------------------------------------
Local $objWMIService ; Main object
Local $objQueryCollection ; Result of query
Local $hObj ; Current selected Object in $objQueryCollection
If $DebugMode = 1 Then ConsoleWrite(@CR)
If $DebugMode = 1 Then ConsoleWrite("_IsPossibleStopService($nService)" & @CR)
If $DebugMode = 1 Then ConsoleWrite("_IsPossibleStopService($nService)= " & $nService & @CR)
;Before proceeding, first check if the service exists
If _ServiceExists($nService) = -1 Then
Return 4
EndIf
$objWMIService = ObjGet("winmgmts:\\" & @ComputerName & "\root\CIMV2")
If IsObj($objWMIService) then
If $DebugMode = 1 Then ConsoleWrite("$objWMIService is an Object" & @CR)
$objQueryCollection = $objWMIService.ExecQuery("SELECT * FROM Win32_Service Where AcceptStop = True AND Where Name = '" & $nService & "'")
Else
Return 110
EndIf
If IsObj($objQueryCollection) then
If $DebugMode = 1 Then ConsoleWrite("Collection returned by Query on $objWMIService)" & @CR)
For $hObj In $objQueryCollection
If $hObj.Name = $nService Then
If $DebugMode = 1 Then ConsoleWrite("Current $objWMIService.Name= " & $objWMIService.Name() & " Current $objWMIService.AcceptPause= " & $objWMIService.AcceptPause() & " Returning 0" & @CR)
Return 0 ;If we have found the service and the service can be stopped, return 0
Else
If $DebugMode = 1 Then ConsoleWrite("Current $objWMIService.Name= " & $objWMIService.Name() & " Current $objWMIService.AcceptPause= " & $objWMIService.AcceptPause() & " Returning 1" & @CR)
Return 1 ;the service can not be stopped, return 1
EndIf
Next ;$hObj In $objQueryCollection
Else
Return 110 ;Obj error
EndIf
EndFunc
Func _IsServiceState($nService,$nServiceState)
#cs ----------------------------------------------------------------------------
AutoIt Version : 3.3.0.0
Author : Sriptonize
UDF Version : 1.3
Updated on : 21-08-2009 (dd-mm-yyyy)
Function : Checks if the state of the service equals the state as provided
Handled Parameters for $nServiceState:
Stopped
Stopping
Running
Starting
Paused
Unknown
Return values : 0 (Success, service state equals the provided state)
1 (Failure, service state does not equal the provided state)
110 (Object error: Not an Object)
200 (Invalid state provided)
Requirements : WindowsXP Pro, SP-3 (other OS versions and/or service-packs may work, but havn't been tested)
Source : http://msdn.microsoft.com
#ce ----------------------------------------------------------------------------
Local $objWMIService ; Main object
Local $objQueryCollection ; Result of query
Local $hObj ; Current selected Object in $objQueryCollection
If $DebugMode = 1 Then ConsoleWrite(@CR)
If $DebugMode = 1 Then ConsoleWrite("_IsServiceState($nService,$nServiceState)" & @CR)
If $DebugMode = 1 Then ConsoleWrite("_IsServiceState($nService,$nServiceState)= " & $nService & "," & $nServiceState & @CR)
;Before proceeding, first check if the service exists
If _ServiceExists($nService) = -1 Then
Return 4
EndIf
;Check input...
Select
Case $nServiceState = "Stopped"
Case $nServiceState = "Stopping"
Case $nServiceState = "Running"
Case $nServiceState = "Starting"
Case $nServiceState = "Paused"
Case $nServiceState = "Unknown"
Case Else
Return 200
EndSelect
$objWMIService = ObjGet("winmgmts:\\" & @ComputerName & "\root\CIMV2")
If IsObj($objWMIService) then
If $DebugMode = 1 Then ConsoleWrite("$objWMIService is an Object" & @CR)
$objQueryCollection = $objWMIService.ExecQuery("SELECT * FROM Win32_Service Where Name = '" & $nService & "'")
Else
Return 110
EndIf
If IsObj($objQueryCollection) then
If $DebugMode = 1 Then ConsoleWrite("Collection returned by Query on $objWMIService)" & @CR)
For $hObj In $objQueryCollection
If $hObj.Name = $nService Then
If $DebugMode = 1 Then ConsoleWrite("Current value of $hObj.Name= '" & $hObj.Name & "' Proceeding with state" & @CR)
If $hObj.State = $nServiceState Then ;If the service is in the correct state return 0
If $DebugMode = 1 Then ConsoleWrite("Current value of $hObj.State= '" & $hObj.State & "' Returning 0" & @CR)
Return 0
Else
If $DebugMode = 1 Then ConsoleWrite("Current value of $hObj.State= '" & $hObj.State & "' Returning -1" & @CR)
Return -1
EndIf
EndIf
Next ;<== $hObj In $objQueryCollection
Else
Return 110
EndIf
EndFunc
Func _PauseService($nService)
#cs ----------------------------------------------------------------------------
AutoIt Version : 3.3.0.0
Author : Sriptonize
UDF Version : 1.3
Updated on : 21-08-2009 (dd-mm-yyyy)
Function : Starts a service
Return values : 0 (Success)
1 (Not supported)
2 (Access denied)
3 (Dependend services running)
4 (Invalid service control)
5 (Service cannot accept control)
6 (Service not active)
7 (Servie request timeout)
8 (Unknown failure)
9 (path not found)
10 (service allready running)
11 (Service database locked)
12 (Service dependency deleted)
13 (Service dependency failure)
14 (Service disabled)
15 (Service logon failure)
16 (Service marked for deletion)
17 (Service no thread)
18 (Status circular dependency)
19 (Status duplicate name)
20 (Status invalid name)
21 (Status invalid parameter)
22 (Status invalid service account)
23 (Status service exists)
24 (service already paused)
100 (Object error)
110 (Object error: Not an Object)
#ce ----------------------------------------------------------------------------
Local $objWMIService ; Main object
Local $objQueryCollection ; Result of query
Local $hObj ; Current selected Object in $objQueryCollection
Local $hErr,$hResult,$i
If $DebugMode = 1 Then ConsoleWrite(@CR)
If $DebugMode = 1 Then ConsoleWrite("_PauseService($nService)" & @CR)
If $DebugMode = 1 Then ConsoleWrite("_PauseService($nService)= " & $nService & @CR)
;Before proceeding, first check if the service exists
If _ServiceExists($nService) = -1 Then
Return 4
EndIf
;If service does exists start the service
$objWMIService = ObjGet("winmgmts:\\" & @ComputerName & "\root\CIMV2")
If IsObj($objWMIService) Then
If $DebugMode = 1 Then ConsoleWrite("$objWMIService is an Object" & @CR)
$objQueryCollection = $objWMIService.ExecQuery("SELECT * FROM Win32_Service Where Name = '" & $nService & "'")
If IsObj($objQueryCollection) Then
If $DebugMode = 1 Then ConsoleWrite("Collection returned by Query on $objWMIService)" & @CR)
;Try to pause the service
For $hObj In $objQueryCollection
$hResult = $hObj.PauseService()
$hErr = @error
If $DebugMode = 1 Then ConsoleWrite("$hObj.PauseService()= " & $hResult & @CR)
If $DebugMode = 1 Then ConsoleWrite("@error= " & $hErr & @CR)
;Give the service some time to pause...
For $i = 1 to 10
Sleep(100)
Next
Return $hErr
Next
Else
Return 100
EndIf
Else
Return 110
EndIf
EndFunc
Func _ResumeService($nService)
#cs ----------------------------------------------------------------------------
AutoIt Version : 3.3.0.0
Author : Sriptonize
UDF Version : 1.3
Updated on : 21-08-2009 (dd-mm-yyyy)
Function : Starts a service
Return values : 0 (Success)
1 (Not supported)
2 (Access denied)
3 (Dependend services running)
4 (Invalid service control)
5 (Service cannot accept control)
6 (Service not active)
7 (Servie request timeout)
8 (Unknown failure)
9 (path not found)
10 (service allready running)
11 (Service database locked)
12 (Service dependency deleted)
13 (Service dependency failure)
14 (Service disabled)
15 (Service logon failure)
16 (Service marked for deletion)
17 (Service no thread)
18 (Status circular dependency)
19 (Status duplicate name)
20 (Status invalid name)
21 (Status invalid parameter)
22 (Status invalid service account)
23 (Status service exists)
24 (service already paused)
100 (Object error)
110 (Object error: Not an Object)
#ce ----------------------------------------------------------------------------
Local $objWMIService ; Main object
Local $objQueryCollection ; Result of query
Local $hObj ; Current selected Object in $objQueryCollection
Local $hErr,$hResult,$i
If $DebugMode = 1 Then ConsoleWrite(@CR)
If $DebugMode = 1 Then ConsoleWrite("_ResumeService($nService)" & @CR)
If $DebugMode = 1 Then ConsoleWrite("_ResumeService($nService)= " & $nService & @CR)
;Before proceeding, first check if the service exists
If _ServiceExists($nService) = -1 Then
Return 4
EndIf
;If service does exists start the service
$objWMIService = ObjGet("winmgmts:\\" & @ComputerName & "\root\CIMV2")
If IsObj($objWMIService) Then
If $DebugMode = 1 Then ConsoleWrite("$objWMIService is an Object" & @CR)
$objQueryCollection = $objWMIService.ExecQuery("SELECT * FROM Win32_Service Where Name = '" & $nService & "'")
If IsObj($objQueryCollection) Then
If $DebugMode = 1 Then ConsoleWrite("Collection returned by Query on $objWMIService)" & @CR)
;Try to resume the service
For $hObj In $objQueryCollection
$hResult = $hObj.ResumeService()
$hErr = @error
If $DebugMode = 1 Then ConsoleWrite("$hObj.ResumeService()= " & $hResult & @CR)
If $DebugMode = 1 Then ConsoleWrite("@error= " & $hErr & @CR)
;Give the service some time to resume...
For $i = 1 to 10
Sleep(100)
Next
Return $hErr
Next
Else
Return 100
EndIf
Else
Return 110
EndIf
EndFunc
Func _ServiceExists($nService)
#cs ----------------------------------------------------------------------------
AutoIt Version : 3.3.0.0
Author : Sriptonize
UDF Version : 1.3
Updated on : 21-08-2009 (dd-mm-yyyy)
Function : Checks if a service exists
Return values : 0 (Success, service was found)
-1 (Failure, service was not found)
110 (Object error: Not an Object)
Requirements : WindowsXP Pro, SP-3 (other OS versions and/or service-packs may work, but havn't been tested)
Source : http://msdn.microsoft.com
#ce ----------------------------------------------------------------------------
Local $objWMIService ; Main object
Local $objQueryCollection ; Result of query
Local $hObj ; Current selected Object in $objQueryCollection
If $DebugMode = 1 Then ConsoleWrite(@CR)
If $DebugMode = 1 Then ConsoleWrite("_ServiceExists($nService)" & @CR)
If $DebugMode = 1 Then ConsoleWrite("_ServiceExists($nService)= " & $nService & @CR)
$objWMIService = ObjGet("winmgmts:\\" & @ComputerName & "\root\CIMV2")
If IsObj($objWMIService) Then
If $DebugMode = 1 Then ConsoleWrite("$objWMIService is an Object" & @CR)
$objQueryCollection = $objWMIService.ExecQuery("SELECT * FROM Win32_Service Where Name = '" & $nService & "'")
Else
Return 110
EndIf
If IsObj($objQueryCollection) then
If $DebugMode = 1 Then ConsoleWrite("Collection returned by Query on $objWMIService)" & @CR)
For $hObj In $objQueryCollection
If $hObj.Name = $nService Then Return 0 ;Service found, return 0
Next ;<== $objWMIService In $hObj
Else
Return 110 ;Obj error
EndIf
Return -1 ;Service not found, return -1
EndFunc
Func _StartService($nService)
#cs ----------------------------------------------------------------------------
AutoIt Version : 3.3.0.0
Author : Sriptonize
UDF Version : 1.3
Updated on : 21-08-2009 (dd-mm-yyyy)
Function : Starts a service
Return values : 0 (Success)
1 (Not supported)
2 (Access denied)
3 (Dependend services running)
4 (Invalid service control)
5 (Service cannot accept control)
6 (Service not active)
7 (Servie request timeout)
8 (Unknown failure)
9 (path not found)
10 (service allready running)
11 (Service database locked)
12 (Service dependency deleted)
13 (Service dependency failure)
14 (Service disabled)
15 (Service logon failure)
16 (Service marked for deletion)
17 (Service no thread)
18 (Status circular dependency)
19 (Status duplicate name)
20 (Status invalid name)
21 (Status invalid parameter)
22 (Status invalid service account)
23 (Status service exists)
24 (service already paused)
100 (Object error)
110 (Object error: Not an Object)
#ce ----------------------------------------------------------------------------
Local $objWMIService ; Main object
Local $objQueryCollection ; Result of query
Local $hObj ; Current selected Object in $objQueryCollection
Local $hErr,$hResult,$i
If $DebugMode = 1 Then ConsoleWrite(@CR)
If $DebugMode = 1 Then ConsoleWrite("_StartService($nService)" & @CR)
If $DebugMode = 1 Then ConsoleWrite("_StartService($nService)= " & $nService & @CR)
;Before proceeding, first check if the service exists
If _ServiceExists($nService) = -1 Then
Return 4
EndIf
;If service does exists start the service
$objWMIService = ObjGet("winmgmts:\\" & @ComputerName & "\root\CIMV2")
If IsObj($objWMIService) Then
If $DebugMode = 1 Then ConsoleWrite("$objWMIService is an Object" & @CR)
$objQueryCollection = $objWMIService.ExecQuery("SELECT * FROM Win32_Service Where Name = '" & $nService & "'")
If IsObj($objQueryCollection) Then
If $DebugMode = 1 Then ConsoleWrite("Collection returned by Query on $objWMIService)" & @CR)
;Try to start the service
For $hObj In $objQueryCollection
$hResult = $hObj.StartService()
$hErr = @error
If $DebugMode = 1 Then ConsoleWrite("$hObj.StartService()= " & $hResult & @CR)
If $DebugMode = 1 Then ConsoleWrite("@error= " & $hErr & @CR)
;Give the service some time to start up...
For $i = 1 to 10
Sleep(100)
Next
Return $hErr
Next
Else
Return 100
EndIf
Else
Return 110
EndIf
EndFunc
Func _StopService($nService)
#cs ----------------------------------------------------------------------------
AutoIt Version : 3.3.0.0
Author : Sriptonize
UDF Version : 1.3
Updated on : 21-08-2009 (dd-mm-yyyy)
Function : Stops a service
Return values : 0 (Success)
1 (Not supported)
2 (Access denied)
3 (Dependend services running)
4 (Invalid service control)
5 (Service cannot accept control)
6 (Service not active)
7 (Servie request timeout)
8 (Unknown failure)
9 (path not found)
10 (service allready running)
11 (Service database locked)
12 (Service dependency deleted)
13 (Service dependency failure)
14 (Service disabled)
15 (Service logon failure)
16 (Service marked for deletion)
17 (Service no thread)
18 (Status circular dependency)
19 (Status duplicate name)
20 (Status invalid name)
21 (Status invalid parameter)
22 (Status invalid service account)
23 (Status service exists)
24 (service already paused)
100 (Object error)
110 (Object error: Not an Object)
#ce ----------------------------------------------------------------------------
Local $objWMIService ; Main object
Local $objQueryCollection ; Result of query
Local $hObj ; Current selected Object in $objQueryCollection
Local $hErr,$hResult,$i
If $DebugMode = 1 Then ConsoleWrite(@CR)
If $DebugMode = 1 Then ConsoleWrite("_StopService($nService)" & @CR)
If $DebugMode = 1 Then ConsoleWrite("_StopService($nService)= " & $nService & @CR)
;Before proceeding, first check if the service exists
If _ServiceExists($nService) = -1 Then
Return 4
EndIf
;If service does exists stop the service
$objWMIService = ObjGet("winmgmts:\\" & @ComputerName & "\root\CIMV2")
If IsObj($objWMIService) Then
If $DebugMode = 1 Then ConsoleWrite("$objWMIService is an Object" & @CR)
$objQueryCollection = $objWMIService.ExecQuery("SELECT * FROM Win32_Service Where Name = '" & $nService & "'")
If IsObj($objQueryCollection) Then
If $DebugMode = 1 Then ConsoleWrite("Collection returned by Query on $objWMIService)" & @CR)
;Try to start the service
For $hObj In $objQueryCollection
$hResult = $hObj.StopService()
$hErr = @error
If $DebugMode = 1 Then ConsoleWrite("$hObj.StopService()= " & $hResult & @CR)
If $DebugMode = 1 Then ConsoleWrite("@error= " & $hErr & @CR)
;Give the service some time to stop...
For $i = 1 to 10
Sleep(100)
Next
Return $hErr
Next
Else
Return 100
EndIf
Else
Return 110
EndIf
EndFunc
А чем не простые функций выше?Можно оперировать простыми функциями?
А проверить? Ну а код с net, тоже не подходит?Пост с использованием Obj мне вообще непонятен, так как прочитав его эдак раз 5, пришел к выводу, что из-за неописанных переменных он работать не будет.
Ну так в чём проблема?так как код пишется под ХР 32-bit, то подобная чепуха с правами отпадает сама-собой.
А зачем это понимать? в моём примере оно используется лишь для конвертирования строки в OEM возвращаемоей с консоли (net).Объяснять каждую строку кода мне никто не будет, а понимание работы к примеру DllStructCreate с неба не придет.
не путайте задачи администрирования ОС и программирования – одно не заменяет другое… если прав нет, их надо просто предоставить, а не пытаться “обмануть” систему безопасностиarfey сказал(а):Первый код не работает на win7 x64.
Второй код похоже функционален, только на платформе "семерки" х64 ему смерть из-за прав доступа.
net и sc так же спотыкаются о права доступа.
в моём посте практически то же самое (сравни код)r35p3ct сказал(а):В моем посте как раз как ты хочешь.
аналог твоей UDF на WMI, но для работы требуется установка перехвата COM ошибок...CreatoR сказал(а):У меня возвращает 1 при попытке запустить только что остановленную службу
$oServiceErrorHandler = ObjEvent("AutoIt.Error", "_Service_ErrorHandler")
_Service_WaitSetState("alerter", "Stop")
_Service_WaitSetState("alerter", "Start")
Func _Service_WaitSetState($sService, $sState, $iTimeout = -1, $sComputer = ".")
Local $iRet, $iState, $oEventSource, $oEvent, $iState=-1
Local Const $aSets[4][4] = [ _
["Start" , "StartService" , "Stopped", "Running"], _
["Stop" , "StopService" , "Running", "Stopped"], _
["Resume", "ResumeService", "Paused" , "Running"], _
["Pause" , "PauseService" , "Running", "Paused" ]]
For $i=0 To 3
If $sState=$aSets[$i][0] Then $iState=$i
Next
If $iState<0 Then Return SetError(1, 0, False) ; Ошибка: Недопустимое состояние
If $iTimeout >0 Then $iTimeout*=1000
If $iTimeout<=0 Then $iTimeout=-1
Local $oWMI = ObjGet("winmgmts:\\" & $sComputer & "\root\cimv2")
If Not(IsObj($oWMI)) Then Return SetError(5, 1, False) ; Ошибка WMI
Local $sQuery = "Select * From Win32_Service Where Name='"& $sService &"'"
Local $sNotify= "Select * From __InstanceModificationEvent Within 5 " & _
"Where TargetInstance ISA 'Win32_Service' AND TargetInstance.Name='"& _
$sService &"' AND TargetInstance.State='"& $aSets[$iState][3] &"'"
Local $cItems = $oWMI.ExecQuery($sQuery)
If Not(IsObj($cItems)) Then Return SetError(5, 2, False) ; Ошибка WMI
For $oItem In $cItems
If $oItem.State = $aSets[$iState][3] Then Return True ; Сервис уже в нужном состоянии
If $oItem.State <>$aSets[$iState][2] Then Return SetError(3, 0, False) ; Недопустимое исходное состояние
$oEventSource = $oWMI.ExecNotificationQuery($sNotify)
If Not(IsObj($oEventSource)) Then Return SetError(5, 3, False) ; Ошибка WMI
$iRet = Execute("$oItem."& $aSets[$iState][1])
If $iRet Then Return SetError(4, $iRet, False) ; Cервис вернул ошибку
$oEvent = $oEventSource.NextEvent($iTimeout)
If IsObj($oEvent) Then Return True ; Сервис переверен в нужное состояние
Return SetError(1, 0, False) ; Ошибка таймаута
Next
Return SetError(2, 0, False) ; Ошибка: сервис не найден
EndFunc ;==> _Service_WaitSetState
Func _Service_ErrorHandler()
SetError(5, $oServiceErrorHandler.Number)
EndFunc ;==> _Service_ErrorHandler()
Func _Service_Start($sService, $Computer = ".")
ConsoleWrite($sService & @CRLF)
Local $objWMI = ObjGet("winmgmts:\\" & $Computer & "\root\cimv2")
If Not(IsObj($objWMI)) Then Return SetError(-2)
Local $strQuery = "Select * from Win32_Service Where State = 'Stopped' And " & _
"Name Like '"& $sService & "'"
Local $colItems = $objWMI.ExecQuery($strQuery)
If Not(IsObj($colItems)) Then Return SetError(-2)
For $objItem in $colItems
Return $objItem.StartService($objItem.Name)
Next
Return SetError(-1)
EndFunc ;==> _Service_Start()
Func _Service_Stop($sService, $Computer = ".")
ConsoleWrite($sService & @CRLF)
Local $objWMI = ObjGet("winmgmts:\\" & $Computer & "\root\cimv2")
If Not(IsObj($objWMI)) Then Return SetError(-2)
Local $strQuery = "Select * from Win32_Service Where State = 'Running' And " & _
"name like '"& $sService &"'"
Local $colItems = $objWMI.ExecQuery($strQuery)
If Not(IsObj($colItems)) Then Return SetError(-2)
For $objItem In $colItems
Return $objItem.StopService($objItem.Name)
Next
Return SetError(-1)
EndFunc ;==> _Service_Stop()