Open another user registry settings - windows

I want to write a application that writes to all users on a local machine a specified key (eg: i want set the location for IE Favorites for all users to the same folder)
PS
anybody used these functions?
LoadUserProfile
RegOpenCurrentUser
CreateProcessAsUser

I've done this many times. The idea is to update the currently logged on user's HKCU (that's easy enough). Then you must enumerate every profile on the system and find their ntuser.dat file (that's easy enough too).
With the ntuser.dat file found, you load it into a temporary key in the HKLM hive (I usually use 'HKLM\TempHive'. Then edit away.
If there is more than 1 user logged on, their profile will be loaded under HKEY_USERS, by their SID. Simply update that location.
To modify the setting for any new users, simply modify the appropriate key under HKEY_USERS.DEFAULT, OR use the Delphi code below which will do this by loading the Default Users's HKCU registry hive (stored in ntuser.dat).
UPDATE: I found my Delphi code that demonstrates how to update the HKCU hives of users that are not logged onto the system.
This requires Russell Libby's 'Privilege' component, which is available here.
//NOTE: sPathToUserHive is the full path to the users "ntuser.dat" file.
//
procedure LoadUserHive(sPathToUserHive: string);
var
MyReg: TRegistry;
UserPriv: TUserPrivileges;
begin
UserPriv := TUserPrivileges.Create;
try
with UserPriv do
begin
if HoldsPrivilege(SE_BACKUP_NAME) and HoldsPrivilege(SE_RESTORE_NAME) then
begin
PrivilegeByName(SE_BACKUP_NAME).Enabled := True;
PrivilegeByName(SE_RESTORE_NAME).Enabled := True;
MyReg := TRegistry.Create;
try
MyReg.RootKey := HKEY_LOCAL_MACHINE;
MyReg.UnLoadKey('TEMP_HIVE'); //unload hive to ensure one is not already loaded
if MyReg.LoadKey('TEMP_HIVE', sPathToUserHive) then
begin
//ShowMessage( 'Loaded' );
MyReg.OpenKey('TEMP_HIVE', False);
if MyReg.OpenKey('TEMP_HIVE\Environment', True) then
begin
// --- Make changes *here* ---
//
MyReg.WriteString('KEY_TO_WRITE', 'VALUE_TO_WRITE');
//
//
end;
//Alright, close it up
MyReg.CloseKey;
MyReg.UnLoadKey('TEMP_HIVE');
//let's unload the hive since we are done with it
end
else
begin
WriteLn('Error Loading: ' + sPathToUserHive);
end;
finally
FreeAndNil(MyReg);
end;
end;
WriteLn('Required privilege not held');
end;
finally
FreeAndNil(UserPriv);
end;
end;
I also wrote a VBScript a while ago that accomplishes this task. I used it for modifying some Internet Explorer settings, but you can customize it to your needs. It also demonstrates the general process:
Option Explicit
Dim fso
Dim WshShell
Dim objShell
Dim RegRoot
Dim strRegPathParent01
Dim strRegPathParent02
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreateObject("WScript.shell")
'==============================================
' Change variables here
'==============================================
'
'This is where our HKCU is temporarily loaded, and where we need to write to it
RegRoot = "HKLM\TEMPHIVE"
'
strRegPathParent01 = "Software\Microsoft\Windows\CurrentVersion\Internet Settings"
strRegPathParent02 = "Software\Microsoft\Internet Explorer\Main"
'
'======================================================================
Call ChangeRegKeys() 'Sets registry keys per user
Sub ChangeRegKeys
'Option Explicit
On Error Resume Next
Const USERPROFILE = 40
Const APPDATA = 26
Dim iResult
Dim iResult1
Dim iResult2
Dim objShell
Dim strUserProfile
Dim objUserProfile
Dim strAppDataFolder
Dim strAppData
Dim objDocsAndSettings
Dim objUser
Set objShell = CreateObject("Shell.Application")
Dim sCurrentUser
sCurrentUser = WshShell.ExpandEnvironmentStrings("%USERNAME%")
strUserProfile = objShell.Namespace(USERPROFILE).self.path
Set objUserProfile = fso.GetFolder(strUserProfile)
Set objDocsAndSettings = fso.GetFolder(objUserProfile.ParentFolder)
'Update settings for the user running the script
'(0 = default, 1 = disable password cache)
WshShell.RegWrite "HKCU\" & strRegPathParent01 & "\DisablePasswordCaching", "00000001", "REG_DWORD"
WshShell.RegWrite "HKCU\" & strRegPathParent02 & "\FormSuggest PW Ask", "no", "REG_SZ"
strAppDataFolder = objShell.Namespace(APPDATA).self.path
strAppData = fso.GetFolder(strAppDataFolder).Name
' Enumerate subfolders of documents and settings folder
For Each objUser In objDocsAndSettings.SubFolders
' Check if application data folder exists in user subfolder
If fso.FolderExists(objUser.Path & "\" & strAppData) Then
'WScript.Echo "AppData found for user " & objUser.Name
If ((objUser.Name <> "All Users") and _
(objUser.Name <> sCurrentUser) and _
(objUser.Name <> "LocalService") and _
(objUser.Name <> "NetworkService")) then
'Load user's HKCU into temp area under HKLM
iResult1 = WshShell.Run("reg.exe load " & RegRoot & " " & chr(34) & objDocsAndSettings & "\" & objUser.Name & "\NTUSER.DAT" & chr(34), 0, True)
If iResult1 <> 0 Then
WScript.Echo("*** An error occurred while loading HKCU: " & objUser.Name)
Else
WScript.Echo("HKCU loaded: " & objUser.Name)
End If
WshShell.RegWrite RegRoot & "\" & strRegPathParent01 & "\DisablePasswordCaching", "00000001", "REG_DWORD"
WshShell.RegWrite RegRoot & "\" & strRegPathParent02 & "\FormSuggest PW Ask", "no", "REG_SZ"
iResult2 = WshShell.Run("reg.exe unload " & RegRoot,0, True) 'Unload HKCU from HKLM
If iResult2 <> 0 Then
WScript.Echo("*** An error occurred while unloading HKCU: " & objUser.Name & vbcrlf)
Else
WScript.Echo(" unloaded: " & objUser.Name & vbcrlf)
End If
End If
Else
'WScript.Echo "No AppData found for user " & objUser.Name
End If
Next
End Sub

We had the exact same issue the other day.
We discovered that you can just open the HKEY_USERS hive and write the changes to each user's SID.
And, If you want the settings to be present for any new users, you should also apply the settings to the HKEY_USERS/.DEFAULT key.
That is to say, just write your settings to...
HKEY_USERS\S-1-5-XX-XXXXXXXX-XXXXXXXXX-XXXXXXXX-XXXX\Software\...
For each of the SIDs present and:
HKEY_USERS\.DEFAULT\Software\...

Related

Need VBScript to list disabled accounts

The following script check local computers for inactive (90 days or more) accounts and disables them. The script works fine, but it lists all the disabled accounts every time is executed. I only need it to list the accounts that have been disabled the day is was executed.
Option Explicit
Dim objNetwork, strComputer, objComputer, objUser, dtmLast, objGroup, ObjGroupDict
Dim FSO, OutPutFile
Set FSO = CreateObject("Scripting.FileSystemObject")
'1 = reading, 2 = writing, and 8 = appending. The third parameter is a
'boolean true means a new file can be created if it doesn't exist. False
'means a new file cannot be created.
Set OutPutFile = FSO.OpenTextFile("C:\Test\Result.log", 8, True)
'Bind to the local computer.
Set objNetwork = CreateObject("WScript.Network")
strComputer = objNetwork.ComputerName
Set objComputer = GetObject("WinNT://" & strComputer & ",computer")
'Enumerate all users.
objComputer.Filter = Array("user")
For Each objUser In objComputer
Set ObjGroupDict = CreateMemberOfObject(objUser)
If ((Left(objUser.Name,3) <> "au_") And (CBool(ObjGroupDict.Exists("Administrators") = False))) Then
'Trap error if user never logged in.
On Error Resume Next
dtmLast = objUser.lastLogin
If (Err.Number <> 0) Then
dtmLast = #1/1/1970#
End If
On Error GoTo 0
'Check if last logon was more than 90 days in the past.
If (DateDiff("d", dtmLast, Now()) > 90) Then
'Disable the user.
objUser.AccountDisabled = True
objUser.SetInfo
OutPutFile.WriteLine(Now & " " & strComputer & " " & Wscript.ScriptName & " " & objUser.Name & " " & "Disabled")
'MsgBox objUser.Name
Set FSO = Nothing
End If
End If
Next
Function CreateMemberOfObject(objUser)
'Given a domain name and username, returns a Dictionary
'object of groups to which the user is a member of.
'Inputs: objUser - User Object
Set CreateMemberOfObject = CreateObject("Scripting.Dictionary")
CreateMemberOfObject.CompareMode = vbTextCompare
Dim objGroup
For Each objGroup In objUser.Groups
CreateMemberOfObject.Add objGroup.Name, "-"
Next
End Function
You're disabling all accounts whose last login was more than 90 days ago, even if the account already is disabled. Add a condition that matches only accounts that are not disabled, and the code will do what you want:
If DateDiff("d", dtmLast, Now) > 90 And Not objUser.AccountDisabled Then
...
End If

800A0408, 800A0400 errors [duplicate]

I am trying to create a registry key and subkey for enabling IE 11 enterprise mode for all users on a machine. This is what I am using for my VBScript currently and it is failing horribly (does not add the key). I could use some assistance in getting this corrected.
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set ObjRegistry = _
GetObject("winmgmts:{impersonationLevel = impersonate}! \\" & _
strComputer & "\root\default:StdRegProv")
strPath = strKeyPath & "\" & strSubPath
strKeyPath = "Software\Policies\Microsoft"
strSubPath = "Internet Explorer\Main\EnterpriseMode"
strName = "Enabled"
ObjRegistry.CreateKey (HKEY_LOCAL_MACHINE, strPath)
ObjRegistry.SetStringValue HKEY_LOCAL_MACHINE, strPath, strName, strValue
MsgBox "Successfully enabled Internet Explorer Enterprise Mode."
End Function
There are several issues with your code, aside from the fact that you posted an incomplete code sample.
"winmgmts:{impersonationLevel = impersonate}! \\" & strComputer & "\root\default:StdRegProv"
The WMI moniker contains a spurious space between security settings and path (...! \\...). Remove it.
As a side note, it's pointless to use a variable for the hostname if that hostname never changes.
strPath = strKeyPath & "\" & strSubPath
You define strPath before you define the variables you build the path from. Also, your path components are defined as string literals, so you could drop the concatenation and the additional variables and simply define strPath as a string literal.
ObjRegistry.CreateKey (HKEY_LOCAL_MACHINE, strPath)
You must not put argument lists in parentheses unless you're calling the function/method/procedure in a subexpression context. See here for more details. However, you may want to check the return value of your method calls to see if they were successful.
And FTR, hungarian notation is pointless code bloat. Don't use it.
Modified code:
Function SetEnterpriseMode(value)
Const HKLM = &h80000002
Set reg = GetObject("winmgmts:{impersonationLevel=impersonate}!//./root/default:StdRegProv")
path = "Software\Policies\Microsoft\Internet Explorer\Main\EnterpriseMode"
name = "Enabled"
rc = reg.CreateKey(HKLM, path)
If rc <> 0 Then
MsgBox "Cannot create key (" & rc & ")."
Exit Function
End If
rc = reg.SetStringValue(HKLM, path, name, value)
If rc = 0 Then
MsgBox "Successfully enabled Internet Explorer Enterprise Mode."
Else
MsgBox "Cannot set value (" & rc & ")."
End If
End Function

VBScript Strange Issue with HTA and Type mismatch error

When I run the following script on it's own by double clicking, it works just fine. It returns the last logged on user as expected. But when I run it from the HTA I have been developing as a front end to all of my scripts, I get a type mismatch error on the "wscript.echo strvalue" line. I have tried everything to get it to work, like changing permissions on mshta.exe to full control for myself. I simply can't get it to run from the HTA without getting an error, but it works 100% as expected on its own. I am completely stumped.
strinput = "myserver"
Set objRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strinput & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI"
strValueName = "LastLoggedOnUser"
objRegistry.GetStringValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, strValue
Wscript.Echo strValue
By default, Windows 64-bit uses MSHTA.EXE 32-bit. The registry has a separate branches for 64-bit and 32-bit apps, thus WMI can't find the registry value you are looking for.
Save the code below to e. g. C:\test\tmp.hta, try to launch it from explorer by double-click (32-bit by default) - you will get null, and then launch via Run dialog (Win+R) with path: %windir%\system32\mshta.exe "C:\test\tmp.hta" (64-bit), the result will be your username.
<html>
<head>
<script language="vbscript">
Sub window_onload()
Const HKEY_LOCAL_MACHINE = &H80000002
Set objRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
strKeyPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI"
strValueName = "LastLoggedOnUser"
objRegistry.GetStringValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, strValue
document.body.innerText = strValue
End Sub
</script>
</head>
<body>
</body>
</html>
Note that many other stuff within scripts depends on application architecture, e. g. number of ActiveX are available only in 32-bit version, so they should be launched via %windir%\SysWOW64\ (Windows 32-bit on Windows 64-bit subsystem).
Use Msgbox function instead of Wscript.Echo method. HTAs use the Internet Explorer Scripting Object Model which does not contain Wscript object (this belongs to Windows Script Host Object Model).
Read HTA: Why Can’t I Use Wscript.Echo?:
You might have noticed that when it came time to report back the
operating system version we used the VBScript Msgbox function rather
than the more common Wscript.Echo. Why didn’t we use Wscript.Echo?
Here’s why:
As it turns out the various Wscript methods - Wscript.Echo,
Wscript.Sleep, Wscript.Quit, etc. - are designed solely to run under
the Windows Script Host environment. When we’re working in an HTA
we’re not running under WSH; instead we’re running under the MSHTA
process. Because of that the Wscript methods are not available to us
(nor can we create them). Consequently we need to find workarounds for
each method, and Msgbox is a perfectly adequate replacement for
Wscript.Echo. (We’ll talk about workarounds for other methods - such
as Wscript.Sleep - when we get to them.)
The moral of the story: Don’t bother with Wscript.Echo; it won’t work.
Edit: with Wscript.Echo TypeName(strValue) & vbNewLine & VarType(strValue):
==> C:\Windows\System32\cscript.exe D:\VB_scripts\SO\33505295.vbs
String
8
==> C:\Windows\SysWOW64\cscript.exe D:\VB_scripts\SO\33505295.vbs
Null
1
Tried in a simple HTA which gives the same (different) result
==> C:\Windows\System32\mshta.exe 33505295.hta
versus
==> C:\Windows\SysWOW64\mshta.exe 33505295.hta
Conclusion. Check HTA file type association. For instance, ftype htafile in my Windows 8 (64bit) returns (surprisingly?) the same value which causes wrong behaviour on double click:
==> assoc .hta
.hta=htafile
==> ftype htafile
htafile=C:\Windows\SysWOW64\mshta.exe "%1" {1E460BD7-F1C3-4B2E-88BF-4E770A288AF5}%U{1E460BD7-F1C3-4B2E-88BF-4E770A288AF5} %*
I have had the same challenge a few weeks ago.
The following code provided me the possibility to see who is currently logged onto a remote computer.
I hope this can help you.
Sub ActionGetCurrentUser(strCPU) 'strCPU is the computername
set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strCPU & "\root\cimv2")
set Items = objWMI.ExecQuery("Select * From Win32_ComputerSystem")
For Each obj in Items
OutStr = right(obj.username,9)
Next
Resultstring = "Logged in User is: " & OutStr
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
strTarget = "LDAP://" & strDNSDomain
' ---------------- Write the User's account & password to a variable -------------------
strCurrentuser = Currentuser.value
strPassword = PasswordArea.value
' ---------------- Connect to Ad Provider ----------------
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Properties("User ID") = strCurrentUser ' pass credentials - if you omit this, the search is performed....
objConnection.Properties("Password") = strPassword ' ... with the current credentials
objConnection.Properties("Encrypt Password") = True ' only needed if you set "User ID" and "Password"
objConnection.Open "Active Directory Provider"
Set objCmd = CreateObject("ADODB.Command")
Set objCmd.ActiveConnection = objConnection
objCmd.CommandText = "SELECT DisplayName FROM '" & strTarget & "' WHERE extensionAttribute11 = '" & OutStr & "'"
Const ADS_SCOPE_SUBTREE = 2
objCmd.Properties("Page Size") = 100
objCmd.Properties("Timeout") = 30
objCmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCmd.Properties("Cache Results") = False
Set objRecordSet = objCmd.Execute
If objRecordset.Recordcount = 0 then ' If no user is found then the recordcount will be 0
msgbox "No user is logged on"
Resultstring = ""
Set objCmd = Nothing
Set objRootDSE = Nothing
Set objRecordSet = Nothing
Set objWMI = Nothing
Set Items = Nothing
exit sub
End if
Set objRecordSet = objCmd.Execute
objRecordSet.MoveFirst
Resultstring = Resultstring & vbcrlf & "Name: " & objRecordset.fields("DisplayName")
Msgbox Resultstring
Resultstring = ""
Set objCmd = Nothing
Set objRootDSE = Nothing
Set objRecordSet = Nothing
Set objWMI = Nothing
Set Items = Nothing
End Sub

Small VBScript Does Not Work in HTA

I'm using the following VBSript and it works fine, however when I a attempt to add it to a .hta app I've created, it does not function correctly.
Firstly, the 'strValue' does not show in the MsgBox and secondly script errors appear such as "Type mismatch: 'fso.FolderExists'"
Any help would be greatly appreciated as I've been struggling to figure this out.
sub LyncFix
dim oReg, strKeyPath, strValueName, strValue, oWS, userProfile
Const HKEY_LOCAL_MACHINE = &H80000002
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components\C7376A18AE70EB645A6EA7E5F5CE44F9"
strValueName = "71B0EB18B3654D541B8975126E6C56DC"
oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
MsgBox "Folder required to resolve Lync Install prompt: " & strValue
Dim fso
Dim Folder
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(strValue)) Then
MsgBox("The folder '" + strValue + "' already exists")
end If
If NOT (fso.FolderExists(strValue)) Then
' Delete this if you don't want the MsgBox to show
MsgBox("Local folder doesn't exist, creating...")
' Create folder
MsgBox("'" + strValue + "'" + " created")
fso.CreateFolder(strValue)
MsgBox("Please now try launching Lync again")
End If
end sub
Two side-notes only:
querying HTML with GetStringValue method gives different results for different Windows Script Host executable versions (32 bit vs. 64 bit as manifested in next example);
CreateFolder method might require elevated privileges.
Example: with strComputer = "." and next amendment
'
oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
' the amendment in 29026643.vbs as follows:
Wscript.Echo VarType(strValue) & vbTab & TypeName(strValue)
'
I have got next output on Windows 8, 64 bit:
==>%windir%\sysWOW64\cscript.exe D:\VB_scripts\SO\29026643.vbs
1 Null
==>%windir%\system32\cscript.exe D:\VB_scripts\SO\29026643.vbs
8 String
==>
Analogous output (with windowed echo) with different versions of wscript.exe.
Analogous output with sub LyncFix defined and used in a basic hta (with msgbox instead of Wscript.Echo) and with different versions of mshta.exe as follows:
==>%winDir%\sysWOW64\mshta.exe D:\VB_scripts\SO\29026643.hta
==>%winDir%\system32\mshta.exe D:\VB_scripts\SO\29026643.hta

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