You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBScript脚本增强需求:实现服务反向启停及参数传入

Got it, let's build out this enhanced VBScript for you! Since you're already handling service disable/stop logic, adding the reverse "enable/start" functionality with parameter control is totally doable. Here's a complete solution that keeps your original logging behavior and plays nicely with Windows Task Scheduler:

Complete Enhanced Script
Option Explicit

' Configuration - adjust these values to match your needs
Const SERVICE_NAME = "YourTargetService" ' Replace with your actual service name
Const MACHINE_LIST_PATH = "C:\Path\To\MachineList.txt" ' Path to your machine names file
Const LOG_FILE_PATH = "C:\Path\To\ServiceControlLog.txt" ' Path for logging actions

Dim objFSO, objLogFile, strMachine, objWMIService, colServices, objService
Dim strOperationMode, strInitialState, strFinalState, dtmTimestamp

' Handle command-line parameter to set operation direction
If WScript.Arguments.Count > 0 Then
    strOperationMode = UCase(WScript.Arguments(0))
    If strOperationMode <> "ON" And strOperationMode <> "OFF" Then
        WScript.Echo "Invalid parameter! Use ""On"" to enable/start services, ""Off"" to stop/disable."
        WScript.Quit 1
    End If
Else
    ' Default to original stop/disable behavior if no parameter is provided
    strOperationMode = "OFF"
End If

' Initialize file system and log file (append mode)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.OpenTextFile(LOG_FILE_PATH, 8, True)
dtmTimestamp = Now()

' Read machine list line by line
Set objFile = objFSO.OpenTextFile(MACHINE_LIST_PATH, 1)
Do Until objFile.AtEndOfStream
    strMachine = Trim(objFile.ReadLine())
    If strMachine <> "" Then ' Skip empty lines in the file
        On Error Resume Next
        ' Connect to WMI on the target machine
        Set objWMIService = GetObject("winmgmts:\\" & strMachine & "\root\cimv2")
        If Err.Number <> 0 Then
            objLogFile.WriteLine dtmTimestamp & " | ERROR: Failed to connect to " & strMachine & " - " & Err.Description
            Err.Clear
            On Error GoTo 0
            Continue
        End If
        On Error GoTo 0

        ' Fetch the target service
        Set colServices = objWMIService.ExecQuery("SELECT * FROM Win32_Service WHERE Name = '" & SERVICE_NAME & "'")
        For Each objService In colServices
            ' Capture initial service state
            strInitialState = "State: " & objService.State & ", Start Mode: " & objService.StartMode

            ' Execute action based on operation mode
            If strOperationMode = "OFF" Then
                ' Original logic: Stop if running, disable regardless
                If objService.State = "Running" Then
                    objService.StopService()
                    WScript.Sleep 2000 ' Give service time to stop
                End If
                objService.ChangeStartMode("Disabled")
                strFinalState = "State: " & objService.State & ", Start Mode: Disabled"
            ElseIf strOperationMode = "ON" Then
                ' Reverse logic: Enable first, then start if not running
                objService.ChangeStartMode("Automatic")
                WScript.Sleep 1000 ' Wait for start mode update
                If objService.State <> "Running" Then
                    objService.StartService()
                    WScript.Sleep 2000 ' Wait for service to start
                End If
                strFinalState = "State: " & objService.State & ", Start Mode: Automatic"
            End If

            ' Log the result
            objLogFile.WriteLine dtmTimestamp & " | Machine: " & strMachine & " | Service: " & SERVICE_NAME
            objLogFile.WriteLine "  Initial State: " & strInitialState
            objLogFile.WriteLine "  Final State: " & strFinalState & vbCrLf
        Next
    End If
Loop

' Clean up resources
objFile.Close
objLogFile.Close
Set objFSO = Nothing
Set objWMIService = Nothing
WScript.Echo "Operation finished. Check log file at: " & LOG_FILE_PATH
Key Details to Note
  • Parameter Control: The script checks for a command-line argument (On/Off). If you run it without parameters, it defaults to your original "stop/disable" behavior.
  • Robust Logging: Every action is timestamped and includes machine name, service name, initial state, and final state – preserving the logging behavior you already have.
  • Error Handling: Added basic checks for WMI connection failures, so you'll be notified if a machine is unreachable.
  • Timing Adjustments: Small WScript.Sleep calls give the service time to update its state after changes. Feel free to tweak these values if your service needs more/less time to start/stop.
Setting Up in Windows Task Scheduler

When creating your scheduled task:

  1. Go to Actions > New
  2. For Program/script, enter wscript.exe
  3. For Add arguments (optional), input the full path to your script plus your desired mode, like:
    "C:\Scripts\ServiceControlScript.vbs" On
    
  4. Configure the trigger and other settings to match your schedule requirements.
Quick Testing Tip

Before setting up the task, test the script manually to confirm it works:

  • Run wscript.exe "C:\Scripts\ServiceControlScript.vbs" Off to verify the original stop/disable behavior
  • Run wscript.exe "C:\Scripts\ServiceControlScript.vbs" On to test the enable/start functionality

内容的提问来源于stack exchange,提问作者DanBot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:19:15