Search code examples
vbscriptwmibios

Write console output into a file


I'm attempting to list a Lenovo computer BIOS settings with a VBScript and write the result into a file. I've came to a point where I can write the stuff into a text file, however it writes in only the first setting (record). How do I write all the settings into one file - one by one?

On Error Resume Next
Dim colItems, fso

Set fso = WScript.CreateObject("Scripting.Filesystemobject")
Set f = fso.CreateTextFile("bios-settings" & ".txt", True)

strComputer = "LOCALHOST"
strOptions
Set objWMIService = GetObject("WinMgmts:" _
    &"{ImpersonationLevel=Impersonate}!\\" & strComputer & "\root\wmi")
Set colItems = objWMIService.ExecQuery("Select * from Lenovo_BiosSetting")

For Each objItem In colItems
    If Len(objItem.CurrentSetting) > 0 Then
        Setting = ObjItem.CurrentSetting
        StrItem = Left(ObjItem.CurrentSetting, InStr(ObjItem.CurrentSetting, ",") - 1)
        StrValue = Mid(ObjItem.CurrentSetting, InStr(ObjItem.CurrentSetting, ",") + 1, 256)

        Set selItems = objWMIService.ExecQuery("Select * from Lenovo_GetBiosSelections")
        For Each objItem2 In selItems
            objItem2.GetBiosSelections StrItem + ";", strOptions
        Next

        f.WriteLine StrItem
        f.WriteLine "  current setting  = " + StrValue
        f.WriteLine "  possible settings = " + strOptions
        f.WriteLine
    End If
    f.Close
Next

This is the part where the actual writing to the file is carried out:

f.WriteLine StrItem
f.WriteLine "  current setting  = " + StrValue
f.WriteLine "  possible settings = " + strOptions
f.WriteLine

It writes the BIOS setting name (StrItem), current setting value (StrValue) and possible setting values (strOptions).


Solution

  • The first thing you need to do is remove the

    on error resume next
    

    from your script. This should only be used in specific circumstances to do error handling, not as a way to cut corners for lazy developers.

    If you do so you will get an error complaining about not being able to write to a closed file.

    That then leads to the actual error, you are closing the file after the first write.

    Move the line

    f.Close
    

    outside of your for each loop and it will probably work a lot better.