Search code examples
emailvbscriptemail-attachmentscdo.message

Specify the windows folder path in VBScript


I have a vbscript ,which sends the folder contents as attachments to my email but the problem is i am unable to specify the path of windows folder because the windows path is different for different computers.

In my code following works

Const PATH = "C:\windows\Folder1\"

but since path is different for different machines. i tried following but no success

Const PATH = "%windows%\Folder1\"

Here is the full vbscript code

Const cdoSendUsingPickup = 1 'Send message using the local SMTP service pickup directory.
Const cdoSendUsingPort = 2 'Send the message using the network (SMTP over the network).

Const cdoAnonymous = 0 'Do not authenticate
Const cdoBasic = 1 'basic (clear-text) authentication
Const cdoNTLM = 2 'NTLM


Set objMessage = CreateObject("CDO.Message")
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFolder
Dim oFile
Dim oFiles
Const PATH = "%windows%\Folder\" 'This method not working!!!!! 
Set oFolder = fso.GetFolder(PATH)
Set oFiles= oFolder.files
objMessage.Subject = "This is the email subject"
objMessage.From = "[email protected]"
objMessage.To = ""
objMessage.TextBody = "This is the body of the email. I’m fairly unoriginal"
For Each oFile in oFolder.files
objMessage.AddAttachment PATH & oFile.name
Next
'==This section will provide the configuration information for the remote SMTP server.
'==End remote SMTP server configuration section==

objMessage.Send

when the configuration information for the remote SMTP server the code works perfectly.

how will i specify the windows,programfiles,desktop(special folders) in this script??


Solution

  • >> WScript.Echo CreateObject("WScript.Shell").ExpandEnvironmentStrings("%windir%")
    >>
    C:\WINDOWS
    
    >> WScript.Echo CreateObject("WScript.Shell").SpecialFolders("Desktop")
    >>
    C:\Documents and Settings\eh\Desktop
    

    UPDATE:

    sample usage:

    Option Explicit
    
    Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
    
    'Your problem in a nutshell
    'Const PATH = "c:\windows\system"  ' fails on systems with %windir% <> c:\windows
    'Const PATH = "%windir%\system"  ' fails with "Path not found" (FSO does not expand env vars)
    
    Dim goWS   : Set goWS = CreateObject("WScript.Shell")
    ' PATH can't be a Const, because Consts can be initialized with literals only
    ' I use the prefix "cs" to indicate "constant string - keep your fingers off!"
    Dim csPATH  : csPATH   = goWS.ExpandEnvironmentStrings("%windir%\system")
    Dim csDESKT : csDESKT  = goWS.SpecialFolders("desktop")
    WScript.Echo "# of files in system folder:", goFS.GetFolder(csPATH).Files.Count
    WScript.Echo "# of files in desktop:", goFS.GetFolder(csDESKT).Files.Count
    

    output:

    cscript specfolders.vbs
    # of files in system folder: 27
    # of files in desktop: 49