Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

In a comment to my response to this question , cop1152 said he loved WMI scripts. Well, so do I!

What are your favourite, best, most useful scripts you'd like to share with the community?

thanks.

share|improve this question
add comment

6 Answers

up vote 3 down vote accepted

I've corralled a bunch of WMIC snippets here.

share|improve this answer
add comment

One I wrote to help a colleague, who RDPd to a server, opened Event Viewer, looked through it for errors. Then repeated for the other 3 servers... every day.

'
' WMI script to read all eventlog errors generated since last time this script was run.
' This script reads a datetime value from a file (EventView_date.txt) and uses it to
' construct a WMI query for all windows EventLog entries since then that are of type
' Error or error (seems winxp writes with a lowercase e)
'
' These results are written to a file (EventView_<dts>.log) and the time the script was
' run is written to the date file. This allows this script to be run several times a day
' and will only retrieve the error entries since the last run.
'
' If the date file is not present a new one will be created with the current date/time.
'
'
' Usage: click the vbs file in Windows Explorer to run using wscript. Some information
'        will be displayed in message boxes (start time, each computer, number of records found)
'        Alternatively type "cscript EventLogErrorView.vbs" in a command prompt to show the
'        same details written to the command prompt. This can be used in a batch file, or in
'        a scheduled task - the command is cscript, the parameter is this vbs file.
'
'
' 

On Error Resume Next

'
' update this to refelect the computers to monitor - comma separated for multiple
'
arrComputers = Array("server1", "server2")



Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20

Set objFSO = CreateObject("Scripting.FileSystemObject")

today = ""
Set objDateFile = objFSO.OpenTextFile ("EventView_date.txt")
    today = objDateFile.Readline
    Wscript.echo "today = " & today
    if (isempty(today)) then
        WScript.Echo "Date file not found, using today's date at midnight"
        today = Date & " 00:00:00"
    end if

    today = DateToWMIDateString(today)

' write current datetime to file for next run.
set objDateFile = objFSO.CreateTextFile("EventView_date.txt")
objDateFile.WriteLine(Date & " " & Time)

Set objFile = objFSO.CreateTextFile("EventView_" & today & ".log")



' start processing
WScript.Echo "Processing All Error reports since: " & today & " (" & WMIDateStringToDate(today) & ")"
objFile.WriteLine "Processing All Error reports since: " & today & " (" & WMIDateStringToDate(today) & ")"


For Each strComputer In arrComputers
   objFile.WriteLine
   objFile.WriteLine
   objFile.WriteLine
   objFile.WriteLine "=========================================="
   objFile.WriteLine "Computer: " & strComputer
   objFile.WriteLine "=========================================="

   WScript.Echo "Computer: " & strComputer

' notes:
' timestamp comparisons in WMI queries are in the form YYYYMMDDHHMMSS.milliseconds+exp

   Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
   Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_NTLogEvent WHERE (Type = 'error' OR Type= 'Error') AND TimeGenerated > '" & today & ".000000+000'", "WQL", _
                                          wbemFlagReturnImmediately + wbemFlagForwardOnly)

   dim records
   records = 0

   For Each objItem In colItems
        objFile.WriteLine "CategoryString: " & objItem.CategoryString
        objFile.WriteLine "ComputerName: " & objItem.ComputerName
        strData = Join(objItem.Data, ",")
            objFile.WriteLine "Data: " & strData
        objFile.WriteLine "EventCode: " & objItem.EventCode
        objFile.WriteLine "EventIdentifier: " & objItem.EventIdentifier
        objFile.WriteLine "EventType: " & objItem.EventType

        strInsertionStrings = Join(objItem.InsertionStrings, ",")
        objFile.WriteLine "InsertionStrings: " & strInsertionStrings
        objFile.WriteLine "Logfile: " & objItem.Logfile
        objFile.WriteLine "Message: " & objItem.Message

        objFile.WriteLine "SourceName: " & objItem.SourceName
        objFile.WriteLine "TimeGenerated: " & WMIDateStringToDate(objItem.TimeGenerated)

        objFile.WriteLine "Type: " & objItem.Type
        objFile.WriteLine "User: " & objItem.User
        objFile.WriteLine
        objFile.WriteLine "------------------------------------------"
        objFile.WriteLine

        records = records + 1
   Next

   WScript.Echo "          " & records & " records found"
   objFile.WriteLine "          " & records & " records found"
Next



Function WMIDateStringToDate(dtmDate)
    WMIDateStringToDate = CDate(Mid(dtmDate, 5, 2) & "/" & _
    Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) _
    & " " & Mid (dtmDate, 9, 2) & ":" & Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate,13, 2))
End Function

' takes a dd/mm/yyyy hh:mm:ss format and turns it into yyyymmddhhmmss
Function DateToWMIDateString(dtmDate)
DateToWMIDateString = Year(dtmDate) & PadZeros(Month(dtmDate)) & PadZeros(Day(dtmDate)) & PadZeros(Hour(dtmDate)) & PadZeros(Minute(dtmDate)) & PadZeros(Second(dtmDate))
End Function

Function PadZeros(dtmDate)
If Len(dtmDate) = 1 Then
    PadZeros = "0" & dtmDate
Else
    PadZeros = dtmDate
End If
End Function
share|improve this answer
add comment

Everything in Microsoft's (free) tool Scriptomatic2!

share|improve this answer
add comment

One of my favs (because it was my first) that gave me the most trouble...that I wrote over and over and over until it worked correctly....was a script that remotely 'disabled' our homemade web-filter.

We use a 'customized' (by me) version of Squid with some freely available blacklists to content filter and block ports on our public machines (I work for a med-sized, 3-branch public library system).

The WMI script runs on a staff machine. Once a staff member executes it he/she is prompted to select which machine to disable the filter. When the script executes, essentially it removes the check mark from the proxy setting opions in Internet Explorer, at the registry level.

The filter is enabled by a batch file that fires off when the patrons session is up and the computer auto logs off and back on.

We ended up using my WMI only on a few test machines, but I really enjoyed learning how almost anything can be accomplished with WMI.

share|improve this answer
    
I will post some examples later...its late and I am on my way home. –  cop1152 Jun 3 '09 at 23:02
    
go on then.... :) –  gbjbaanb Jun 30 '09 at 12:39
add comment

Script is useful and iam able to execute this. But the file is only showing the information like

========================================== Data: InsertionStrings:


      1 records found

More over ("EventView_" & today & ".log") this file is just creating the file with EventView_00.log not with actual date. As per the syntax it should give data instead off )00 .

share|improve this answer
    
I'm not entirely sure what you're asking. If the date is wrong, assume I am running on UK date formats, you might want to check for errors or modify it to suit you. Also, make sure you change the server array at the top. –  gbjbaanb Jun 30 '09 at 12:43
add comment

From WSH JScript:

// List errors from Windows EventLog (filter only errors from last month).

function leadingzero(str) {
    if (str.length == 1)
        return "0"+str;
    else
        return str;
}
function good_date(d) {
    var dstr = d.getFullYear().toString();
    dstr += leadingzero((d.getMonth()+1).toString());
    dstr += leadingzero(d.getDate().toString());
    dstr += leadingzero(d.getHours().toString());
    dstr += leadingzero(d.getMinutes().toString());
    dstr += leadingzero(d.getSeconds().toString());
    dstr += ".000000-000";
    return dstr;
}

// 24*3600*1000 - one day
// 30*24*3600*1000 - one month
time = good_date(new Date(new Date() - 30*24*3600*1000));

var wbemFlagReturnImmediately = 0x10;
var wbemFlagForwardOnly = 0x20;

var objWMIService = GetObject("winmgmts:\\\\.\\root\\CIMV2");
var items = objWMIService.ExecQuery("SELECT * FROM Win32_NTLogEvent WHERE (Type = 'Ошибка' OR Type = 'Error') AND TimeGenerated > '" + time + "'",
        "WQL", wbemFlagReturnImmediately | wbemFlagForwardOnly);
var enumItems = new Enumerator(items);

for (enumItems.moveFirst(); !enumItems.atEnd(); enumItems.moveNext()) {
    var i = enumItems.item();
    WScript.Echo("Type: " + i.Type + "\n" + "Message: " + i.Message + "\n" + "TimeGenerated: " + i.TimeGenerated);
} 
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.