代码改变世界

vbs 更新补丁

2013-03-22 11:06  雪中风筝  阅读(3495)  评论(0编辑  收藏  举报

最近由于客户需要写了一段vbs,主要有两个功能点:

1、如果可以上网、从internet获取指定文件中的KB号对应的updates 如果不能联网从WSUS获取updates,下载安装

2、日志功能,每次运行要单独写一份日志

Set strArgus = Wscript.Arguments

Dim filePath,computer,currentTime

computer =GetComputerName()

If strArgus.Count > 1 Then
    Wscript.echo "please input less one files as a paramter"
    Wscript.Quit
ElseIf strArgus.Count = 0 Then
    filePath= ".\"&computer&"_List.txt"
ElseIf strArgus.Count = 1 Then
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    strMapping = strArgus(0)
    
    'check the source files on host machine
    If objFso.FileExists(strMapping) = False Then
        filePath= ".\"&computer&"_List.txt"
    Else
        filePath =strMapping
    End If
End If

WScript.Echo vbCRLF & "Would you like to install? (Y/N)"
stdInput = WScript.StdIn.Readline

If (stdInput = "N" or stdInput = "n") Then 
   WScript.Quit
ElseIf(stdInput = "Y" OR stdInput = "y") Then

currentTime= Format_Time(Now,6)

Set updateSession = CreateObject("Microsoft.Update.Session")

WScript.Echo vbCRLF & "Searching All avialiable Softwares..."

Set updateSearcher = updateSession.CreateUpdateSearcher()

'Search for all software updates, already installed and not installed
Set searchResult = updateSearcher.Search("Type='Software'")

Set updateToInstall = CreateObject("Microsoft.Update.UpdateColl")

'Get update title to search for
Dim arrLines,updateTitle,temp,noKB
    arrLines = GetFileLines(filePath)
    If Not(IsArray(arrLines)) Then WScript.Quit
     For x = 0 To UBound(arrLines)
         temp = Trim(arrLines(x))
            updateTitle = Mid(temp,3)
            If Len(updateTitle)>0 Then
                noKB= False
                'updateIsApplicable = False
                'Cycle through search results to look for the update title
                For i = 0 To searchResult.Updates.Count-1
                       Set update = searchResult.Updates.Item(i)
                       If InStr(UCase(update.Title),UCase(updateTitle))>0 Then
                    noKB= True
                       'Update in list of applicable updates 
                       'Determine if it is already installed or not
                          If update.IsInstalled = False Then
                             WScript.Echo vbCRLF & _
                             "Result:"&updateTitle&"更新可用,未安装."
                            Call WriteLog("Result: KB"&updateTitle&"更新可用,未安装.")
                             'updateIsApplicable = True
                             
                             updateToInstall.Add(update)
                           End If 
                    'Else 
                         'noKB= True
                         'WScript.Quit    
                      End If
                Next
                If noKB = False Then
                      noKBFun(updateTitle)
                End If
            End If
        Next
        
        
     End If

    'If updateIsApplicable = False Then
       '        WScript.Echo "Result: Update is not applicable to this machine Or applicable is installed."
    '           Call    WriteLog(updateTitle,"Result: Update is not applicable to this machine Or applicable is installed.")
       '        'WScript.Quit
       'Else
               'Download update
               Set downloader = updateSession.CreateUpdateDownloader() 
               downloader.Updates = updateToInstall
               WScript.Echo vbCRLF & "downloading..."
               Set downloadResult = downloader.Download()
               WScript.Echo "需要下载"&updateToInstall.Count&"个更新。下载结果:" & downloadResult.ResultCode
            Call WriteLog("需要下载"&updateToInstall.Count&"个更新。下载结果:" & downloadResult.ResultCode)
        
               'Install Update
               Set installer = updateSession.CreateUpdateInstaller()
               WScript.Echo vbCRLF & "Installing..."
               installer.Updates = updateToInstall
               Set installationResult = installer.Install()
        
               'Output the result of the installation
               WScript.Echo "Installation Result: " & _
               installationResult.ResultCode
            'Output the result of the installation
              Call WriteLog("Installation Result: " & _
               installationResult.ResultCode)

            For I = 0 to updateToInstall.Count - 1
                      Set updateInstallationResult = installationResult.GetUpdateResult(I)
                      WScript.Echo "Result for " & updateToInstall.Item(I).Title & " is " & installationResult.GetUpdateResult(I).ResultCode
                    Call WriteLog("Result for " & updateToInstall.Item(I).Title & " is " & installationResult.GetUpdateResult(I).ResultCode)
            Next

               WScript.Echo "Reboot Required: " & _
               installationResult.RebootRequired 
               Call WriteLog("Reboot Required: " & _
               installationResult.RebootRequired )

            WScript.Echo vbCRLF & "Would you like to reboot? (Y/N)"
            stdInput = WScript.StdIn.Readline

            If (strInput = "N" or strInput = "n") Then 
                   WScript.Quit
            ElseIf  (stdInput = "Y" OR stdInput = "y") Then
            
                strComputer = "." ' Local Computer

                SET objWMIService = GETOBJECT("winmgmts:{impersonationLevel=impersonate,(Shutdown)}!\\" & _
                strComputer & "\root\cimv2")

                SET colOS = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")

                FOR EACH objOS in colOS
                    objOS.Reboot()
                NEXT
            End If
    'End If
'End If


Function WriteLog(sText)
    Set FSO= CreateObject("Scripting.FileSystemObject")    
    if FSO.fileexists(".\"&computer&"_Log_"&currentTime&".txt") = True Then
        Set Datei = FSO.OpenTextFile(".\"&computer&"_Log_"&currentTime&".txt", 8)
        Datei.Write(Date &"|"& Time &" "+sText+ VbCrlf)
    else
        Set Datei = FSO.CreateTextFile(".\"&computer&"_Log_"&currentTime&".txt", True)
        Datei.Write(Date &"|"& Time & " "+sText+ VbCrlf)
    end if
End Function

Function GetFileLines(sFilePath)
    'WScript.Echo(sFilePath)
        Dim objFSO, oFile
        Set objFSO = CreateObject("Scripting.FileSystemObject")
        If Not(objFSO.FileExists(sFilePath)) Then
            WScript.Echo "File "& sFilePath &" not found."
        WScript.Quit
        End If
        Set oFile = objFSO.OpenTextFile(sFilePath)
        GetFileLines = Split(oFile.ReadAll, VBCrLf)
        oFile.Close
        Set oFile = Nothing
        Set objFSO = Nothing
End Function

Function GetComputerName()    
    Set objNet = CreateObject("WScript.Network")
    GetComputerName= objNet.ComputerName
End Function


Function noKBFun(updateTitle)
    'Update is installed so notify user and quit
                         WScript.Echo vbCRLF & _
                         "Result:"&updateTitle&"没有此安装更新."
                        Call WriteLog("Result: KB"&updateTitle&"没有此安装更新.")
                         'updateIsApplicable = False
End Function

Function Format_Time(s_Time, n_Flag) 
Dim y, m, d, h, mi, s 
Format_Time = "" 
If IsDate(s_Time) = False Then Exit Function 
y = cstr(year(s_Time)) 
m = cstr(month(s_Time)) 
If len(m) = 1 Then m = "0" & m 
d = cstr(day(s_Time)) 
If len(d) = 1 Then d = "0" & d 
h = cstr(hour(s_Time)) 
If len(h) = 1 Then h = "0" & h 
mi = cstr(minute(s_Time)) 
If len(mi) = 1 Then mi = "0" & mi 
s = cstr(second(s_Time)) 
If len(s) = 1 Then s = "0" & s 
Select Case n_Flag 
Case 1 
' yyyy-mm-dd hh:mm:ss 
Format_Time = y & "-" & m & "-" & d & " " & h & ":" & mi & ":" & s 
Case 2 
' yyyy-mm-dd 
Format_Time = y & "-" & m & "-" & d 
Case 3 
' hh:mm:ss 
Format_Time = h & ":" & mi & ":" & s 
Case 4 
' yyyy年mm月dd日 
Format_Time = y & "" & m & "" & d & "" 
Case 5 
' yyyymmdd 
Format_Time = y & m & d 
case 6 
'yyyymmddhhmmss 
format_time= y & m & d & h & mi & s 
End Select 
End Function