Tuesday, June 5, 2012

Handy VBScript: File Functions

File Functions

These functions and subroutines are great and useful when working with files.  One example is creating a log within your program.  Simply keep appending your comments to a text stream and finally use the SaveStrToFile function below.  This works great when combined with the Sortable Time functions.  A file can be created using a timestamp as the file name (ie. 20120313_0406.txt)

GetStreamFromFile

Function GetStreamFromFile (aFileName)
'On Error Resume Next  
  Const FORREADING    = 1
  Const TRISTATEFALSE = 0
  
  Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
  If Not fso.FileExists(aFileName) Then
    Err.Description = "File does not exist. " & """" & aFileName & """"
    Err.Number = -1
    Err.Source = "GetStreamFromFile()"
    Err.Raise -1
    Exit Function
  End If   
  Dim file: Set file =  fso.OpenTextFile(aFileName, FORREADING, TRISTATEFALSE)
  Dim fileStream : fileStream = file.ReadAll

  Set file = nothing
  Set fso = nothing
  
  GetStreamFromFile = fileStream
End Function

SaveStrToFile 

Sub SaveStrToFile (aString, aFileName)
On Error Resume Next
   Dim textFile

   Dim fso: Set fso = CreateObject("Scripting.FileSystemObject") 
   Set textFile = fso.OpenTextFile(aFileName, 2, True, 0)
   If Err.Number <> 0 Then
      WScript.Echo "Err No: " & Err.Number & vbcrlf & "Description: " & Err.Description
      WScript.Echo "Program failed."
      WScript.Quit (Err.Number)
   End If
   textFile.WriteLine aString
   textFile.Close
   
   Set textFile = Nothing
   Set fso = nothing
End Sub

MoveAllFiles

aSource: Full source path (ie. C:\source\path)
aDestination: Full destination path (ie. C:\destination\path)
aLog: Log string.  Useful for logging which files were moved
Sub MoveAllFiles(aSource, aDestination, ByRef aLog)
' Validate parameters
If (aSource = vbEmpty) Then
WScript.Echo "ERROR: Source path is empty"
End If

If (aDestination = vbEmpty) Then
WScript.Echo "ERROR: Destination path is empty"
End If

On Error Resume Next
Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
Dim folder : Set folder = fso.GetFolder(aSource)
Dim file
Dim DestinationLeadingBackStash : DestinationLeadingBackStash = ""
Dim tempDestinationFullPath : tempDestinationFullPath = ""
Dim Count : Count = 0

If (Right(aDestination, 1) = "\") Then
DestinationLeadingBackStash = ""
Else 
DestinationLeadingBackStash = "\"
End If

Dim fileCol : Set fileCol = folder.Files

For Each file in fileCol
tempDestinationFullPath = aDestination & DestinationLeadingBackStash & file.Name
'Move only if does not exist in the destination
If Not fso.FileExists(tempDestinationFullPath) Then
      ' Wait for process
      If Count Mod 2000 = 0 Then
        WScript.Sleep 500
      End If
file.Move aDestination & DestinationLeadingBackStash
      If Err.Number <> 0 Then
        aLog = aLog & "ERROR: Unable to move file: " & file.Name & vbNewLine & _
              Err.Number & ": " & Err.Description & vbNewLine 
      Else
        aLog = aLog & file.Name & vbNewLine
 Count = Count + 1      
      End If
End If
Next

aLog = aLog & "Files Moved: " & Count & vbNewLine
  
  If folder.Count > 0 Then 
    aLog = aLog & "Error: Not all files were moved." & vbNewLine & _
      "Remaining file count: " & folder.Count & vbNewLine
  End If

Set file = nothing
Set folder = nothing
Set fso = nothing

End Sub

MapNetworkDrive 

Sub MapNetworkDrive (aDriveLetter, aStrRemoteShare, aPersistentFlag, aStrUser, aStrPassword)
On Error Resume Next
Dim objNetwork : Set objNetwork = CreateObject("WScript.Network")

objNetwork.MapNetworkDrive aDriveLetter, aStrRemoteShare, aPersistentFlag, aStrUser, aStrPassword

If Err.Number = -2147023677 Then
WScript.Echo objNetwork.MapNetworkDrive (aDriveLetter, aStrRemoteShare, aPersistentFlag)
Exit Sub
End If 

If Err.Number <> 0 Then
WScript.Echo "Error: " & Err.Number & vbNewLine & Err.DESCRIPTION
Exit Sub
End If

Set objNetwork = nothing
End Sub

GetFileName


Function GetFileName(aFileName)
  Dim fso, file, retval
   
  Set fso = CreateObject("Scripting.FileSystemObject") 
  Set file = fso.GetFile(aFileName)
  
  retval = file.Name
  
  Set file = nothing
  Set fso = nothing
  
  GetFileName = retval
   
End Function

Handy VBScript: Time Functions

Hello and welcome to a post that I know some of you will be glad to find!

This is part of a series of posts designed to help the IT/Network/System Administrators.  These posts will show you have to make use of fantastic functions to help you do your work more efficiently.  I have gathered a set of these functions throughout the years and find myself reusing them time and time again.  Let's jump right in!

Time Functions

These are handy when creating reports in Access or just manipulating time-related data.  

This function simply returns the current calendar quarter
'Returns: Integer value (1 - 4)
Function GetCurrentQuarter()
  GetCurrentQuarter = DatePart ("q", Now())
End Function


This function simply returns the current calendar quarter
'Returns: Integer value (1 - 4)
Function GetLastQuarter()
  GetLastQuarter = DatePart("q", DateAdd ("q", -1, Now()))
End Function



Returns the year of the last quarter.  If current date is 3/13/2012, the function returns 2011.
'Returns: Integer value (ie. 2011)

Function GetLastQuarterYear()

  GetLastQuarterYear = Year(DateAdd ("q", -1, Now()))
End Function


Function mainly used to create log file names that are able to be sorted (yyyymmdd).
' Returns a formatted date that is computer sortable (ex. 20100513)
Function GetDateComputerSortable (aDate)
  Dim m_date: m_date = aDate
  Dim retval
  
  If aDate=Empty Then
    m_date = Now()
  End If
  
  retval = Year(m_date)
  
  If Month(m_date)<10 Then
    retval = retval & "0" & Month(m_date) 
  Else
   retval = retval & Month(m_date)
  End If
  
  If Day(m_date)<10 Then
    retval = retval & "0" & Day(m_date)
  Else
    retval = retval & Day(m_date)
  End If
  
  GetDateComputerSortable = retval 
    
End Function


This can be used when requiring a full date instead of 1/1/2011 versus 12/31/2011.  All 10 characters are used.  Instead of 1/1/2011 then function returns 01/01/2011.

' Returns a standard formatted date (ex. 08/22/2011)
Function GetDateStandardFormat (aDate)
  Dim m_date: m_date = aDate
  Dim retval
  
  If aDate=Empty Then
    m_date = Now()
  End If


  If Month(m_date)<10 Then
    retval = retval & "0" & Month(m_date) 
  Else
   retval = retval & Month(m_date)
  End If
  
  retval = retval & "/"
  
  If Day(m_date)<10 Then
    retval = retval & "0" & Day(m_date)
  Else
    retval = retval & Day(m_date)
  End If
  
  retval = retval & "/" & Year(m_date)
  GetDateStandardFormat = retval 
    
End Function




Returns a date used by the most of the world. (ie. 13MAR2012)
Requires GetMonthInEnglish(..)
Date Format By Country (Wikipedia.org)

Function GetDateLittleEnding (aDate)
  Dim m_date: m_date = aDate
  Dim retval


  If aDate=Empty Then
    m_date = Now()
  End If


  'Day
  If Day(m_date) < 10 Then
    retval = "0" & Day(m_date) 
  Else
    retval = Day(m_date)
  End If
  
   GetDateLittleEnding  = retval & GetMonthInEnglish(Month(m_date)) & Year(m_date)


End Function





Returns an abbreviated version of the month in English.

Function GetMonthInEnglish (aNumber)
Dim MonthInEnglish
  Select Case aNumber
    Case 1: MonthInEnglish = "JAN" 
    Case 2: MonthInEnglish = "FEB"
    Case 3: MonthInEnglish = "MAR"
    Case 4: MonthInEnglish = "APR" 
    Case 5: MonthInEnglish = "MAY"
    Case 6: MonthInEnglish = "JUN"
    Case 7: MonthInEnglish = "JUL"
    Case 8: MonthInEnglish = "AUG"
    Case 9: MonthInEnglish = "SEP"
    Case 10: MonthInEnglish = "OCT"
    Case 11: MonthInEnglish = "NOV"
    Case 12: MonthInEnglish = "DEC"
  End Select
  GetMonthInEnglish = MonthInEnglish
End Function




' Returns formatted time that is computer sortable (ex. 3:12 PM => 1512 )
Function GetTimeMilitaryComputerSortable (aTime)
  Dim m_date: m_date = aTime
  Dim retval

  If aDate=Empty Then
    m_date = Now()
  End If  

  If Hour(m_date) < 10 Then
    retval = retval & "0" & Hour(m_date) 
  Else
    retval = retval & Hour(m_date)
  End If  
  
  If Minute(CurrentTime) < 10 Then
    retval = retval & "0" & Minute(m_date) 
  Else
    retval = retval & Minute(m_date)
  End If    
  
  GetTimeMilitaryComputerSortable = retval

End Function