VB Script - Undefined variable - vbscript

I'm getting 'variable is undefined', I'm guessing this has something to do with the scope of variables in vbscript, but my knowledge is limited with this.
I know the loading of the email addresses works and the actual emailing because I have checked these separately. I'm trying to loop through a list of email addresses and send the log file to each..
Any additional information would be great!
First, there is a var array at the top of the file:
dim emails()
function getEmailAddresses()
dim objFSO
dim objConfigFile
dim strLine
dim iCounter
const ForReading = 1, ForWriting = 2, ForAppending = 8
set objFSO = createobject("Scripting.FileSystemObject")
set objConfigFile = objFSO.OpenTextFile("emailAddresses.config", ForReading)
iCounter = 0
do while not objConfigFile.AtEndOfStream
redim preserve emails(iCounter)
strLine = trim(objConfigFile.ReadLine)
emails(iCounter) = strLine
iCounter = iCounter + 1
loop
objConfigFile.Close
end function
function writetolog(strLogtext)
dim objFSO
dim objLogfile
const ForReading = 1, ForWriting = 2, ForAppending = 8
set objFSO = createobject("Scripting.FileSystemObject")
set objLogfile = objFSO.OpenTextFile("xxx.log", ForAppending, true)
objLogfile.Writeline now() & " - " & strLogText
objLogfile.Close
call EmailLogFile(strLogText)
end function
function EmailLogFile(bodyText)
for each emailAddress in emails
set objEmail = CreateObject("CDO.Message")
objEmail.From = "File.Mover#xxxxxxx.xxx"
objEmail.To = emailAddress
objEmail.Subject = "File Move Log"
objEmail.Textbody = bodyText
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"xxxxxx"
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send
next
end function

It doesn't look like you're calling getEmailAddresses() anywhere so your file won't be read and your emails array won't be populated

What line is the undefined var at? Or what is the var name?
Either way, 'strLogText' is not defined anywhere. Also, if this is a classic ASP page put an Option Explicit statement at the top.

Related

creating a VBScript to grab fonts from fileserver

I'm trying to create a VBS script that will grab all the fonts from the server font location so that the domain user will have the ability to use them. When I run this script I get a line 15 char 1 error: 800A400C.
Not sure what is wrong with it or if this script will do the job I'm wanting it to do.
'On Error Resume Next
'Option Explicit
Dim objShell, objFSO, wshShell
Dim strFontSourcePath, objFolder, objFont, objNameSpace, objFile, strFontsSytem
Set objShell = CreateObject("Shell.Application")
Set wshShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FilesyStemObject")
strFontSourcePath = "\\server\Fonts\"
strFontsSytem = WSHShell.SpecialFolders("Fonts") & "\"
Set objNameSpace = objShell.Namespace(strFontSourcePath)
Set objFolder = objFSO.GetFolder(strFontSourcePath)
For Each objFile In objFolder.Files
If LCase(Right(objFile, 4)) = ".ttf" Or LCase(Right(objFile, 4)) = ".otf" Then
Set objFont = objNameSpace.ParseName(objFile.Name)
If objFSO.FileExists(strFontsSytem & objFile.Name) = False Then
objFont.InvokeVerb("Install")
Set objFont = Nothing
End If
End If
Next
Set objShell = Nothing
Set wshShell = Nothing
Set objFSO = Nothing
Set objNameSpace = Nothing
Set objFolder = Nothing
WScript.Quit
Error code 800A004C means Path not found. Please check the existance of the strFontSourcePath and like Ansgar says also check if the user running this code has access to this share.
Anyway, Here's my code to copy and install fonts from a server share if that is any help
Call AddFonts("\\server\Fonts\")
WScript.Quit
Private Sub AddFonts(strFromPath)
' install fonts from a server location if not already present
Dim appShell, objShell, objFSO, colFiles, objFile, objFolder
Dim strToPath, flags, strFile, strExt
'SpecialFolder. See: https://technet.microsoft.com/en-us/library/ee176604.aspx
Const FONTFOLDER = &H14&
'CopyHere switches
Const FOF_MULTIDESTFILES = &H1&
Const FOF_CONFIRMMOUSE = &H2&
Const FOF_SILENT = &H4&
Const FOF_RENAMEONCOLLISION = &H8&
Const FOF_NOCONFIRMATION = &H10&
Const FOF_WANTMAPPINGHANDLE = &H20&
Const FOF_ALLOWUNDO = &H40&
Const FOF_FILESONLY = &H80&
Const FOF_SIMPLEPROGRESS = &H100&
Const FOF_NOCONFIRMMKDIR = &H200&
Const FOF_NOERRORUI = &H400&
Const FOF_NOCOPYSECURITYATTRIBS = &H800&
Const FOF_NORECURSION = &H1000&
Const FOF_NO_CONNECTED_ELEMENTS = &H2000&
Const FOF_WANTNUKEWARNING = &H4000&
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = Createobject("Wscript.Shell")
Set appShell = CreateObject("Shell.Application")
'create an object for the systems fonts folder
Set objFolder = appShell.Namespace(FONTFOLDER)
'make sure these paths end in a backslash
strFromPath = FixPath(strFromPath)
'get the name of the system fonts folder (C:\WINDOWS\Fonts)
strToPath = FixPath(objShell.SpecialFolders("Fonts"))
'set flags to install as quiet as possible.
flags = FOF_SILENT Or FOF_NOCONFIRMATION Or FOF_NOERRORUI Or _
FOF_NOCONFIRMMKDIR Or FOF_NOCOPYSECURITYATTRIBS
If (Not objFolder Is Nothing) Then
If objFSO.FolderExists(strFromPath) Then
Set colFiles = objFSO.GetFolder(strFromPath).Files
If colFiles.Count > 0 Then
For Each objFile In colFiles
strExt = objFSO.GetExtensionName(objFile.Name)
Select Case LCase(strExt)
Case "ttf", "otf" ' can also be used for "fon", "pfm", "pfb", "afm"
'get the complete path and filename for this font file and check if already there
strFile = strToPath & objFile.Name
If Not (objFSO.FileExists(strFile)) Then
objFolder.CopyHere strFromPath & objFile.Name, flags
End If
End Select
Next
End If
End If
End If
'cleanup objects
Set appShell = Nothing
Set colFiles = Nothing
Set objFile = Nothing
Set objFolder = Nothing
Set objFSO = Nothing
Set objShell = Nothing
End Sub
Private Function FixPath(sPath)
'small helper function to ensure a path ends in a backslash
If Len(sPath) > 0 And Right(sPath, 1) <> "\" Then
FixPath = sPath & "\"
Else
FixPath = sPath
End If
End Function

vbscript search string in multiple files

Please advice how changes the current single incoming log file to search multiple files.
Dim strTextToFind, strInputFile, strOutputFile, boolMatchCaseSensitive
Dim objFSO, objInputFile, strFoundText, strLine, objOutputFile
strTextToFind = Inputbox("Enter the text you would like to search for.")
strInputFile = "C:\Users\mmmanima\Desktop\mani\Day_16.txt"
iF YOU CAN NOTICED, IM ONLY ACCESS THE day_16 FILE
strOutputFile = "C:\Users\mmmanima\Desktop\texting As\result.txt"
Set objFSO = CreateObject("Scripting.FilesystemObject")
Const intForReading = 1
Const intForWriting = 2
Const intForAppending = 8
Set objInputFile = objFSO.OpenTextFile(strInputFile, intForReading, False)
Do until objInputFile.atEndOfStream
strLine = objInputFile.ReadLine
If InStr(strLine,strTextToFind) > 0 Then
strFoundText = strLine
If strFoundText <> "" Then
Set objOutputFile = objFSO.OpenTextFile(strOutputFile,intForAppending, True)
objOutputFile.WriteLine strFoundText
objOutputFile.Close
Set objOutputFile = Nothing
End If
End If
loop
objInputFile.Close
Set objInputFile = Nothing
WScript.Quit
VBScript required to search userinput string into the share folder and there is 60 files.
As I believe you want to search through the all files in a particular folder. Then I suggest you to loop you action while all files are read
to do that it's easier to maintain sub or function
pseudo:
var inputFolder = ".\myfolder"
foreach file in the inputFolder
{
inputFile = file
searchIn(inputFile)
}
sub searchIn(inputFile)
{
'do your current works here
}
code:
This part will give you the all file names
Set fso = CreateObject("Scripting.FileSystemObject")
inputFldr = Replace(wscript.scriptfullname,wscript.scriptname,".\")
Set fldr = fso.getFolder(inputFldr)
For Each file In fldr.Files
'call to your function
Next
----------plese aware of typos------
Dim strTextToFind, strInputFile, strOutputFile, boolMatchCaseSensitive
Dim objFSO, objInputFile, strFoundText, strLine, objOutputFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
inputFldr = Replace(wscript.scriptfullname,wscript.scriptname,".\")
Set fldr = objFSO.getFolder(inputFldr)
strTextToFind = Inputbox("Enter the text you would like to search for.")
For Each file In fldr.Files
yourFunctionName(file )
Next
sub yourFunctionName(inputFile)
strInputFile = inputFile
strOutputFile = ".\result.txt"
Const intForReading = 1
Const intForWriting = 2
Const intForAppending = 8
Set objInputFile = objFSO.OpenTextFile(strInputFile, intForReading, False)
Do until objInputFile.atEndOfStream
strLine = objInputFile.ReadLine
If InStr(strLine,strTextToFind) > 0 Then
strFoundText = strLine
If strFoundText <> "" Then
Set objOutputFile = objFSO.OpenTextFile(strOutputFile,intForAppending, True)
objOutputFile.WriteLine strFoundText
objOutputFile.Close
Set objOutputFile = Nothing
End If
End If
loop
objInputFile.Close
Set objInputFile = Nothing
end sub
WScript.echo "done"
WScript.Quit
You can try this vbscript, i added a function BrowseForFolder()
Option Explicit
Dim strTextToFind,inputFldr,strInputFile,strOutputFile,path,fldr
Dim objFSO, objInputFile,strFoundText,strLine,objOutputFile,file,ws
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject("wscript.Shell")
path = objFSO.GetParentFolderName(wscript.ScriptFullName)
strOutputFile = path & "\result.txt"
If objFSO.FileExists(strOutputFile) Then
objFSO.DeleteFile(strOutputFile)
End if
inputFldr = BrowseForFolder()
Set fldr = objFSO.getFolder(inputFldr)
strTextToFind = Inputbox("Enter the text you would like to search for it !","Enter the text you would like to search for it !","wscript")
For Each file In fldr.Files
Call Search(file,strTextToFind)
Next
ws.run strOutputFile
'***************************************************************************************************************
Sub Search(inputFile,strTextToFind)
strInputFile = inputFile
Const intForReading = 1
Const intForWriting = 2
Const intForAppending = 8
Set objInputFile = objFSO.OpenTextFile(strInputFile,intForReading, False)
Do until objInputFile.atEndOfStream
strLine = objInputFile.ReadLine
If InStr(strLine,strTextToFind) > 0 Then
strFoundText = strLine
If strFoundText <> "" Then
Set objOutputFile = objFSO.OpenTextFile(strOutputFile,intForAppending, True)
objOutputFile.WriteLine "The Path of file ===> "& DblQuote(strInputFile) & VbCRLF &_
"String found "& DblQuote(strTextToFind) & " ===> "& DblQuote(strFoundText) & VbCRLF & String(100,"*")
objOutputFile.Close
Set objOutputFile = Nothing
End If
End If
loop
objInputFile.Close
Set objInputFile = Nothing
End sub
'***************************************************************************************************************
Function BrowseForFolder()
Dim ws,objFolder,Copyright
Set ws = CreateObject("Shell.Application")
Set objFolder = ws.BrowseForFolder(0,"Choose the folder to search on it ",1,"c:\Programs")
If objFolder Is Nothing Then
Wscript.Quit
End If
BrowseForFolder = objFolder.self.path
end Function
'****************************************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'*****************************************************
A bit late in the day after such a long time gap to address Mara Raj's problem with Hackoo's script but here it is for any others who may be interested. On starting the script it automatically deletes any existing result.txt file. Should the script subsequently go on to find "no match" it fails to generate a results.txt file as it would normally do if there were a match. The simplest way to correct this is to insert:
If objFSO.FileExists(strOutputFile) Then
else
wscript.echo "No Matches Found"
wscript.Quit
end if
between "next" and "ws.run strOutputFile"

VBScript - Change Group Type

I am using the below VBscript to change group type of couple of groups to Security. I am getting an error "The server is unwilling to process the request" when executing objGroup.setinfo.
Appreciate if someone can help to resolve this.
Dim strOU, strGroup, objOU, objGroup
Dim strFile, objFile, objFSO
Const ADS_GROUP_TYPE_SECURITY_ENABLED = &H80000000
Const ForReading = 1
Const ADS_NAME_INITTYPE_GC = 3
Const ADS_NAME_TYPE_NT4 = 3
Const ADS_NAME_TYPE_1779 = 1
Const ADS_GROUP_TYPE_UNIVERSAL = &H8
strFile = "c:\Temp\GroupNames.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFile, ForReading)
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
Set objTrans = CreateObject("NameTranslate")
objTrans.Init ADS_NAME_INITTYPE_GC, ""
objTrans.Set ADS_NAME_TYPE_1779, strDNSDomain
strNetBIOSDomain = objTrans.Get(ADS_NAME_TYPE_NT4)
strNetBIOSDomain = Left(strNetBIOSDomain, _
Len(strNetBIOSDomain) - 1)
Do Until objFile.AtEndOfStream
strNTName = Trim(objFile.ReadLine)
If (strNTName <> "") Then
On Error Resume Next
objTrans.Set ADS_NAME_TYPE_NT4, strNetBIOSDomain & "\" & strNTName
End If
' Use Get method to retrieve Distinguished Name.
strUserDN = objTrans.Get(ADS_NAME_TYPE_1779)
wscript.echo strUSerDN
' Bind to user object in AD.
Set objGroup = GetObject("LDAP://servername
" & strUserDN)
objGroup.Put "groupType", ADS_GROUP_TYPE_SECURITY_ENABLED
objGroup.SetInfo
Loop
objFile.Close
You need to specify the group scope as well. Instead of just "ADS_GROUP_TYPE_SECURITY_ENABLED", you need "ADS_GROUP_TYPE_[type]_GROUP Or ADS_GROUP_TYPE_SECURITY_ENABLED", where [type] is GLOBAL, LOCAL, or UNIVERSAL.

Read integer from text file and replace with different integer

I'm working with the below code
Dim objFSO, objFile, maxRetry, numRetries, newRetries
CONST ForReading = 1
CONST ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(MICacheFilename(), ForReading)
maxRetry = CInt(MIGetTaskParam("maxRetry"))
strText = objFile.ReadAll
Set numRetries = CInt(objFile.ReadLine)
IF numRetries >= maxRetry THEN
MISetTaskParam "RerunTask", "False"
strLine = Replace(strLine,numRetries ,0)
Else
MISetTaskParam "RerunTask", "True"
Set newRetries = numRetries + 1
strLine = Replace(strLine,numRetries ,newRetries)
END IF
MICacheFilename() and MIGetTaskParam are passed into the script as a file path and an integer. My goal is to compare the max value passed in to the value in the file and set MISetTaskParam based on the comparison. I'm very new to VB and this seems like it shoudl be easier than I'm finding. The input file is a text file that only contains an integer.
While my first instinct would be to stay in a loop this script is only called periodically and needs to be an IF.
I am currently getting the error object requried with set numRetries = CInt(objFile.ReadLine)
mhopkins321, you say:
I am currently getting the error object requried with set numRetries =
CInt(objFile.ReadLine)
That is because the Set keyword is used only for setting a variable that holds an instance of an object. In your case, the purpose numRetries is to hold an integer.
So, try this instead:
numRetries = CInt(objFile.ReadLine)
I found a few other issues with your script. Here is my edited version with some comments:
Option Explicit ' Checks that you have declared all variables
Dim objFSO, objFile, maxRetry, numRetries, newRetries
Dim strText, strLine ' declare these also
CONST ForReading = 1
CONST ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(MICacheFilename(), ForReading)
maxRetry = CInt(MIGetTaskParam("maxRetry"))
' strText = objFile.ReadAll ' Not needed
numRetries = CInt(objFile.ReadLine) ' just read the one line in the file
WScript.Echo "numRetries = [" & numRetries & "]"
IF numRetries >= maxRetry THEN
MISetTaskParam "RerunTask", "False"
strLine = Replace(strLine,numRetries ,0) ' does nothing, 'strline' is empty
Else
MISetTaskParam "RerunTask", "True"
newRetries = numRetries + 1
strLine = Replace(strLine,numRetries ,newRetries) ' does nothing, 'strline' is empty
END IF
WScript.Echo "strLine = [" & strLine & "]"
' Dummy Function.
Function MICacheFilename()
MICacheFilename = "retries.txt"
End Function
' Dummy Function.
Function MIGetTaskParam(key)
MIGetTaskParam = 13
End Function
' Dummy Sub.
Sub MISetTaskParam(arg1, arg2)
End Sub

Reading data from a file with a variable name - VBScript

I'm trying to count the number of lines in a text file using VBScript. I have managed to do this without a problem for a text file with a fixed name. EG: "C:\Orig\sample.txt"
However, our filenames change daily, EG: "C:\Orig\sample*todaysdate*.txt"
I have looked high and low for a way to 'read' a file with a variable name and have had no luck.
What I have so far for a fixed file name is:
Dim oFso, oReg, sData, lCount, linesum
Const ForReading = 1, sPath = "C:\Orig\sample.txt"
Set oReg = New RegExp
Set oFso = CreateObject("Scripting.FileSystemObject")
sData = oFso.OpenTextFile(sPath, ForReading).ReadAll
With oReg
.Global = True
.Pattern = "\r\n" 'vbCrLf
lCount = .Execute(sData).Count + 1
End With
WScript.Echo("The total number of lines including the header is " & lCount)
Set oFso = Nothing
Set oReg = Nothing
This works perfectly well, but I just cannot find the correct syntax for a variable file name.
If it is of any help, the file I'm looking to interrogate will be the ONLY file in the containing folder.
Is anybody able to offer any assistance? Many thanks.
I have now tried the following:
Dim objFso, objReg, sData, lCount
Const ForReading = 1
sPath = "C:\Orig"
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder(sPath)
For Each objFile in objFolder.Files
Set objReg = New RegExp
sData = objFso.OpenTextFile(sPath, ForReading).ReadAll
With objReg
.Global = True
.Pattern = "\r\n" 'vbCrLf
lCount = .Execute(sData).Count + 1
End With
WScript.Echo("The total number of lines including the header is " & lCount)
Set objFso = Nothing
Set objReg = Nothing
Set objFolder = Nothing
set sData = Nothing
Next
But on line 9 I am getting a 'Permission denied' error. I have checked folder permissions and file permissions and I have full rights.
Does anybody have any ideas?
Thanks in advance.
Loop through the files in the folder instead. There's no need to name the file directly.
Dim oFso, oReg, sData, lCount, linesum
Const ForReading = 1
sPath = "C:\Orig\sample\"
Set oFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder(sPath)
For Each objFile in objFolder.Files
Set oReg = New RegExp
sData = oFso.OpenTextFile(sPath, ForReading).ReadAll
With oReg
.Global = True
.Pattern = "\r\n" 'vbCrLf
lCount = .Execute(sData).Count + 1
End With
WScript.Echo("The total number of lines including the header is " & lCount)
Set oFso = Nothing
Set oReg = Nothing
Next

Resources