VBscript and WMI: VBscript to find files with specific extensions and creation date on remote servers

Posted March 21st, 2011 in files by dirk adamsky

I recently got the question to find all Symantec BESR snaphot files older than 2 weeks (the retention period) on the company servers. This so that we could clear up some space on the snapshot volumes.
I decided to make a general purpose script of it.
You can use it to find old logfiles, etc.

What the script does:

  • create an array with all server you want to check (replace srv001, etc with your server names)
  • create a variable with a date of 2 weeks ago (Date -14)(can easily be changed in 30, 60 days ago)
  • change the variable date to the UTC date of 14 days ago (because WMI works with UTC dates)
  • for each server in the array
  • make a wmi connection
  • query for files with specific extensions and a creation date older than 14 days ago
  • in this example i took .txt and .csv extensions, change them in whatever filetype you want

The script is tested in an win2003 environment.

Follow the next steps to run the script (admin rights needed):

  • copy and paste the script in your favorite text editor
  • replace the strings ‘srv001′ and ‘srv002′ with the name of your exchange server
  • replace the extensions ‘txt’ and ‘csv with the extensions you need
  • save the script (for example c:tempfindoldfileswithspecificextensions.vbs)(or something shorter..)
  • open a command prompt
  • go to “c:temp”
  • give “cscript findoldfileswithspecificextensions.vbs” (without quotes) and enter

When you want the output in a file please give this command:

“cscript findoldfileswithspecificextensions.vbs > findoldfileswithspecificextensions.txt” (again without the quotes)

The script:

' Name : findoldfileswithspecificextensions.vbs
' Description : VBscript to find files with specific extensions and creation date on remote servers
' Author : dirk adamsky - deludi bv
' Version : 1.00
' Date : 21-03-2011
' Level: intermediate

arrServers = Array("srv001","srv002")
strDate = Date - 14
Set objDateToUtcDate = CreateObject("WbemScripting.SWbemDateTime")
objDateToUtcDate.SetVarDate(strDate)

For Each Server in arrServers
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\" & Server & "rootcimv2")
	Set colFiles = objWMIService.ExecQuery("Select * from CIM_DataFile where (Extension = 'txt' or Extension = 'csv') and CreationDate < '" & objDateToUtcDate & "'")
	For Each objFile in colFiles
		Wscript.Echo objFile.Name
	Next
	Set colFiles = Nothing
	Set objWMIService = Nothing
Next
Set objDateToUtcDate = Nothing

When you have problems/questions please post a reply or give a ‘star’ rating.

Happy scripting.

Best regards,

Dirk Adamsky – Deludi BV

Active Directory and WMI: VBscript to enumerate the ntfs rights of a given UNC path and a given level of subfolders

Posted October 22nd, 2010 in ntfsrights by dirk adamsky

Today I have extended the previous script:
it now also enumerates the NTFS rights of subfolders below the share.
As a bonus the level of subfolders can be set

Follow the next steps to run the script (admin rights needed for the WMI connection):

  • copy and paste the script in your favorite text editor
  • save the script (for example c:\temp\uncacl2.vbs)
  • open a command prompt
  • go to “c:\temp”
  • give “cscript uncacl2.vbs” (without quotes) and enter

The script:

' Name : uncacl2.vbs
' Description : script to enumerate the ntfs rights of a given UNC path and a given level of subfolders
' Author : dirk adamsky - deludi bv
' Version : 1.00
' Date : 22-10-2010

strUNCPathName = InputBox("please supply the UNC path to the shared folder")
strSubfolderLevel = InputBox("please supply the subfolder depth (1,2,etc.)")
arrUNC = split(strUNCPathName,"\")
If Ubound(arrUNC) > 3 Then
strRightPartOfPath = Mid(strUNCPathName,(Instr(strUNCPathName,arrUNC(4)) -1))
End If
Set objWMI = GetObject("winmgmts:\\" & arrUNC(2) & "\root\CIMV2")
Set objFileShare = objWMI.Get("Win32_Share.Name=""" & arrUNC(3) & """")
If Right(arrUNC(3),1) = "$" And Len(arrUNC(3)) = 2 Then
strPath = objFileShare.Path & Mid(strRightPartOfPath,2)
Else
strPath = objFileShare.Path & strRightPartOfPath
End If
ShowACL strPath
ViewSubFolders strPath, strSubfolderLevel
Set objFileShare = Nothing
Set objWMI = Nothing

Function ViewSubfolders(strFolder, strMaxlevel)
Set colSubfolders = objWMI.ExecQuery("Associators Of {Win32_Directory.Name='" & strFolder & "'} " &_
"Where AssocClass = Win32_Subdirectory ResultRole = PartComponent")
If strMaxlevel >= 1 Then
    For Each SubFolder in colSubfolders
        wscript.echo SubFolder.Name
        ShowACL SubFolder.Name
        ViewSubFolders SubFolder.Name, (strMaxlevel - 1)
    Next
End If
Set colSubfolders = Nothing
End Function

Function ShowACL(strDir)
Set objFolderSecuritySettings = objWMI.Get("Win32_LogicalFileSecuritySetting.Path='" & strDir & "'")
objFolderSecuritySettings.GetSecurityDescriptor objSD
For Each objAce in objSD.DACL
    Select Case objAce.AccessMask
        Case 1179817
            strRights = "read-only"
        Case 2032127
            strRights = "full-control"
        Case 1245631
            strRights = "change"
    End Select
Wscript.Echo strUNCPathName & " ; " & strDir & " ; " & objAce.Trustee.Domain & " ; " & objAce.Trustee.Name & " ; " & strRights
Next
Set objSD = Nothing
Set objFolderSecuritySettings = Nothing
End Function

When you have problems/questions please post a reply or give a ‘star’ rating.

Happy scripting.

Best regards,

Dirk Adamsky – Deludi BV

Active Directory and WMI: VBscript to enumerate the ntfs rights of a given UNC path

Posted October 20th, 2010 in ntfsrights by dirk adamsky

Last weeks I haven’t done much scripting (lack of inspiration, bad weather, etc.).
But today I finished a script that I wanted to make for quite some time.
The script enumerates the NTFS rights (to be more precisely a subset of the possible NTFS rights: read, change and full-control) of a given UNC path.
What the script does:

  • ask for a UNC path
  • split the UNC path and put the substrings in an array
  • make a wmi connection to the target server
  • find the absolut path of the share
  • enumerate the acl’s
  • close the used objects

Follow the next steps to run the script (admin rights needed for the WMI connection):

  • copy and paste the script in your favorite text editor
  • save the script (for example c:tempuncacl.vbs)
  • open a command prompt
  • go to “c:temp”
  • give “cscript uncacl.vbs” (without quotes) and enter

The script:

' Name : uncacl.vbs
' Description : script to enumerate the ntfs rights of a given UNC path
' Author : dirk adamsky - deludi bv
' Version : 1.00
' Date : 20-10-2010

strUNCPathName = InputBox("please supply the UNC path to the shared folder")
arrUNC = split(strUNCPathName,"")
If Ubound(arrUNC) > 3 Then
	strRightPartOfPath = Mid(strUNCPathName,(Instr(strUNCPathName,arrUNC(4)) -1))
End If
Set objWMI = GetObject("winmgmts:\" & arrUNC(2) & "rootCIMV2")
Set objFileShare = objWMI.Get("Win32_Share.Name=""" & arrUNC(3) & """")
If Right(arrUNC(3),1) = "$" And Len(arrUNC(3)) = 2 Then
	strPath = objFileShare.Path & Mid(strRightPartOfPath,2)
Else
	strPath = objFileShare.Path & strRightPartOfPath
End If
Set objFolderSecuritySettings = objWMI.Get("Win32_LogicalFileSecuritySetting.Path='" & strPath & "'")
objFolderSecuritySettings.GetSecurityDescriptor objSD
For Each objAce in objSD.DACL
	Select Case objAce.AccessMask
		Case 1179817
			strRights = "read-only"
		Case 2032127
			strRights = "full-control"
		Case 1245631
			strRights = "change"
	End Select
	Wscript.Echo strUNCPathName & " ; " & strPath & " ; " & objAce.Trustee.Domain & " ; " & objAce.Trustee.Name & " ; " & strRights
Next
Set objSD = Nothing
Set objFolderSecuritySettings = Nothing
Set objFileShare = Nothing
Set objWMI = Nothing

When you have problems/questions please post a reply or give a ‘star’ rating.

Happy scripting.

Best regards,

Dirk Adamsky – Deludi BV

[adrotate group="3"]

Active Directory and WMI: VBscript to enumerate the system uptime of all servers in Active Directory V2

Posted July 15th, 2010 in active directory, uptime, vbscript, wmi by dirk adamsky

The script for today is created for Paul.
It is an extension of the previous server uptime script.
The uptime is now formatted in: xx days, xx hours, xx minutes.


Follow the next steps to run the script (admin rights needed for the WMI connections):

  • copy and paste the script in your favorite text editor
  • save the script (for example c:tempserveruptimev2.vbs)
  • open a command prompt
  • go to “c:temp”
  • give “cscript serveruptimev2.vbs” (without quotes) and enter

The script:

' Name : serveruptimev2.vbs
' Description : script to enumerate the system uptime of all servers in Active Directory V2
' Author : dirk adamsky - deludi bv
' Version : 2.00
' Date : 15-07-2010

Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
adoCommand.ActiveConnection = adoConnection

Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
strBase = "<LDAP://" & strDNSDomain & ">"
strFilter = "(&(objectCategory=computer)(operatingSystem=*server*))"
strAttributes = "name"

strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 100
adoCommand.Properties("Timeout") = 30
adoCommand.Properties("Cache Results") = False
Set adoRecordset = adoCommand.Execute

Do Until adoRecordset.EOF
	On Error Resume Next
	strHostname = adoRecordset.Fields("name").Value
	If CheckStatus(strHostname) = False Then
		Wscript.Echo strHostname & " does not reply"
	Else
		Wscript.Echo strHostname & " is up for " & GetUptime(strHostname)
	End If
	adoRecordset.MoveNext
Loop

adoRecordset.Close
adoConnection.Close

Set adoRecordset = Nothing
Set objRootDSE = Nothing
Set adoConnection = Nothing
Set adoCommand = Nothing

Function CheckStatus(strAddress)
	Dim objPing, objRetStatus
	Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strAddress & "'")
	For Each objRetStatus In objPing
        If IsNull(objRetStatus.StatusCode) Or objRetStatus.StatusCode <> 0 Then
			CheckStatus = False
        Else
			CheckStatus = True
        End If
    Next
	Set objPing = Nothing
End Function 

Function GetUptime(strServer)
	Set objDateTime = CreateObject("WbemScripting.SWbemDateTime")
	Set objWMIService = GetObject("winmgmts:\" & strServer & "rootcimv2")
	Set colOperatingSystems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
	For Each objOS in colOperatingSystems
		objDateTime.Value = objOS.LastBootUpTime
		strMinutes = DateDiff("n", objDateTime.GetVarDate, Now)
		If strMinutes =< 0 Then
			strUptime = "0 days, 0 hours, 0 minutes"
		Else
			strUptime = ""
			If strMinutes >= 1440 Then
				strUptime = Round(strMinutes1440,0) & " days,"
			End If
			strMinutes = strMinutes Mod 1440
			If strMinutes >= 60 Then
				strUptime = strUptime & (strMinutes60) & " hours,"
			End If
			strMinutes = strMinutes Mod 60
			GetUptime = strUptime & strMinutes & " minutes"
		End If
	Next
	Set colOperatingSystems = Nothing
	Set objWMIService = Nothing
	Set objDateTime = Nothing
End Function

When you have problems/questions please post a reply or give a ‘star’ rating.

Happy scripting.

Best regards,

Dirk Adamsky – Deludi BV

[adrotate group="2" banner="3"]