vbs script works on 86 but fails on 64 - windows

the script works on x86 but doesnt create the file on x64.
Can anyone understand why and explain?
The script is searching the registry, Uninstall key and checking for displayname equal to what im searching for, and grabbing the productcode, and saving to a file which then copies to a remote share i have set up.
On error resume Next
Dim strName, WshShell, oReg, keyname, WshNetwork, ComputerName
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreateObject("WScript.Shell")
Set WshNetwork = WScript.CreateObject("WScript.Network")
Const HKEY_LOCAL_MACHINE = &H80000002
Const ForReading = 1, ForWriting = 2, ForAppending = 8
ComputerName = WshNetwork.ComputerName
FileName = ComputerName & "_data.txt"
'FileName = "sep_data.txt"
'=============================================
'Chage the value here with DisplayName's value
strName = "Symantec Endpoint Protection"
'=============================================
'currentDirectory = Left(WScript.ScriptFullName,(Len(WScript.ScriptFullName))-(Len(WScript.ScriptName)))
currentDirectory = "c:\windows\temp\"
'set location in registry we want to get data from
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & ComputerName & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
oReg.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys
'check each key in uninstall for any display name called Symantec Endpoint Protection
For Each subkey In arrSubKeys
keyname = ""
keyname = wshshell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" & subkey & "\DisplayName")
If keyname = strName then
i = subkey
End If
' Writes text to file if it exists
If i Then
'open text file for writing
Set filetxt = fso.OpenTextFile(currentDirectory & FileName, 2, True)
'write to text file
filetxt.WriteLine "" & computerName & "," & i & ""
'Close file
filetxt.Close
'Copy file to network share
fso.CopyFile "c:\windows\temp\" & FileName & "", "\\hostname\test\", true
End If
Next
Set WshShell = Nothing
Set ObjReg = Nothing
Set computerName = Nothing
Set i = Nothing
WScript.Quit

Here you can find why (in short there are separate structures for 32 and 64 bits in the registry and the file system access is redirected)
For a how, if the application/registry is 32 bit, start the script using the 32 bit script host version (in 64b OS versions, the 32b executables are under %systemroot%\SysWOW64)
"%systemroot%\SysWOW64\cscript.exe" myscript.vbs
The inverse problem, you have a 32 bits process but you need to access the 64 bit registry, requires the start of a 64 bit process, and here things change.
While the executables in %systemroot%\System32 are 64 bits, as the current process is 32 bits it is running under a registry and file system redirection and any reference to %systemroot%\System32 in converted to a reference to %systemroot%\SysWOW64 (32bit processes expect a 32bit OS). This can be solved using
"%systemroot%\sysnative\cscript.exe" myscript.vbs
Yes, if you search the sysnative folder from a 64 bit process you will not find it, but from a 32 bit process it gives you access to the 64 bit system32 folder.
edited to include a workaround. The basic idea is to try to find the required information using the current engine. If not found, the script relaunches itself with a different host.
Option Explicit
Const HKEY_LOCAL_MACHINE = &H80000002
Const ForReading = 1 _
, ForWriting = 2 _
, ForAppending = 8
Const UNINSTALL_KEY_PATH = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
Const KEY_DISPLAY_NAME = "Symantec Endpoint Protection"
Const TARGET_FOLDER = "C:\TEMP"
Const ARGUMENT_FLAG = "_CHILD_"
Dim shell
Set shell = WScript.CreateObject("WScript.Shell")
Dim retValue, alternateHost
If Not WScript.Arguments.Named.Exists(ARGUMENT_FLAG) Then
retValue = shell.Run( quote(WScript.FullName) & " " & quote(WScript.ScriptFullName) & " /" & ARGUMENT_FLAG, 0, True )
If retValue > 0 Then
With WScript.CreateObject("Scripting.FileSystemObject")
If .GetFile( WScript.FullName ).ParentFolder.Name = "SysWOW64" Then
alternateHost = "\sysnative\"
Else
alternateHost = "\SysWOW64\"
End If
alternateHost = .BuildPath( shell.ExpandEnvironmentStrings("%systemroot%") & alternateHost, "cscript.exe" )
If .FileExists( alternateHost ) Then
Call shell.Run( quote(alternateHost) & " " & quote(WScript.ScriptFullName) & " /" & ARGUMENT_FLAG, 0, True )
End If
End With
End If
WScript.Quit
End If
Dim reg
Set reg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
Dim subKeys, subKey, value, keyFound
keyFound = False
reg.EnumKey HKEY_LOCAL_MACHINE, UNINSTALL_KEY_PATH, subKeys
For Each subKey In subKeys
reg.GetStringValue HKEY_LOCAL_MACHINE, UNINSTALL_KEY_PATH & "\" & subkey , "DisplayName", value
If Not IsNull( value ) Then
If value = KEY_DISPLAY_NAME Then
keyFound = True
Exit For
End If
End If
Next
Dim computerName, baseName, fileName, exitCode
If keyFound Then
computerName = WScript.CreateObject("WScript.Network").ComputerName
baseName = computerName & "_data.txt"
With WScript.CreateObject("Scripting.FileSystemObject")
fileName = .BuildPath( shell.ExpandEnvironmentStrings("%temp%"), baseName )
.CreateTextFile( fileName, True ).WriteLine( computerName & "," & KEY_DISPLAY_NAME )
.CopyFile fileName, .BuildPath( TARGET_FOLDER, .GetFile( fileName ).Name )
End With
exitCode = 0
Else
exitCode = 1
End If
Call WScript.Quit( exitCode )
Function quote( text )
quote = """" & text & """"
End Function

i used an alternative method to move the file to a share. why the 64 bit os was getting missed was due to my reg query call. it was missing /reg64 at the end.

Related

"dir" parameter in Shell.Execute command doesn't work when "verb" parameter contains "runas" option [duplicate]

I need to copy my file "manufacturer.bmp", wich is located in the same directory as the script (in my flash drive), to the system32 directory.
I succeed, in getting the variables sourcefile, destinationdirectory, and to elevate my script, but when I elevate it, my sourcefile variable is lost, because of the use of CurrentDirectory, which differs in this mode.
Set shell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
CurrentDirectory = fso.GetAbsolutePathName(".")
sourcefile = fso.buildpath(CurrentDirectory, "manufacturer.bmp")
MsgBox(sourcefile)
'Checks if the script is running elevated (UAC)
Function isElevated
Set shell = CreateObject("WScript.Shell")
Set whoami = shell.Exec("whoami /groups")
Set whoamiOutput = whoami.StdOut
strWhoamiOutput = whoamiOutput.ReadAll
If InStr(1, strWhoamiOutput, "S-1-16-12288", vbTextCompare) Then
isElevated = True
Else
isElevated = False
End If
End Function
'Re-runs the process prompting for priv elevation on re-run
Sub uacPrompt
'Check if we need to run in C or W script
interpreter = "wscript.exe"
If InStr(1, WScript.FullName, "CScript", vbTextCompare) = 0 Then
interpreter = "wscript.exe"
Else
interpreter = "cscript.exe"
End If
'Start a new instance with an elevation prompt first
Set shellApp = CreateObject("Shell.Application")
shellApp.ShellExecute interpreter, Chr(34) & WScript.ScriptFullName & _
Chr(34) & " uac", "", "runas", 1
'End the non-elevated instance
WScript.Quit
End Sub
'Make sure we are running elevated, prompt if not
If Not isElevated Then uacPrompt
destinationdir = fso.buildpath(shell.ExpandEnvironmentStrings("%windir%"), _
"system32")
MsgBox(destinationdir)
fso.CopyFile sourcefile, destinationdir
Any idea of how to push my sourcefile var to the child elevated script?
The ShellExecute method allows you to specify the working directory as the 3rd argument, so you can pass the current directory to the elevated script and build the sourcefile path after elevation. Also, your code could be streamlined quite a bit.
Const HKLM = &h80000002
Const DELETE = &h10000
Set sh = CreateObject("WScript.Shell")
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
reg.CheckAccess HKLM, "SYSTEM\CurrentControlSet", DELETE, isAdmin
If Not isAdmin Then
If WScript.Arguments.Count = 0 Then
CreateObject("Shell.Application").ShellExecute WScript.FullName, _
Chr(34) & WScript.ScriptFullName & Chr(34) & " uac", _
sh.CurrentDirectory, "runas", 1
WScript.Quit 0
Else
WScript.Echo "Privilege elevation failed!"
WScript.Quit 1
End If
End If
Set fso = CreateObject("Scripting.FileSystemObject")
src = fso.BuildPath(sh.CurrentDirectory, "manufacturer.bmp")
dst = fso.buildpath(sh.ExpandEnvironmentStrings("%windir%"), "system32")
fso.CopyFile src, dst & "\"
Edit: or at least that's how it would work if you weren't elevating the process. According to this blog post from Raymond Chen the start directory is ignored when elevating processes, so that malicious DLLs from the current directory aren't loaded into elevated processes by mistake. Meaning that you must pass the working directory "manually", like this:
Const HKLM = &h80000002
Const DELETE = &h10000
Set sh = CreateObject("WScript.Shell")
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
reg.CheckAccess HKLM, "SYSTEM\CurrentControlSet", DELETE, isAdmin
If Not isAdmin Then
If WScript.Arguments.Count = 0 Then
CreateObject("Shell.Application").ShellExecute WScript.FullName, _
Chr(34) & WScript.ScriptFullName & Chr(34) & " " & _
Chr(34) & sh.CurrentDirectory & Chr(34), , "runas", 1
WScript.Quit 0
Else
WScript.Echo "Privilege elevation failed!"
WScript.Quit 1
End If
End If
sh.CurrentDirectory = WScript.Arguments(0)
Set fso = CreateObject("Scripting.FileSystemObject")
src = fso.BuildPath(sh.CurrentDirectory, "manufacturer.bmp")
dst = fso.buildpath(sh.ExpandEnvironmentStrings("%windir%"), "system32")
fso.CopyFile src, dst & "\"
Note that since your destination path is a folder, it must have a trailing backslash (as documented).

transfer CurrentDirectory from un-elevated script to elevated one

I need to copy my file "manufacturer.bmp", wich is located in the same directory as the script (in my flash drive), to the system32 directory.
I succeed, in getting the variables sourcefile, destinationdirectory, and to elevate my script, but when I elevate it, my sourcefile variable is lost, because of the use of CurrentDirectory, which differs in this mode.
Set shell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
CurrentDirectory = fso.GetAbsolutePathName(".")
sourcefile = fso.buildpath(CurrentDirectory, "manufacturer.bmp")
MsgBox(sourcefile)
'Checks if the script is running elevated (UAC)
Function isElevated
Set shell = CreateObject("WScript.Shell")
Set whoami = shell.Exec("whoami /groups")
Set whoamiOutput = whoami.StdOut
strWhoamiOutput = whoamiOutput.ReadAll
If InStr(1, strWhoamiOutput, "S-1-16-12288", vbTextCompare) Then
isElevated = True
Else
isElevated = False
End If
End Function
'Re-runs the process prompting for priv elevation on re-run
Sub uacPrompt
'Check if we need to run in C or W script
interpreter = "wscript.exe"
If InStr(1, WScript.FullName, "CScript", vbTextCompare) = 0 Then
interpreter = "wscript.exe"
Else
interpreter = "cscript.exe"
End If
'Start a new instance with an elevation prompt first
Set shellApp = CreateObject("Shell.Application")
shellApp.ShellExecute interpreter, Chr(34) & WScript.ScriptFullName & _
Chr(34) & " uac", "", "runas", 1
'End the non-elevated instance
WScript.Quit
End Sub
'Make sure we are running elevated, prompt if not
If Not isElevated Then uacPrompt
destinationdir = fso.buildpath(shell.ExpandEnvironmentStrings("%windir%"), _
"system32")
MsgBox(destinationdir)
fso.CopyFile sourcefile, destinationdir
Any idea of how to push my sourcefile var to the child elevated script?
The ShellExecute method allows you to specify the working directory as the 3rd argument, so you can pass the current directory to the elevated script and build the sourcefile path after elevation. Also, your code could be streamlined quite a bit.
Const HKLM = &h80000002
Const DELETE = &h10000
Set sh = CreateObject("WScript.Shell")
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
reg.CheckAccess HKLM, "SYSTEM\CurrentControlSet", DELETE, isAdmin
If Not isAdmin Then
If WScript.Arguments.Count = 0 Then
CreateObject("Shell.Application").ShellExecute WScript.FullName, _
Chr(34) & WScript.ScriptFullName & Chr(34) & " uac", _
sh.CurrentDirectory, "runas", 1
WScript.Quit 0
Else
WScript.Echo "Privilege elevation failed!"
WScript.Quit 1
End If
End If
Set fso = CreateObject("Scripting.FileSystemObject")
src = fso.BuildPath(sh.CurrentDirectory, "manufacturer.bmp")
dst = fso.buildpath(sh.ExpandEnvironmentStrings("%windir%"), "system32")
fso.CopyFile src, dst & "\"
Edit: or at least that's how it would work if you weren't elevating the process. According to this blog post from Raymond Chen the start directory is ignored when elevating processes, so that malicious DLLs from the current directory aren't loaded into elevated processes by mistake. Meaning that you must pass the working directory "manually", like this:
Const HKLM = &h80000002
Const DELETE = &h10000
Set sh = CreateObject("WScript.Shell")
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
reg.CheckAccess HKLM, "SYSTEM\CurrentControlSet", DELETE, isAdmin
If Not isAdmin Then
If WScript.Arguments.Count = 0 Then
CreateObject("Shell.Application").ShellExecute WScript.FullName, _
Chr(34) & WScript.ScriptFullName & Chr(34) & " " & _
Chr(34) & sh.CurrentDirectory & Chr(34), , "runas", 1
WScript.Quit 0
Else
WScript.Echo "Privilege elevation failed!"
WScript.Quit 1
End If
End If
sh.CurrentDirectory = WScript.Arguments(0)
Set fso = CreateObject("Scripting.FileSystemObject")
src = fso.BuildPath(sh.CurrentDirectory, "manufacturer.bmp")
dst = fso.buildpath(sh.ExpandEnvironmentStrings("%windir%"), "system32")
fso.CopyFile src, dst & "\"
Note that since your destination path is a folder, it must have a trailing backslash (as documented).

how to add a log to my vbscript

i have this script that reads a list of computers and check to see if the computers have the right software version install. the script echo to me the computers with the wrong version, but i want to make a log instead
Dim strComputer, objFSO, ObjShell, strDisplayName, objList, strObject
Dim objReg, arrSubKeys, strProduct, strVersion, strReqVersion
Const For_Writing = 2
Const ForReading = 1
const ForAppending = 3
Const HKLM = &H80000002
Const strKeyPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
strReqVersion = "8.2.1 MP2"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("WScript.Shell")
Set objList = objFSO.OpenTextFile("c:\test\test.txt",ForReading)
Do While Not objList.AtEndOfStream
strComputer = objList.ReadLine
If HostOnline(strComputer) = True Then
Inventory(strComputer)
End If
Loop
Function Inventory(strComputer)
Set objTextFile = objFSO.OpenTextFile("c:\test\inventory.txt",2,true)
'creating a dictionary object
Set objDictionary = CreateObject("Scripting.Dictionary")
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
' Enumerate the subkeys of the Uninstall key
objReg.EnumKey HKLM, strKeyPath, arrSubKeys
For Each strProduct In arrSubKeys
' Get the product's display name
objReg.GetStringValue HKLM, strKeyPath & "\" & strProduct, "DisplayName", strDisplayName
' Process only products whose name contain 'symantec'
If InStr(1, strDisplayName, "Symantec", vbTextCompare) > 0 Then
' Get the product's display version
objReg.GetStringValue HKLM, strKeyPath & "\" & strProduct, "DisplayVersion", strVersion
If strReqVersion <> strVersion Then
WScript.Echo strObject
objDictionary.Add strComputer, strVersion
For Each strObject In objDictionary
WScript.Echo strObject
objTextFile.WriteLine(strObject)
Next
objTextFile.Close
End If
End If
Next
End Function
Function HostOnline(strComputername)
'---------- Test to see if host or url alive through ping -----------------
' Returns True if Host responds to ping
'
' strComputername is a hostname or IP
Const OpenAsASCII = 0
Const FailIfNotExist = 0
Const ForReading = 1
Dim objShell, objFSO, sTempFile, fFile
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
sTempFile = objFSO.GetSpecialFolder(2).ShortPath & "\" & objFSO.GetTempName
objShell.Run "cmd /c ping -n 2 -l 8 " & strComputername & ">" & sTempFile, 0 , True
Set fFile = objFSO.OpenTextFile(sTempFile, ForReading, FailIfNotExist, OpenAsASCII)
Select Case InStr(fFile.ReadAll, "TTL=")
Case 0
HostOnline = False
Case Else
HostOnline = True
End Select
ffile.close
objFSO.DeleteFile(sTempFile)
Set objFSO = Nothing
Set objShell = Nothing
End Function
can some one help me please thanks
There are several ways to do this. The simplest way, without any modification to your script, would be to call the script with cscript.exe (in a command prompt) and redirect the output to a file:
cscript your.vbs > output.log
However, if you want a log to be created even when users double-click your script you'll have to change your script so that it writes to a file instead of echoing the output. Open the log file at the beginning of the script:
Set myLog = objFSO.OpenTextFile("C:\my.log", For_Writing, True)
replace WScript.Echo ... with myLog.WriteLine ..., and close the file before you exit from the script:
myLog.Close
A somewhat more sophisticated approach would be to create a set of logging functions, which will allow you create log lines depending on certain conditions, e.g. LogInfo() for informational log messages and LogError() for errors.
Shameless plug: Some time ago I got fed up with writing the same boilerplate logging functions over and over again, so I wrote a logger class that encapsulates the usual logging facilities (interactive console, files, eventlog) and provides logging methods for 4 log levels (Error, Warning, Information, Debug). The class can be used for logging to a file like this:
Set myLog = New CLogger
myLog.LogToConsole = False
myLog.LogFile = "C:\my.log"
myLog.LogInfo "info message"
...
myLog.LogError "an error occurred"
The log file is automatically closed when the object is released.
Why not use the system's event log? I described how in this answer
It means most of the work is done for you and you don't need to worry about where to put your log file

Searching the registry and i need the output of Path from list of servers using VBscript

Below Script is working fine ,it gets the path of the key i am searching . Please some one help me to find the way to read the list of servers from text file. im learning vbscript and tried some ways to read the text file it fails.
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "Server name"
const REG_SZ = 1
const REG_EXPAND_SZ = 2
const REG_BINARY = 3
const REG_DWORD = 4
const REG_MULTI_SZ = 7
strOriginalKeyPath = "SOFTWARE\VMware, Inc.\VMware Tools"
FindKeyValue(strOriginalKeyPath)
'-------------------------------------------------------------------------
Function FindKeyValue(strKeyPath)
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_
strComputer & "\root\default:StdRegProv")
errorCheck = oReg.EnumKey(HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys)
If (errorCheck=0 and IsArray(arrSubKeys)) then
For Each subkey In arrSubKeys
strNewKeyPath = strKeyPath & "\" & subkey
FindKeyValue(strNewKeyPath)
Next
End If
oReg.EnumValues HKEY_LOCAL_MACHINE, strKeyPath, _
arrValueNames, arrValueTypes
If (errorCheck=0 and IsArray(arrValueNames)) then
For i=0 To UBound(arrValueNames)
'Wscript.Echo "Value Name: " & arrValueNames(i)
if arrValueNames(i) = "InstallPath" then
strValueName = arrValueNames(i)
oReg.GetDWORDValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, dwValue
wscript.echo strComputer & "\" & strkeyPath & vbNewLine
end if
Next
End if
end Function
Following is some code I use to read a list of machine names like:
MACHINE1
MACHINE2
MACHINE3
Into an array, which you can then loop through with a "For" statement.
pcList = readlist("C:\temp\testlist.txt")
'
' Reads in a list of PC names from a file and returns
' an array containing one PC name per member.
'
' Blank lines are ignored.
' Lines starting with ";" are treated as comments and
' are not added to the list.
'
'
function ReadList(listfile)
const forReading = 1
dim thelist()
redim thelist(1)
listLen = 0
set theFSO = createobject("Scripting.FileSystemObject")
set listFile = theFSo.openTextFile(listfile,forReading)
while not listFile.atendofstream
pcname = ltrim(rtrim(listFile.readline))
if len(pcname)>1 and left(pcname,1)<>";" then
if listlen = 0 then
thelist(0) = pcname
listlen = listlen+1
else
redim preserve thelist(listlen)
thelist(listlen) = pcname
listlen = listlen + 1
end if
end if
wend
listfile.close
set listfile = nothing
set thefso = nothing
ReadList = theList
end Function

vbscript filesystemobject permission denied

I'm having a problem with Trend OfficeScan Patterns filling up the C:\ drive (no other drives available to change directories) and I'm getting a permission denied error accessing "C:\Program Files\Trend Micro\OfficeScan\PCCSRV\WSS\patterns" running the below script. As I'll be using this script for a few sites, and to make it easy to implement for my colleagues, I don't want to play around adding various permissions.
I tried changing: PatternLocation = (strValue & "WSS\patterns\") to PatternLocation = ("""" & strValue & "WSS\patterns\""") and I get 'Path not found'. Are there any VBScript experts that may be able to recommend an impersonate method to overcome the permissions denied?
' Variable to locate HLM.
const HKEY_LOCAL_MACHINE = &H80000002
Set fso = CreateObject("Scripting.FileSystemObject")
' Checks if the operating system is x86 or x64
Set objShell = CreateObject("WScript.Shell")
osType = objShell.ExpandEnvironmentStrings("%PROCESSOR_ARCHITECTURE%")
' The dot refers to the computer this vbscript has been run on.
strComputer = "."
' Provides connection to the registry.
Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_
strComputer & "\root\default:StdRegProv")
' Checks the bit for the operating system
If osType = "x86" Then
' Checks registry for Trend folder path.
strKeyPath = "SOFTWARE\TrendMicro\OfficeScan\Service\Information"
Elseif osType = "AMD64" Then
strKeyPath = "SOFTWARE\Wow6432Node\TrendMicro\OfficeScan\service\Information"
End if
trValueName = "Local_Path"
objReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
' If the registry path is empty it won't install the scheduled task and alert you.
If IsNull(strValue) Then
msgbox("Trend Micro is not installed.")
else
PatternLocation = (strValue & "WSS\patterns\") ' folder to start deleting (subfolders will also be cleaned)
OlderThanDate = DateAdd("d", -2, Date) ''# 2 days (adjust as necessary)
DeleteOldFiles PatternLocation, OlderThanDate
end if
Function DeleteOldFiles(folderName, BeforeDate)
Dim folder, file, fileCollection, folderCollection, subFolder
Set folder = fso.GetFolder(folderName)
Set fileCollection = folder.Files
For Each file In fileCollection
If file.DateLastModified < BeforeDate Then
fso.DeleteFile(file.Path)
End If
Next
Set folderCollection = folder.SubFolders
For Each subFolder In folderCollection
DeleteOldFiles subFolder.Path, BeforeDate
Next
End Function
This is the working script with a few changes for anyone who might find it useful:
'Variable to locate HLM.
const HKEY_LOCAL_MACHINE = &H80000002
Set fso = CreateObject("Scripting.FileSystemObject")
'Checks if the operating system is x86 or x64
Set objShell = CreateObject("WScript.Shell")
osType = objShell.ExpandEnvironmentStrings("%PROCESSOR_ARCHITECTURE%")
'The dot refers to the computer this vbscript has been run on.
strComputer = "."
'Provides connection to the registry.
Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_
strComputer & "\root\default:StdRegProv")
'Checks the bit for the operating system
If osType = "x86" Then
'Checks registry for Trend folder path.
strKeyPath = "SOFTWARE\TrendMicro\OfficeScan\Service\Information"
Elseif osType = "AMD64" Then
strKeyPath = "SOFTWARE\Wow6432Node\TrendMicro\OfficeScan\service\Information"
End if
strValueName = "Local_Path"
objReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
'If the registry path is empty it won't install the scheduled task and alert you.
If IsNull(strValue) Then
msgbox("Trend Micro is not installed.")
else
PatternLocation = (strValue & "WSS\patterns") ' folder to start deleting (subfolders will also be cleaned)
'msgbox(PatternLocation)
end if
startFolder = PatternLocation
OlderThanDate = DateAdd("d", -1, Date) ' 1 days
DeleteOldFiles startFolder, OlderThanDate
DeleteEmptyFolders startFolder
Function DeleteOldFiles(folderName, BeforeDate)
Dim folder, file, fileCollection, folderCollection, subFolder
Set folder = fso.GetFolder(folderName)
Set fileCollection = folder.Files
For Each file In fileCollection
If file.DateLastModified < BeforeDate Then
fso.DeleteFile(file.Path)
End If
Next
Set folderCollection = folder.SubFolders
For Each subFolder In folderCollection
DeleteOldFiles subFolder.Path, BeforeDate
Next
End Function
Function DeleteEmptyFolders(foldername)
For Each Folder In fso.GetFolder(foldername).SubFolders
DeleteEmptyFolders(Folder.Path)
If Folder.Files.Count = 0 and Folder.SubFolders.Count = 0 Then
fso.DeleteFolder(Folder.Path)
End If
Next
End Function

Resources