How to write to a text file in VBScript, without overwriting? - vbscript

I am currently writing a script which parses the ServiceTage, Computername and Username from a computer and outputs it to a text file on a share, but it seems that it always overwrites the data there rather than adding to it.
The code is as follows:
'Get Dell Service Tag Info
set ProSet = GetObject("winmgmts:").InstancesOf("Win32_BIOS")
Set ProSet1 = GetObject("winmgmts:").InstancesOf("Win32_SystemEnclosure")
For each Pro in ProSet
For each Pro1 in ProSet1
ServiceTag=Pro.SerialNumber
exit for
Next
exit for
Next
'get username and computername, could also be asked in a batch
Set oShell = WScript.CreateObject("WScript.Shell")
Set oShellEnv = oShell.Environment("Process")
sComputerName = oShellEnv("ComputerName")
sUsername = oShellEnv("username")
dim filesys, filetxt, getname, path
Set filesys = CreateObject("Scripting.FileSystemObject")
Set filetxt = filesys.CreateTextFile("\\xx.xx.xx.xx\Support\DataLog.txt", 8, True)
path = filesys.GetAbsolutePathName("\\xx.xx.xx.xx\Support\DataLog.txt")
getname = filesys.GetFileName(path)
filetxt.WriteLine sUsername & ", " & sComputerName & ", " & ServiceTag
filetxt.Close
Thank you!

Straight from the VBScript Docs:
object.CreateTextFile(filename[, overwrite[, unicode]])
object.OpenTextFile(filename[, iomode[, create[, format]]])
From your code:
Set filetxt = filesys.CreateTextFile(filename, 8, True)
Diagnosis:
You call .CreateTextFile() with the parameters of .OpenTextFile()
Remedy:
Use .OpenTextFile():
Set filetxt = filesys.OpenTextFile(filename, 8, True)

Related

VBScript Using Computername to Name a File

New to VBScript and having a problem grasping this concept.
This is the code:
Set WshNetwork = WScript.CreateObject("WScript.Network")
strCompName = WshNetwork.Computername
Wscript.Echo WshNetwork.Username >j:\strCompName.txt
WScript.Quit()
Basically I want to the username dumped to a text file and the text file should be named with the name of the computer. I've tried putting the strCompName in quotes, single quotes, parenthesis with no success.
Here is the code that you can use. You need to use FileSystemObject. The FileSystemObject is used to gain access to a computer's file system. It can create new files and access existing ones.
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set objFSO = CreateObject("Scripting.FileSystemObject")
strCompName = WshNetwork.Computername
'writing to file
outFile="c:\TEMP\" & strCompName & ".txt"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write WshNetwork.Username & vbCrLf
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing
Set WshNetwork = Nothing
WScript.Quit()
Save this in .vbs file and run and you will get a text file with computer name in TEMP folder (Change the path if you like).
This code should work. This code opens the file and appends it if the file exists or creates a file and writed to it if it does not exist.
'constants
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
'Load domain, username, & computer variables
Set oShell = CreateObject( "WScript.Shell" )
sDomain = oShell.ExpandEnvironmentStrings( "%USERDOMAIN%" )
sUserName = oShell.ExpandEnvironmentStrings( "%USERNAME%" )
sComputer = oShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )
'Setup filesystemobject
Set oFSO=CreateObject("Scripting.FileSystemObject")
'Check to see if file exists. If exists open it forAppending
'else create file and write to it.
outFile="c:\export\" & sComputer & ".txt"
If oFSO.FileExists(outFile) Then
Set objFile = oFSO.OpenTextFile(outFile, ForAppending, True, TristateTrue)
Else
Set objFile = oFSO.CreateTextFile(outFile,True)
End If
'write to file
objFile.WriteLine sDomain & "\" & sUsername & " - " & Now
'clean up objects
objFile.Close
Set objFile = Nothing
Set oFSO = Nothing
Set oShell = Nothing

How to search a folder name at a particular location, with a wildcard character and store in a variable?

This is the script I have written and I have mentioned the issue I am facing below.
Option Explicit
Dim FSO, WSH, RunDefaultProfile
Dim PF, UPF
Set FSO = CreateObject("Scripting.FileSystemObject")
Set WSH = CreateObject("Wscript.Shell")
UPF = Wsh.ExpandEnvironmentStrings("%userprofile%")
PF = Wsh.ExpandEnvironmentStrings("%ProgramFiles(x86)%")
RunDefaultProfile = """" & PF & "\Mozilla Firefox\firefox.exe" & """" & _
" -CreateProfile default"
' Create the Default profile if it not exists
If NOT FSO.FolderExists (UPF & "\AppData\Roaming\Mozilla\Firefox\Profiles\c4ssju9t.default") Then
WSH.Run RunDefaultProfile
End if
Now the challenge I am facing is, Firefox creates a random .default folder on each machine and I can't use my If NOT FSO.FolderExists condition. Also I want store the .default folder name if already exists. I will use that to run other commands and expand my script.
The path to the profile is stored in the file %APPDATA%\Mozilla\Firefox\profiles.ini. You can read it from the file like this:
Set fso = CreateObject("Scripting.FileSystemObject")
Set sh = CreateObject("WScript.Shell")
configdir = sh.ExpandEnvironmentStrings("%APPDATA%\Mozilla\Firefox")
inifile = fso.BuildPath(configDir, "profiles.ini")
If fso.FileExists(inifile) Then
Set f = fso.OpenTextFile(inifile)
Do Until f.AtEndOfStream
line = f.ReadLine
If Left(line, 5) = "Path=" Then
relPath = Split(line, "=")(1)
Exit Do
End If
Loop
f.Close
End If
This will get the first profile path from the INI file (if it exists).
You can then use it like this to create a missing profile:
profileExists = False
If Not IsEmpty(relPath) Then
profile = fso.BuildPath(configdir, relPath)
profileExists = fso.FolderExists(profile)
End If
If Not profileExists Then sh.Run RunDefaultProfile

Attempting to extract printers from users machine and then outputting to a text fill.

I am attempting to extract the printers from a users machine and then output to a text file but when I run the test I get a invalid procedure call or argument for this specific line of code.
Set objOutputFile = objFSO.OpenTextFile(outFile, ForAppending, True)
I have attempted to change OpenTextFileto CreateTextFile but I need the lines to appended to file as it will be running as a log on script.
I have done some research and used the Microsoft developer articles to help me debug the issue in the code but I don't have much experience in Visual Basic.
I have added the entire script to give context to the what is going on.
dim objComputerName, ObjNetwork , strText , objfile, StrComputer
dim wshnetwork
Set wshnetwork = CreateObject ("Wscript.network")
StrComputer = WshNetwork.ComputerName
If IsEmpty(StrComputer) Then Wscript.Quit
Set WshNetwork = CreateObject("WScript.Network")
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters = objWMIService.ExecQuery("Select * from Win32_Printer")
Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
outFile = "C:\scripts\Printers" & StrComputer
Set objOutputFile = objFSO.OpenTextFile(outFile, ForAppending, True)
For Each objPrinter in colInstalledPrinters
strTest = Left(objPrinter.Name, 2)
objOutputFile.WriteLine(objPrinter.Name)
objfile.close
Next
Set objPrinter = WshNetwork.EnumPrinterConnections
'Set objOutputFile = objFSO.OpenTextFile (filOutput, ForAppending, True)
If objPrinter.Count = 0 Then
WScript.Echo "No Printers Mapped "
else
For intDrive = 0 To (objPrinter.Count -1) Step 2
intNetLetter = IntNetLetter +1
printer = "UNC Path " & objPrinter.Item(intDrive) & " = " & objPrinter.Item(intDrive +1) & " Printer : " & intDrive
objOutputFile.WriteLine(printer)
Next
end if
objOutputFile.Close``*
Invalid procedure call or argument
You passed an invalid parameter in your procedure call. This could be because the parameter was out of range, or contained invalid data. Alternately, you may have invoked a procedure at an unexpected time.
To correct this error
Verify that the parameters being passed to the procedure are valid.
Verify that you are calling the function at an appropriate time.
My guess is this line is an ilegal filename.
outFile = "C:\scripts\Printers" & StrComputer
On my computer this is c:\scripts\PrintersSerenity which is probably not right that your text file is called PrintersSerenity without an extension.

Check if folder is there, if not create it on current user logged in VBS

Currently this is my script
Set oWS = WScript.CreateObject("WScript.Shell")
' Get the %userprofile% in a variable, or else it won't be recognized
userProfile = oWS.ExpandEnvironmentStrings( "%userprofile%" )
What I am trying to do is grab the current user logged in, I want it to check the directory D:\"personsuser"\Appdata\Roaming\Local to see if the folder "Local" is created, if it isn't created I want to create one via createobject in vbs. The script above from what i know grabs the current logged on user, however i'm not sure how to use this variable to create a folder.
I know i will have to incorporate something along these lines:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.CreateFolder("C:\FSO")
And or something along these lines:
Dim objNetwork
Dim userName
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objNetwork = CreateObject("WScript.Network")
userName = objNetwork.userName
If fso.driveExists("D:\" & userName & "\AppData\Local\") Then
FSO.CreateDirectory ("D:\" & userName & "\AppData\Local\")
End If
Thanks in advance, not very familiar with VBS however that is the only platform I can operate from in the environment that i'm using it.
Set oWS = WScript.CreateObject("WScript.Shell")
' Get the %userprofile% in a variable, or else it won't be recognized
userProfile = oWS.ExpandEnvironmentStrings( "%userprofile%" )
Dim objNetwork
Dim userName
Dim FSO
Dim Folder
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objNetwork = CreateObject("WScript.Network")
userName = objNetwork.userName
If NOT (FSO.FolderExists(userProfile + "\AppData\Roaming\Local")) Then
' Delete this if you don't want the MsgBox to show
MsgBox("Local folder doesn't exists, creating...")
splitString = Split(userProfile, "\")
' Create folder
MsgBox("D:\" + splitString(2) + "\AppData\Roaming\Local")
'FSO.CreateFolder(splitString(2) + "\AppData\Roaming\Local")
End If
Here you go man, this should work perfect, regards Daniel.
Here is code part from my utilty for FSO:
dim ffso
Function GetFSO
if not IsValidObject(ffso) then set ffso = CreateObject("Scripting.FileSystemObject")
Set GetFSO = ffso
End Function
sub SureDirectoryExists(ADir)
if ADir="" then exit sub
if not GetFSO().FolderExists(ADir) then
SureDirectoryExists ffso.GetParentFolderName(ADir)
ffso.CreateFolder ADir
end if
end sub
This function will create all folders in the path parameter (string).
Public Function CheckCreateFolder(path)
Dim TempPath As String
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
pos = 0
While pos < Len(path)
pos = InStr(pos + 1, path, "\")
TempPath = Left(path, pos)
If Not (FSO.FolderExists(TempPath)) Then
FSO.CreateFolder (TempPath)
End If
Wend
End Function

VBScript: way to check why the script stopped?

I have this VBScript which runs however, while it is processing, it will randomly stop and require a user to hit the spacebar for it to display the rest of its ongoing output.
How do I figure out why this is happening?
Here is a copy of the script:
'On Error Resume Next
Dim arrFolders()
intSize = 0
Function StampNow()
Dim Hr, Mn, Yr, Mon, Dy, Date1
Date1=Now()
Hr=DatePart("h",Date1)
Mn=DatePart("n",Date1)
Yr = DatePart("yyyy",Date1)
Mon = DatePart("m",Date1)
Dy = DatePart("d",Date1)
StampNow = Yr & "-" & Mon & "-" & Dy
end function
'Output log info.
Function OutputToLog (strToAdd)
Dim strDirectory,strFile,strText, objFile,objFolder,objTextFile,objFSO
strDirectory = "c:\log"
strFile = "\dpadmin_copy2run-"& StampNow & ".bat"
'strText = "dpadmin_copy2"
strText = strToAdd
' Create the File System Object.
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check that the strDirectory folder exists.
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
'WScript.Echo "Just created " & strDirectory
End If
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
'Wscript.Echo "Just created " & strDirectory & strFile
End If
set objFile = nothing
set objFolder = nothing
' OpenTextFile Method needs a Const value
' ForAppending = 8 ForReading = 1, ForWriting = 2
Const ForAppending = 8
Set objTextFile = objFSO.OpenTextFile _
(strDirectory & strFile, ForAppending, True)
' Writes strText every time you run this VBScript.
objTextFile.WriteLine(strText)
objTextFile.Close
End Function
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
strFolderName = "D:\1\production\Openjobs"
Set colSubfolders = objWMIService.ExecQuery _
("Associators of {Win32_Directory.Name='" & strFolderName & "'} " _
& "Where AssocClass = Win32_Subdirectory " _
& "ResultRole = PartComponent")
dim diffindates
'Init vars for regex.
Dim retVal, retVal2
Dim Lastprop
Dim objRegExpr 'regex variable
Set objRegExpr = New regexp
Set objRegExprX31 = New regexp
objRegExpr.Pattern = "[0-9][0-9][0-9][0-9][0-9][0-9][A-Z][A-Z][A-Z]"
objRegExprX31.Pattern = "[0-9][0-9][0-9][0-9][0-9][0-9]X31"
objRegExpr.Global = True
objRegExprX31.Global = True
objRegExpr.IgnoreCase = True
objRegExprX31.IgnoreCase = True
'Variables for getting last accessed property.
Dim fs, f
Set fs = CreateObject("Scripting.FileSystemObject")
'Current time vars.
Dim currenttime
currenttime = Now()
ParentFolder = "D:\1\Production\Openjobs\ClosedJobs"
For Each objFolder in colSubfolders
intSize = intSize + 1
retVal = objRegExpr.Test(objFolder.Name)
retVal2 = objRegExprX31.Test(objFolder.Name)
if (retVal OR retVal2 ) then
'set filename to array
strFolderName = objFolder.Name
'Get last modified date.
Set f = fs.GetFolder(objFolder.Name)
Lastprop = f.DateLastModified
'MsgBox(Lastprop)
if ( DateDiff("m", f.DateLastModified, Now()) > 4) then
diffindates = DateDiff("m", f.DateLastModified, Now())
Set objShell = CreateObject("Shell.Application")
Set objCopyFolder = objShell.NameSpace(ParentFolder)
OutputToLog("rem " & f.DateLastModified & ":" & objFolder.Name )
outputtolog("move /Y """ & objFolder.Name & """ " & ParentFolder)
wscript.echo(diffindates & ":" & objFolder.Name & vbCr)
end if
end if
Next
Update
It stops at the line:
Set objTextFile = objFSO.OpenTextFile _
(strDirectory & strFile, ForAppending, True)
with the error Microsoft VBScript runtime error: Permission denied
I'm a little confusd by this. The logfile was only 356kb
I was able to run your script several times without it pausing for input. Run your script with the //X flag to start it in the debugger:
>cscript //nologo //X dpadmin_copy2.vbs"
You should be able to then step through the code.
You can also start putting in wscript.echo trace statements everywhere and see if you can narrow down what it's waiting on.
One thing that's gotten me in the past; If your command console is in QuickEdit mode and you accidentally click anywhere in the console window, the console will hang while it waits for you to press a key.
Well the first step is to remove any global On Error Resume Next statements. Better feedback would come if we could see the script.
You usually get an Permission denied when trying to write to a text file when the text file already has an open handle from some other process or because you have previously opened a handle earlier in you code which you have not closed. I haven't tried this but I don't know why this wouldn't work, you can look at using Handle from Sysinternals (Microsoft) to tell you what process has the open handle for the file. Please see here for a further reference of how to use Handle: http://www.orcsweb.com/blog/post/Closing-open-file-handles.aspx You could also write a second script which runs in a loop to monitor the main script. The second script can verify the first script by doing a WMI Process query which returns only processes that match a defined command line. The second script could then restart the main it stops, alert you, log a file, launch a handle search, etc.

Resources