Can't define f.WriteLine (vbscript) - variables

I want to log my windows updates script, but I get the following error.
800a005b object variable not setline: 28, 1
which refers to:
f.WriteLine 'some text here'
I also tried Dim f.WriteLine and Dim f, neither of which solve my problem.
What should I do to resolve this?
Full code:
set test = CreateObject("Scripting.FileSystemObject")
set f = fso.CreateTextFile(write_to_File,8)
Dim fso
Set fso = WScript.CreateObject("Scripting.Filesystemobject")
Set f = fso.OpenTextFile("C:\output.txt", 2)
f.Close
'End of Script
'ServerSelection values
ssDefault = 0
ssManagedServer = 1
ssWindowsUpdate = 2
ssOthers = 3
strComputer = "." ' Local Computer
'InStr values
intSearchStartChar = 1
dim strTitle
Set updateSession = CreateObject("Microsoft.Update.Session")
Set updateSearcher = updateSession.CreateupdateSearcher()
updateSearcher.ServerSelection = ssWindowsUpdate
Set searchResult = updateSearcher.Search("IsInstalled=0 and Type='Software'")
f.WriteLine "Lijst met beschikbare updates op deze machine:"
For I = 0 To searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(I)
WScript.Echo I + 1 & "> " & update.Title
Next
If searchResult.Updates.Count = 0 Then
f.WriteLine "Er zijn geen updates beschikbaar."
WScript.Quit
End If
f.WriteLine vbCRLF & "Aanmaken lijst met te downloaden updates:"
Set updatesToDownload = CreateObject("Microsoft.Update.UpdateColl")
For I = 0 to searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(I)
addThisUpdate = false
If update.InstallationBehavior.CanRequestUserInput = true Then
WScript.Echo I + 1 & "> skipping: " & update.Title & _
" because it requires user input"
Else
If update.EulaAccepted = false Then
WScript.Echo I + 1 & "> note: " & update.Title & _
" has a license agreement that must be accepted:"
WScript.Echo update.EulaText
update.AcceptEula()
addThisUpdate = false
Else
addThisUpdate = false
End If
End If
If addThisUpdate = true Then
WScript.Echo I + 1 & "> adding: " & update.Title
updatesToDownload.Add(update)
End If
Next
If updatesToDownload.Count = 0 Then
f.WriteLine "All applicable updates were skipped."
WScript.Quit
End If
f.WriteLine vbCRLF & "Downloading updates..."
Set downloader = updateSession.CreateUpdateDownloader()
downloader.Updates = updatesToDownload
downloader.Download()
Set updatesToInstall = CreateObject("Microsoft.Update.UpdateColl")
rebootMayBeRequired = false
f.WriteLine vbCRLF & "Successfully downloaded updates:"
For I = 0 To searchResult.Updates.Count-1
set update = searchResult.Updates.Item(I)
If update.IsDownloaded = true Then
WScript.Echo I + 1 & "> " & update.Title
updatesToInstall.Add(update)
If update.InstallationBehavior.RebootBehavior > 0 Then
rebootMayBeRequired = true
End If
End If
Next
If updatesToInstall.Count = 0 Then
f.WriteLine "No updates were successfully downloaded."
WScript.Quit
End If
If rebootMayBeRequired = true Then
f.WriteLine vbCRLF & "These updates may require a reboot."
End If
f.WriteLine "Installing updates..."
Set installer = updateSession.CreateUpdateInstaller()
installer.Updates = updatesToInstall
Set installationResult = installer.Install()
'Output results of install
f.WriteLine "Installation Result: " & _
installationResult.ResultCode
f.WriteLine "Reboot Required: " & _
installationResult.RebootRequired & vbCRLF
f.WriteLine "Listing of updates installed " & _
"and individual installation results:"
For I = 0 to updatesToInstall.Count - 1
WScript.Echo I + 1 & "> " & _
updatesToInstall.Item(i).Title & _
": " & installationResult.GetUpdateResult(i).ResultCode
Next
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

This code should enable you to use writeline, my example is to a log file
Firstly set test to be a "Scripting.FileSystemObject"
Next set your f to equal test and test points to a log file location (write_to_file), and append to it using value 8
Finally use the f.writeline line to write strings to the log file
set test = CreateObject("Scripting.FileSystemObject")
set f = test.OpenTextFile(write_to_File,8)
f.writeline "Some text here"

Related

Checking Null Value in Access VBA recordset throws null exception?

I have tried this every different way, and it was working yesterday, so I really don't know what changed.
I import a spreadsheet to a temp table in an Access app. Then I set that to be the dao.recordset, and start looping through. I check for the ID to not be null and if not go through checking fields for values, and updating as appropriate. the minute I hit a null, I get a system error "94 - invalid use of null"
It doesn't offer a debug, but I have debugs throughout my code, so I can see where it fails. It fails when I do this check: If IsNull(rstImportCList("columnx")) = False Then
I have tried nz(rstImportCList("columnx"),"") <> "" I have tried rstImportCList("columnx") is not null, and everything else I can think of. Why is the check that is supposed to prevent this error, causing this error?
Edit:
This is the beginning where I declare the recordset I can't get past doing anything with the recordset field.
Dim db As DAO.Database
Dim rstImportCList As DAO.Recordset
Dim RSsql As String
Set db = CurrentDb()
RSsql = "Select * from tblTempImportCList"
Set rstImportCList = db.OpenRecordset(RSsql)
If rstImportCList.EOF Then Exit Sub
Do While Not rstImportCList.EOF
whether I try to check
IsNull(rstImportCList("xyz").Value) = False
or
nz(rstImportCList("xyz").Value,"") <> ""
or
dim x as string
x = rstImportCList!xyz.value
I get the same error 94 invalid use of null.
Any idea why this is?
--edit with more code.
I took some time to take a the beginning and some of each section of the code, so I could make it generic and see if anyone can help. Here is what I am working on. The Code1 and Code2 parts don't seem to be the issue. Sometimes it fails on a null value in a Yes/No column (I'm just looking for Y but the value is null), sometimes on the notes being null. It's not consistent, which is why I'm having a hard time nailing down the issue.
Private Sub cmdImportList_Click()
On Error GoTo cmdImportExcel_Click_err:
Dim fdObj As FileDialog
Set fdObj = Application.FileDialog(msoFileDialogFilePicker)
Dim varfile As Variant
Dim importCT As Integer
Dim dbu As DAO.Database
Dim cBadXVal, cBadYVal As Integer
Dim preNotes As String
Dim RSsql As String
Dim uNotesql, uVal1sql, uVal2sql As String
Dim db As DAO.Database
Dim rstImportCList As DAO.Recordset
Dim CheckB4Import As Integer
CheckB4Import = MsgBox("Are you SURE the sheet you are importing has the following column names in the same order:" & vbCrLf & vbCrLf & _
"IDName/ First/ Mid/ Last/ Sfx/ Age/ Telephone/ Code1/ Code2/ YN1/ YN2/ NY3/ Notes/ AsYN1edTo" & vbCrLf & vbCrLf & _
"AND that there are NO empty rows or empty columns?" & vbCrLf & vbCrLf & _
"Click OK to proceed, Click CANCEL to go double-check your CallSheet before importing.", vbOKCancel, "WITH GREAT POWER COMES GREAT RESPONSIBILITY TO QC DATA")
If CheckB4Import = vbOK Then
CurrentDb.Execute "DELETE * FROM tblTempImportCList", dbFailOnError
With fdObj
'CAN ONLY SELECT 1 FILE
.allowmultiselect = False
.Filters.Clear
.Filters.Add "Excel 2007+", "*.xlsx"
.Title = "Please select the completed list to import:"
.Show
If .SelectedItems.Count = 1 Then
varfile = .SelectedItems(1)
DoCmd.TransferSpreadsheet acImport, , "tblTempImportCList", varfile, True, "Sheet1!"
cBadXVal = DLookup("BadXCount", "qryImpCheckBadXVal")
Debug.Print "cBadXVal - " & cBadXVal
If cBadXVal <> 0 Then
DoCmd.OpenForm "frmImportError", acNormal
Forms!frmImportError.Form.lblErrorMsg.Caption = _
"Oh No! Your list import failed!" & vbCrLf & _
cBadXVal & " X values are not valid." & vbCrLf & _
"Don't worry. You can fix your sheet and re-import!" & vbCrLf & _
"Would you like to open the documentation for the valid codes" & vbCrLf & _
"Or are you all set?"
End If
cBadYVal = DLookup("BadYCount", "qryImpCheckBadYVal")
Debug.Print "cBadYVal - " & cBadYVal
If cBadYVal <> 0 Then
DoCmd.OpenForm "frmImportError", acNormal
Forms!frmImportError.Form.lblErrorMsg.Caption = _
"Oh No! Your list import failed!" & vbCrLf & _
cBadYVal & " YN1 values are not valid." & vbCrLf & _
"Don't worry. You can fix your sheet and re-import!" & vbCrLf & _
"Would you like to open the documentation for the valid codes" & vbCrLf & _
"Or are you all set?"
Exit Sub
End If
Else
MsgBox "No file was selected. Try again!", vbCritical, "Uh-oh Spaghettios!"
End If
End With
'PASSED CHECKS
Set db = CurrentDb()
RSsql = "Select * from tblTempImportCList"
Set rstImportCList = db.OpenRecordset(RSsql)
If rstImportCList.EOF Then Exit Sub
Debug.Print "got here"
Do While Not rstImportCList.EOF
Debug.Print "Start Processing: " & Nz(rstImportCList("IDName").Value, "")
'GET NOTES ALREADY ON RECORD
If Nz(rstImportCList("IDName").Value, "") <> "" Then
Debug.Print "got past if IDName is not null"
If Nz(rstImportCList("Notes").Value, "") <> "" Then
Debug.Print "got past if notes is not null"
preNotes = Replace(Nz(DLookup("Notes", "tblVFileImport", "IDName = " & rstImportCList("IDName").Value), ""), """", "")
'UPDATE NOTES
If Nz(preNotes, "") <> "" Then
uNotesql = "Update tblVFileImport SET tblVFileImport.Notes = '" & preNotes & "; " & Replace(Nz(rstImportCList("Notes").Value, ""), """", "") & "' " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName").Value
'debug.print "Notes"
'debug.print "uNotesql - " & uNotesql
Else
uNotesql = "Update tblVFileImport SET tblVFileImport.Notes = '" & Replace(Nz(rstImportCList("Notes").Value, ""), """", "") & "' " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName").Value
End If
RunMySql (uNotesql)
'DoCmd.RunSQL (uNotesql), dbFailOnError
End If
If Nz(rstImportCList("YN1").Value, "") = "Y" Then
'UPDATE YN1
uYN1sql = "Update tblVFileImport SET tblVFileImport.YN1 = '" & rstImportCList("YN1") & "', tblVFileImport.callprocessed = 'Y' " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName")
Debug.Print "YN1 = Y or y"
Debug.Print "uYN1sql - " & uYN1sql
RunMySql (uYN1sql)
'DoCmd.RunSQL (uYN1sql), dbFailOnError
End If
If Nz(rstImportCList("YN2").Value, "") = "Y" Then
'UPDATE YN2
uYN2sql = "Update tblVFileImport SET tblVFileImport.YN2 = '" & rstImportCList("YN2") & "', tblVFileImport.callprocessed = 'Y' " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName")
Debug.Print "YN2 = Y or y"
Debug.Print "uYN2sql - " & uYN2sql
RunMySql (uYN2sql)
'DoCmd.RunSQL (uYN2sql), dbFailOnError
End If
'START Code1 PROCESSING
If Nz(rstImportCList("Code1").Value, "") <> "" Then
'Code1 Case abc
vdispo = DLookup("Code1", "tblvFileImport", "IDName = " & rstImportCList("IDName"))
If rstImportCList("Code1") = "ABC" Then
Debug.Print "Dispo Case ABC"
'DELETE RECORD
dMDsql = "DELETE from tblVFileImport " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName")
Debug.Print "dMDsql - " & dMDsql
RunMySql (dMDsql)
'DoCmd.RunSQL (dMDsql), dbFailOnError
'Code1 Case DEF OR GHI OR JKL
ElseIf Nz(rstImportCList("Code1"), "") = "DEF" Or Nz(rstImportCList("Code1"), "") = "GHI" Or Nz(rstImportCList("Code1"), "") = "JKL" Then
Debug.Print "Dispo Case DEF OR GHI OR JKL "
'IF DEF
If rstImportCList("Code1") = "DEF" Then
'IF CELL SAME - UPDATE NULL
ccellsame = DLookup("IDName", "tblVFileImport", "IDName = " & rstImportCList("IDName") & " AND nz(Cell,'') = Phone ")
If ccellsame = rstImportCList("IDName") Then
uCellsql = "Update tblVFileImport SET tblVFileImport.Cell = NULL, tblVFileImport.CellString = NULL, tblVFileImport.mobileflag = NULL " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName")
Debug.Print "uCellsql - " & uCellsql
RunMySql (uCellsql)
'DoCmd.RunSQL (uCellsql), dbFailOnError
End If
End If
End If
End If
End If
Debug.Print "End Processing: " & rstImportCList("IDName")
rstImportCList.MoveNext
Loop
Debug.Print "Finished Looping"
rstImportCList.Close
importCT = DCount("IDName", "tblTempImportCList")
MsgBox importCT & " Records imported for list.", vbOKOnly, "List Processed"
Else
MsgBox "Good Call. Check twice, import once!", vbOKOnly, "Better Safe Than Sorry"
End If
Exit Sub
cmdImportExcel_Click_err:
Select Case Err.Number
Case Else
Call MsgBox(Err.Number & " – " & Err.Description, vbCritical + vbOKOnly, "System Error …")
End Select
End Sub
Any suggestions are greatly appreciated. I'm 1/2 tempted to suck this into a SQL table and just execute a stored procedure. I can get it to work in there, I think.
If IsNull(rstImportCList("columnx").Value) Then
otherwise you're checking if the Field object itself is null.
https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/field-object-dao#:~:text=To%20refer%20to,Fields(%22name%22)
This is a case where relying on a default property (in this case Value) causes problems.

vbs script upload only the file name without inside data

The problem of this script is that it shows an unknown error Message while running the script.
I called the function by echo method in my ftp which is "filezilla".
every thing is working fine as it logs into the server check for the path, open channel for data writing. Still dont know where is the problem
Function FTPUpload(sSite, sUsername, sPassword, sLocalFile, sRemotePath)
'This script is provided under the Creative Commons license located
'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
'be used for commercial purposes with out the expressed written consent
'of NateRice.com
Const OpenAsDefault = -2
Const FailIfNotExist = 0
Const ForReading = 1
Const ForWriting = 2
Set oFTPScriptFSO = CreateObject("Scripting.FileSystemObject")
Set oFTPScriptShell = CreateObject("WScript.Shell")
sRemotePath = Trim(sRemotePath)
sLocalFile = Trim(sLocalFile)
'----------Path Checks---------
'Here we willcheck the path, if it contains
'spaces then we need to add quotes to ensure
'it parses correctly.
If InStr(sRemotePath, " ") > 0 Then
If Left(sRemotePath, 1) <> """" And Right(sRemotePath, 1) <> """" Then
sRemotePath = """" & sRemotePath & """"
End If
End If
If InStr(sLocalFile, " ") > 0 Then
If Left(sLocalFile, 1) <> """" And Right(sLocalFile, 1) <> """" Then
sLocalFile = """" & sLocalFile & """"
End If
End If
'Check to ensure that a remote path was
'passed. If it's blank then pass a "\"
If Len(sRemotePath) = 0 Then
'Please note that no premptive checking of the
'remote path is done. If it does not exist for some
'reason. Unexpected results may occur.
sRemotePath = "\"
End If
'Check the local path and file to ensure
'that either the a file that exists was
'passed or a wildcard was passed.
If InStr(sLocalFile, "*") Then
If InStr(sLocalFile, " ") Then
FTPUpload = "Error: Wildcard uploads do not work if the path contains a " & _
"space." & vbCRLF
FTPUpload = FTPUpload & "This is a limitation of the Microsoft FTP client."
Exit Function
End If
ElseIf Len(sLocalFile) = 0 Or Not oFTPScriptFSO.FileExists(sLocalFile) Then
'nothing to upload
FTPUpload = "Error: File Not Found."
Exit Function
End If
'--------END Path Checks---------
'build input file for ftp command
sFTPScript = sFTPScript & "USER " & sUsername & vbCRLF
sFTPScript = sFTPScript & sPassword & vbCRLF
sFTPScript = sFTPScript & "cd " & sRemotePath & vbCRLF
sFTPScript = sFTPScript & "binary" & vbCRLF
sFTPScript = sFTPScript & "prompt n" & vbCRLF
sFTPScript = sFTPScript & "put " & sLocalFile & vbCRLF
sFTPScript = sFTPScript & "quit" & vbCRLF & "quit" & vbCRLF & "quit" & vbCRLF
sFTPTemp = oFTPScriptShell.ExpandEnvironmentStrings("%TEMP%")
sFTPTempFile = sFTPTemp & "\" & oFTPScriptFSO.GetTempName
sFTPResults = sFTPTemp & "\" & oFTPScriptFSO.GetTempName
'Write the input file for the ftp command
'to a temporary file.
Set fFTPScript = oFTPScriptFSO.CreateTextFile(sFTPTempFile, True)
fFTPScript.WriteLine(sFTPScript)
fFTPScript.Close
Set fFTPScript = Nothing
oFTPScriptShell.Run "%comspec% /c FTP -n -s:" & sFTPTempFile & " " & sSite & _
" > " & sFTPResults, 0, TRUE
Wscript.Sleep 1000
'Check results of transfer.
Set fFTPResults = oFTPScriptFSO.OpenTextFile(sFTPResults, ForReading, _
FailIfNotExist, OpenAsDefault)
sResults = fFTPResults.ReadAll
fFTPResults.Close
oFTPScriptFSO.DeleteFile(sFTPTempFile)
oFTPScriptFSO.DeleteFile (sFTPResults)
If InStr(sResults, "226 Transfer complete.") > 0 Then
FTPUpload = True
ElseIf InStr(sResults, "File not found") > 0 Then
FTPUpload = "Error: File Not Found"
ElseIf InStr(sResults, "cannot log in.") > 0 Then
FTPUpload = "Error: Login Failed."
Else
FTPUpload = "Error: Unknown."
End If
Set oFTPScriptFSO = Nothing
Set oFTPScriptShell = Nothing
WScript.Echo "Process Completed (" & Now & ")"
End Function

VB script + delete files that contain word and older then X month

the following VB script , will remove the files under Temp dir and contain the word access.log
how to change this VB script in order to remove only files that contain the word "access.log" and are old then 1 or 2 or 3 ... month
I want to add in the VB some parameter that will contain the month Number
and the files will be deleted according to this parameter
for example if Month_do_del=12
Then only files that contain access.log that old then 12 month will be deleted
If LCase(Right(Wscript.FullName, 11)) = "wscript.exe" Then
strPath = Wscript.ScriptFullName
strCommand = "%comspec% /k cscript """ & strPath & """"
Set objShell = CreateObject("Wscript.Shell")
objShell.Run(strCommand), 1, True
Wscript.Quit
End If
Set objNetwork = CreateObject("WScript.Network")
strLog = "Files deleted on " & objNetwork.ComputerName & " at " & Now & VbCrLf & "===================================================="
Set objFSO = CreateObject("Scripting.FileSystemObject")
strFilesToDelete = ""
ShowSubFolders objFSO.GetFolder("G:\Temp")
If InStr(strFilesToDelete, "|") > 0 Then
arrFiles = Split(strFilesToDelete, "|")
For Each strFilePath In arrFiles
DeleteFile strFilePath
Next
ElseIf strFilesToDelete <> "" Then
DeleteFile strFilesToDelete
Else
WScript.Echo "No files were found."
strLog = strLog & VbCrLf & "No files were found."
End If
Set objLogFile = objFSO.CreateTextFile("C:\FileDeletionLog.log", True)
objLogFile.Write strLog
objLogFile.Close
Set objLogFile = Nothing
Sub ShowSubFolders(Folder)
On Error Resume Next
For Each objFile In Folder.Files
If Err.Number <> 0 Then
WScript.Echo "Error reading " & Folder.Path
strLog = strLog & VbCrLf & "Error reading " & Folder.Path
Err.Clear
On Error Resume Next
Exit For
Else
On Error GoTo 0
If Instr(UCase(objFile.Name), UCase ("access.log")) Then
If strFilesToDelete = "" Then
strFilesToDelete = objFile.Path
Else
strFilesToDelete = strFilesToDelete & "|" & objFile.Path
End If
End If
End If
Next
For Each Subfolder in Folder.SubFolders
ShowSubFolders Subfolder
Next
End Sub
Sub DeleteFile(strFilePath)
On Error Resume Next
WScript.Echo "Deleting " & strFilePath
objFSO.DeleteFile strFilePath, True
If Err.Number <> 0 Then
WScript.Echo "Could not delete " & strFilePath
strLog = strLog & VbCrLf & "Could not delete " & strFilePath
Err.Clear
On Error GoTo 0
Else
On Error GoTo 0
strLog = strLog & VbCrLf & "Successfully deleted " & strFilePath
End If
End Sub
I don't know if FileDateTime, Date and DateDiff are supported in VBS. If not you can easily port your VBS code to VBA. DateDiff will find the difference between two dates in months.
Function CheckMonths(nMonths As Integer, fPath As String) As Boolean
CheckMonths = False
If DateDiff("m", FileDateTime(fPath), Date) = nMonths Then
CheckMonths = True
End If
End Function
Change this line
If Instr(UCase(objFile.Name), UCase ("access.log")) Then
to this
If Instr(1, UCase(objFile.Name), UCase("access.log")) And DateDiff("m", objFile.DateLastModified, Date) >= 12 Then

Insert Reboot Command in Microsoft Update Script

I'm a complete novice in scripting, so starting off just trying to tweak other scripts. I found a script that checks, downloads, and installs Microsoft updates from command line. Is there a way to include a reboot command when complete, or perhaps daisy chain or pipe in a command after it?
To run it, you type cscript.exe ForceAU.vbs
Is there a way to add a command (shutdown /r) to/after it, or does it have to be a setting in the script itself?
'************************************
'* Force Automatic Update Script *
'* Goto http://www.intelliadmin.com *
'* for more tools and utilities *
'************************************
' This script was adapted to only
' install non-prompting updates
' and not ask any questions
' Original script can be found here:
' http://msdn.microsoft.com/en-us/library/windows/desktop/aa387102(v=vs.85).aspx
On Error Resume Next
function IsSecurityUpdate(Update)
Set Categories = Update.Categories
sName = lcase(Categories.Item(0).Name)
'This works on all languages...the category name is always in english
if (sName = "security updates" or sName="critical updates") then
IsSecurityUpdate = TRUE
else
IsSecurityUpdate = FALSE
end if
end function
Sub ForceUpdate()
Set updateSession = CreateObject("Microsoft.Update.Session")
Set updateSearcher = updateSession.CreateupdateSearcher()
WScript.Echo "Searching for updates..." & vbCRLF
Set searchResult = updateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
WScript.Echo vbCRLF & "Creating collection of updates to download:"
Set updatesToDownload = CreateObject("Microsoft.Update.UpdateColl")
bFound = FALSE
For I = 0 to searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(I)
If IsSecurityUpdate(update) then
WScript.Echo " " & update.Title
updatesToDownload.Add(update)
bFound = TRUE
end if
Next
if (NOT(bFound)) then
WScript.Echo "This computer is up to date"
Exit Sub
end if
WScript.Echo vbCRLF & "Downloading updates..."
Set downloader = updateSession.CreateUpdateDownloader()
downloader.Updates = updatesToDownload
downloader.Download()
WScript.Echo vbCRLF & "List of downloaded updates:"
For I = 0 To searchResult.Updates.Count-1
Set update = searchResult.Updates.Item(I)
If update.IsDownloaded Then
WScript.Echo I + 1 & "> " & update.Title
End If
Next
Set updatesToInstall = CreateObject("Microsoft.Update.UpdateColl")
WScript.Echo vbCRLF & _
"Creating collection of downloaded updates to install:"
For I = 0 To searchResult.Updates.Count-1
set update = searchResult.Updates.Item(I)
If update.IsDownloaded = true Then
if (IsSecurityUpdate(update)) then
WScript.Echo I + 1 & "> adding: " & update.Title
updatesToInstall.Add(update)
end if
End If
ext
WScript.Echo "Installing updates..."
Set installer = updateSession.CreateUpdateInstaller()
installer.Updates = updatesToInstall
Set installationResult = installer.Install()
'Output results of install
WScript.Echo "Installation Result: " & _
installationResult.ResultCode
WScript.Echo "Reboot Required: " & _
installationResult.RebootRequired & vbCRLF
WScript.Echo "Listing of updates installed " & _
"and individual installation results:"
For I = 0 to updatesToInstall.Count - 1
WScript.Echo I + 1 & "> " & _
updatesToInstall.Item(i).Title & _
": " & installationResult.GetUpdateResult(i).ResultCode
Next
end sub
ForceUpdate()
if (Err.Number<>0) then
WScript.Echo "Error Downloading Updates. Check your internet connection"
end if
You can try to execute "shutdown -r -t 5" will reboot after 5 seconds.
Maybe something like this:
Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "cmd shutdown -r -t 5"

WMI to get drive letter association with physical drive path, misses CDROMs

I'm running the following WMI script to get the associations between drive letters and physical drives on the system, but for some reason it omits CDROMs/DVD-ROMs. Can someone tell me how to get those as well?
ComputerName = "."
Set wmiServices = GetObject _
("winmgmts:{impersonationLevel=Impersonate}!//" & ComputerName)
Set wmiDiskDrives = wmiServices.ExecQuery _
("SELECT DeviceID FROM Win32_DiskDrive")
For Each wmiDiskDrive In wmiDiskDrives
strEscapedDeviceID = _
Replace(wmiDiskDrive.DeviceID, "\", "\\", 1, -1, vbTextCompare)
Set wmiDiskPartitions = wmiServices.ExecQuery _
("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=""" & _
strEscapedDeviceID & """} WHERE " & _
"AssocClass = Win32_DiskDriveToDiskPartition")
For Each wmiDiskPartition In wmiDiskPartitions
Set wmiLogicalDisks = wmiServices.ExecQuery _
("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""" & _
wmiDiskPartition.DeviceID & """} WHERE " & _
"AssocClass = Win32_LogicalDiskToPartition")
For Each wmiLogicalDisk In wmiLogicalDisks
WScript.Echo wmiLogicalDisk.DeviceID & " = " & wmiDiskDrive.DeviceID
Next
Next
Next
Considering all of the comments thus far, here is a script that adds the capability to list CD-Rom drives.
ComputerName = "."
Set dictDrives = CreateObject("Scripting.Dictionary")
Set listDriveLetters = CreateObject("System.Collections.ArrayList")
Set wmiServices = GetObject _
("winmgmts:{impersonationLevel=Impersonate}!//" & ComputerName)
Set wmiDiskDrives = wmiServices.ExecQuery _
("SELECT DeviceID FROM Win32_DiskDrive")
For Each wmiDiskDrive In wmiDiskDrives
strEscapedDeviceID = Replace(wmiDiskDrive.DeviceID, "\", "\\", 1, -1, vbTextCompare)
Set wmiDiskPartitions = wmiServices.ExecQuery _
("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=""" & _
strEscapedDeviceID & """} WHERE " & _
"AssocClass = Win32_DiskDriveToDiskPartition")
For Each wmiDiskPartition In wmiDiskPartitions
Set wmiLogicalDisks = wmiServices.ExecQuery _
("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""" & _
wmiDiskPartition.DeviceID & """} WHERE " & _
"AssocClass = Win32_LogicalDiskToPartition")
For Each wmiLogicalDisk In wmiLogicalDisks
listDriveLetters.Add wmiLogicalDisk.DeviceID
dictDrives.Add wmiLogicalDisk.DeviceID, wmiDiskDrive.DeviceID
Next
Next
Next
Set wmiCDROMDrives = wmiServices.ExecQuery _
("Select DeviceID, Drive, MediaLoaded from Win32_CDROMDrive")
For Each wmiCDROMDrive in wmiCDROMDrives
If wmiCDROMDrive.MediaLoaded Then ' Only show drives with inserted media
listDriveLetters.Add wmiCDROMDrive.Drive
dictDrives.Add wmiCDROMDrive.Drive, wmiCDROMDrive.DeviceID
End If
Next
listDriveLetters.Sort ' List the drives in alphabetical order
For Each strDriveLetter in listDriveLetters
WScript.Echo strDriveLetter & " = " & dictDrives.Item(strDriveLetter)
Next
I think you wouldn need to use the Win32_CDROMDrive WMI class to access CD-ROM info. The code you have above is looking for physical drives in the Win32_DiskDrive class, it excludes CD_ROM
You could additional lines to get similar data - but not the same given CD-ROMs don't have the Partition characteristics that your current code does
ComputerName = "."
Set wmiServices = GetObject _
("winmgmts:{impersonationLevel=Impersonate}!//" & ComputerName)
Set wmiDiskDrives = wmiServices.ExecQuery _
("SELECT * FROM Win32_CDROMDrive")
For Each wmiDiskDrive In wmiDiskDrives
MsgBox wmiDiskDrive.drive & "=" & wmiDiskDrive.DeviceID
Next
Instead I think this different VBS may do what you want - the may part as I dont think the partition info is relevant to you.
vbs version
Dim objFSO
Dim colDrives
Dim strOut
Dim strArray
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set colDrives = objFSO.Drives
strArray = Array("Unknown", "Removable", "Fixed", "Network", "CD-ROM", "RAM Disk")
On Error Resume Next
'File system errors for virtual drives
For Each objDrive In colDrives
strOut = "Drive letter: " & objDrive.DriveLetter & vbNewLine
strOut = strOut & ("Drive type: " & strArray(objDrive.DriveType) & vbNewLine)
strOut = strOut & ("File system: " & objDrive.FileSystem & vbNewLine)
strOut = strOut & ("Path: " & objDrive.Path)
wscript.echo strOut
Next
On Error GoTo 0
vba version
Sub Test()
Dim objFSO As Object
Dim colDrives As Object
Dim strOut As String
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set colDrives = objFSO.Drives
On Error Resume Next
'File system errors for virtual drives
For Each objDrive In colDrives
strOut = "Drive letter: " & objDrive.DriveLetter & vbNewLine
strOut = strOut & ("Drive type: " & Choose(objDrive.DriveType + 1, "Unknown", "Removable", "Fixed", "Network", "CD-ROM", "RAM Disk") & vbNewLine)
strOut = strOut & ("File system: " & objDrive.FileSystem & vbNewLine)
strOut = strOut & ("Path: " & objDrive.Path)
MsgBox strOut
Next
On Error GoTo 0
End Sub