Announcement

Collapse
No announcement yet.

Start Defrag on a Target Machine (VBS)

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Start Defrag on a Target Machine (VBS)

    I have this little script to start off Defrag on a machine... it only works on the local machine, opens a window, runs the defrag and closes when its finished... works fine, but only if you are an administrator sadly...

    Code:
    Set WshShell = WScript.CreateObject("WScript.Shell")
    
    	Dim fso, d, dc
    	Set fso = CreateObject("Scripting.FileSystemObject")
    	Set dc = fso.Drives
    	For Each d in dc
    		If d.DriveType = 2 Then
    			Return = WshShell.Run("defrag " & d, 1, TRUE)
    		End If
    	Next
    
    Set WshShell = Nothing
    I do get a fair few people asking to start off defrag and then leave them to it - it's a pain connecting to their machine, running defrag/the script as myself...

    I'd like to be able to just double click - type in the comp name and let it go away and start the defrag process - I assume since I'd run it from my machine it'd run as me - which is fine as I'd have admin rights on the machine so it'd prevent all those pesky user without permission problems.

    I know I could use things like the PStools:
    Code:
    PSEXEC -i -d -s \\<computername> c:\windows\system32\defrag.exe c:
    but I want to be able to just enter the computer name rather than edit it into a batch file all the time...

    Any ideas?
    This is my signature.

  • #2
    Re: Start Defrag on a Target Machine (VBS)

    1. You can use the PSEXEC command in a FOR loop instead of editing the batch all the time. Type in FOR /? at the command prompt to get the idea of how to use it with an external text file (list of computers on wich you want to run the defrag on).

    2. You can create a Scheduled Task on all the computers, and set it to run under the NT AUTHORITY\SYSTEM account (so the task will run with higher priviliges). This way you can even schedule the defrag, or just run it "manually" from your machine using the SCHTASKS command (also in a FOR loop).

    I'm a major fan of VBS (and all other scripting lanuages) but I think that in this case, the good old FOR loop in a batch file is the simplest way to do the job.

    Comment


    • #3
      Re: Start Defrag on a Target Machine (VBS)

      is it possible to start it when its run? - like a schedule for 'now'
      and is it also possible to have it prompt for the computer name instead of having it in a list...?

      I haven't had time to read through all this yet...
      Runs a specified command for each file in a set of files.

      FOR %variable IN (set) DO command [command-parameters]

      %variable Specifies a single letter replaceable parameter.
      (set) Specifies a set of one or more files. Wildcards may be used.
      command Specifies the command to carry out for each file.
      command-parameters
      Specifies parameters or switches for the specified command.

      To use the FOR command in a batch program, specify %%variable instead
      of %variable. Variable names are case sensitive, so %i is different
      from %I.

      If Command Extensions are enabled, the following additional
      forms of the FOR command are supported:

      FOR /D %variable IN (set) DO command [command-parameters]

      If set contains wildcards, then specifies to match against directory
      names instead of file names.

      FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]

      Walks the directory tree rooted at [drive:]path, executing the FOR
      statement in each directory of the tree. If no directory
      specification is specified after /R then the current directory is
      assumed. If set is just a single period (.) character then it
      will just enumerate the directory tree.

      FOR /L %variable IN (start,step,end) DO command [command-parameters]

      The set is a sequence of numbers from start to end, by step amount.
      So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would
      generate the sequence (5 4 3 2 1)

      FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
      FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
      FOR /F ["options"] %variable IN ('command') DO command [command-parameters]

      or, if usebackq option present:

      FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
      FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
      FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]

      filenameset is one or more file names. Each file is opened, read
      and processed before going on to the next file in filenameset.
      Processing consists of reading in the file, breaking it up into
      individual lines of text and then parsing each line into zero or
      more tokens. The body of the for loop is then called with the
      variable value(s) set to the found token string(s). By default, /F
      passes the first blank separated token from each line of each file.
      Blank lines are skipped. You can override the default parsing
      behavior by specifying the optional "options" parameter. This
      is a quoted string which contains one or more keywords to specify
      different parsing options. The keywords are:

      eol=c - specifies an end of line comment character
      (just one)
      skip=n - specifies the number of lines to skip at the
      beginning of the file.
      delims=xxx - specifies a delimiter set. This replaces the
      default delimiter set of space and tab.
      tokens=x,y,m-n - specifies which tokens from each line are to
      be passed to the for body for each iteration.
      This will cause additional variable names to
      be allocated. The m-n form is a range,
      specifying the mth through the nth tokens. If
      the last character in the tokens= string is an
      asterisk, then an additional variable is
      allocated and receives the remaining text on
      the line after the last token parsed.
      usebackq - specifies that the new semantics are in force,
      where a back quoted string is executed as a
      command and a single quoted string is a
      literal string command and allows the use of
      double quotes to quote file names in
      filenameset.

      Some examples might help:

      FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k

      would parse each line in myfile.txt, ignoring lines that begin with
      a semicolon, passing the 2nd and 3rd token from each line to the for
      body, with tokens delimited by commas and/or spaces. Notice the for
      body statements reference %i to get the 2nd token, %j to get the
      3rd token, and %k to get all remaining tokens after the 3rd. For
      file names that contain spaces, you need to quote the filenames with
      double quotes. In order to use double quotes in this manner, you also
      need to use the usebackq option, otherwise the double quotes will be
      interpreted as defining a literal string to parse.

      %i is explicitly declared in the for statement and the %j and %k
      are implicitly declared via the tokens= option. You can specify up
      to 26 tokens via the tokens= line, provided it does not cause an
      attempt to declare a variable higher than the letter 'z' or 'Z'.
      Remember, FOR variables are single-letter, case sensitive, global,
      and you can't have more than 52 total active at any one time.

      You can also use the FOR /F parsing logic on an immediate string, by
      making the filenameset between the parenthesis a quoted string,
      using single quote characters. It will be treated as a single line
      of input from a file and parsed.

      Finally, you can use the FOR /F command to parse the output of a
      command. You do this by making the filenameset between the
      parenthesis a back quoted string. It will be treated as a command
      line, which is passed to a child CMD.EXE and the output is captured
      into memory and parsed as if it was a file. So the following
      example:

      FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i

      would enumerate the environment variable names in the current
      environment.

      In addition, substitution of FOR variable references has been enhanced.
      You can now use the following optional syntax:

      %~I - expands %I removing any surrounding quotes (")
      %~fI - expands %I to a fully qualified path name
      %~dI - expands %I to a drive letter only
      %~pI - expands %I to a path only
      %~nI - expands %I to a file name only
      %~xI - expands %I to a file extension only
      %~sI - expanded path contains short names only
      %~aI - expands %I to file attributes of file
      %~tI - expands %I to date/time of file
      %~zI - expands %I to size of file
      %~$PATH:I - searches the directories listed in the PATH
      environment variable and expands %I to the
      fully qualified name of the first one found.
      If the environment variable name is not
      defined or the file is not found by the
      search, then this modifier expands to the
      empty string

      The modifiers can be combined to get compound results:

      %~dpI - expands %I to a drive letter and path only
      %~nxI - expands %I to a file name and extension only
      %~fsI - expands %I to a full path name with short names only
      %~dp$PATH:I - searches the directories listed in the PATH
      environment variable for %I and expands to the
      drive letter and path of the first one found.
      %~ftzaI - expands %I to a DIR like output line

      In the above examples %I and PATH can be replaced by other valid
      values. The %~ syntax is terminated by a valid FOR variable name.
      Picking upper case variable names like %I makes it more readable and
      avoids confusion with the modifiers, which are not case sensitive.
      This is my signature.

      Comment


      • #4
        Re: Start Defrag on a Target Machine (VBS)

        Sorry - I haven't had time to reply to this topic properly yet.


        Tom
        For my own and your protection, I do not provide support by private message under any circumstances. All such messages will be deleted and ignored.

        Anything you say will be misquoted and used against you

        Comment


        • #5
          Re: Start Defrag on a Target Machine (VBS)

          is it possible to start it when its run? - like a schedule for 'now'
          and is it also possible to have it prompt for the computer name instead of having it in a list...?


          I haven't had time to read through all this yet...
          1.
          /
          \
          /
          \
          /
          \
          /
          \
          153.
          Sorry - I haven't had time to reply to this topic properly yet.
          No, a scheduled 'run now' is not even possible.

          When you add a scheduledTask (by script or using a commandline or manually), it is very recommended to set the starttime at least two minutes from now (local computer time) to assure it will run.
          The Job then will start somewhere between one and two minutes.

          The reason for this behaviour is because the scheduler does not realy count time but it monitors the flipping minutes from the systemclock. It waits for the event that the minutes changes, that moment it compares the new pattern of minutes/hours/day/month/year with the start time of the job (at that moment the seconds are exact 00). When if you scheduled the job only one minute from now, there is a real change that during the creation of the Job, the minutes of the clock changes and the Job misses its moment to be launched.


          If you want an InputBox where you can type the name of the target computer to run the defrag on, a vbscript can be a good option.
          Then you can use objectshell.Run to run the psexec command line.
          Or, you can use the "Win32_ScheduledJob" class to add a scheduled Job (the 2 minutes it takes at the most to schedule the job is really nothing if you compare it with time the complete defragmentation takes).


          This is an example how you can use inputboxes for computernames and also for choosing a drive letter.
          Code:
          ' RemoteDefrag.vbs
          ' by Remco Simons [nl] 2007
          ' 
          ' http://forums.petri.com/showthread.php?t=16849
          
          strComputer = _
          InputBox(vbNewline&vbNewline&vbNewline&vbNewline&vbNewline& _
          "Computer Name:","Run Defrag on remote computer","?",xpos,ypos)
          If strComputer = Cancel Then cancelscript("")
          
          With WScript.CreateObject("WScript.Shell")
           'http://msdn2.microsoft.com/en-us/library/x83z1d9f.aspx
            BtnCode = .Popup("Connecting....", 1," Please wait", 0+64)
          End With
          
          On Error Resume Next
          Set objWMIService = GetObject("winmgmts:" _
             & "{impersonationLevel=impersonate}!\\" & _
             strComputer & "\root\cimv2")
          Set colDisks = objWMIService.ExecQuery _
             ("SELECT * FROM Win32_LogicalDisk where mediatype = '12'")
           For each objDisk in colDisks
             strDrives = objDisk.DeviceID & "  " & strDrives
           Next
          If err.Number then cancelscript("")
          
          strDrive = _
          InputBox(vbNewline&vbNewline&"Select a drive to Defrag"& _
          vbNewline&vbNewline&vbNewline&"Choose one of the following drives " & _
          "available on '"&Ucase(strComputer)&"' :"&vbNewline&strDrives,"Run " & _
          "Defrag on remote station","C:",xpos,ypos)
          If strDrive = Cancel Then cancelscript("")
          
          strJob = "defrag.exe "& strDrive &" -f"
          
          schtask strComputer, strJob, "false" 
                        '| the third parameter (true/false) tells whether the job 
                        '| should run INTERACTIVE with the user's desktop or not.
          '(The jobs starts within 2 minutes from now)
          
          wscript.quit
          
          
          Sub cancelscript(errJobCreated)
            With WScript.CreateObject("WScript.Shell")
             BtnCode=.Popup("Script aborted", 5,"[ "&errJobCreated & _
             " ]  * * * * * * * * * *", 0+16)
             wscript.quit
            End With
          End Sub
          
          
          Sub schtask(strComputer, Job, interAct)
           On Error Resume Next
           wait = 2 '(= amount of minute 'flippings')
          '___
          '// dlsBIAS, according to the timezone on your! computer
          
          Set objSWbemServices = GetObject("winmgmts:" _
           & "{impersonationLevel=impersonate}!\\.\root\cimv2")
          
          Set colComputer = objSWbemServices.ExecQuery _
           ("SELECT CurrentTimeZone FROM Win32_ComputerSystem")
            For Each objComputer in colComputer
              BiasGMT = objComputer.CurrentTimeZone
              Exit For
            Next
          Set objSWbemServices = Nothing
          If Int(instr(Cstr(BiasGMT),"-"))=1 Then a="-" Else a="+"
          BiasGMT = a & Right(1000 + Abs(BiasGMT),3)
          '___
          '// determine the CURRENT_TIME from the target! computer
          
          Set objWMIService = GetObject("winmgmts:" _
           & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
          Set colItems = objWMIService.ExecQuery("Select * from Win32_LocalTime")
          
          For Each objItem in colItems
            strtTime = (objItem.Hour*100) + (objItem.Minute + wait)
            Exit For
          Next
          '___
          '// create a new SCHEDULEDJOB on the target computer
          '   http://msdn2.microsoft.com/en-us/library/aa394601.aspx
          
          Set objService = GetObject("winmgmts:\\" & strComputer)
          Set objNewJob  = objService.Get("Win32_ScheduledJob")
          
          sScheduled = "********" & Right(10000 + strtTime,4) _
                       & "00.000000" & BiasGMT
          
          errJobCreated = objNewJob.Create _
           (Job, sScheduled, , , , InterAct, JobID)
          
          If Err.Number = 0 Then
           Wscript.Echo "Defragmentation of drive "&strDrive& " on " & _
           UCase(strComputer) & vbNewLine & "will start within 2 minutes."& _
           vbNewLine&vbTab&"( Job ID: " & JobID &" )"
          Else
           cancelscript(errJobCreated)
          End If
          End Sub
          
          Sub cancelscript(errJobCreated)
            With WScript.CreateObject("WScript.Shell")
             BtnCode=.Popup("Script aborted", 5,"[ "&errJobCreated & _
             " ]  * * * * * * * * * *", 0+16)
             wscript.quit
            End With
          End Sub
          This script use the Win32_ScheduledJob,
          but if you don't want that, just remove the Subroutine "Sub schtask(... " completely.
          And also, replace the 4 lines 36 - 39
          (first line (34) = schtask strComputer, strJob, "false"
          last line (39) = '(The jobs starts within 2 minutes from now)

          with these five new lines:
          Code:
          With WScript.CreateObject("WScript.Shell")
          strCommand = "c:\pstools\PSEXEC -i -d -s \\" & strComputer
          strCommand = strCommand & " " & strJob
                .Run strCommand, 1, TRUE
          End With
          \Rems

          This posting is provided "AS IS" with no warranties, and confers no rights.

          __________________

          ** Remember to give credit where credit's due **
          and leave Reputation Points for meaningful posts

          Comment


          • #6
            Re: Start Defrag on a Target Machine (VBS)

            Dude, that's awesome.
            This is my signature.

            Comment


            • #7
              Re: Start Defrag on a Target Machine (VBS)

              is it possible to store the psexec on a remote share and access it through that?

              I have a feeling someone mentioned it before - or I dreamed it...

              can't seem to use \\pc\share\psexec.exe as the path so I feel I am missing something
              This is my signature.

              Comment


              • #8
                Re: Start Defrag on a Target Machine (VBS)

                What are the share permissions on the SHARE? Read Only?
                1 1 was a racehorse.
                2 2 was 1 2.
                1 1 1 1 race 1 day,
                2 2 1 1 2

                Comment


                • #9
                  Re: Start Defrag on a Target Machine (VBS)

                  read only - but a new share could possibly be set up if it needs write access...?

                  but actually since it was me that was testing it with a unc path it would have been full access.


                  strCommand = "\\Pctest1\share\PSEXEC -i -d -s \\" & strComputer
                  should that work fine?
                  Last edited by Lan; 9th July 2007, 15:59. Reason: actually... :P
                  This is my signature.

                  Comment


                  • #10
                    Re: Start Defrag on a Target Machine (VBS)

                    It works fine here.

                    What is the error you get when you run the command like this:
                    Code:
                    strComputer = "computername"
                    strJob = "calc.exe"  '(just for testing)
                    
                    With WScript.CreateObject("WScript.Shell")
                    strCommand = "cmd.exe /k \\Pctest1\share\psexec.exe -i -d -s \\" & strComputer
                    strCommand = strCommand & " " & strJob
                          .Run strCommand, 1, TRUE
                    End With

                    This posting is provided "AS IS" with no warranties, and confers no rights.

                    __________________

                    ** Remember to give credit where credit's due **
                    and leave Reputation Points for meaningful posts

                    Comment


                    • #11
                      Re: Start Defrag on a Target Machine (VBS)

                      That /k I think was missing thankies - that's awesome
                      This is my signature.

                      Comment


                      • #12
                        Re: Start Defrag on a Target Machine (VBS)

                        nvm, starting new thread
                        Last edited by jmk1713; 17th July 2007, 16:29.

                        Comment

                        Working...
                        X