Solved

Batch file edit text file and save on local drive AND network drive

Posted on 2004-09-23
12
332 Views
Last Modified: 2010-04-17
Ok, still a newbie here but am liking what I have seen out there so far, so here goes...

I need a batch file to do a few specific things...
1>  Prompt for set <4 character> (alphanumberic) repsonse to a question
2>  Post the prompted answer into a pre-setup 2-line .ini file (text file)
3>  Save the text file as a set name on the local hard drive
4>  Save the same text file as %username.ini% on a network drive

I will be using this file mostly on XP machines, but there is the possibility of also using this same file on a 2000 machine or even an NT machine.  No other OS type would be used.

Thanks to all who respond and assist me with this file.
0
Comment
Question by:mikehugs
  • 6
  • 5
12 Comments
 
LVL 3

Expert Comment

by:domj
ID: 12140222
I would suggest using a VBScript file. Post the exact wording of the ini file and some more specifics on the network drive and I will have a look for you.

Dom
0
 
LVL 3

Expert Comment

by:thunder_moose
ID: 12141930
Hey there,

I have no idea if this is what you want, nor have I had time to test it properly. This asks a question, it only accepts answers 4 chars in length that contain only a-z and 0-9 as characters. It ignores case. It then writes the answer to a file called c:\test.ini. You can ofcourse change this. The program ASSUMES THE FILES EXIST. It only opens them for writing, it doesn't create the file. It also overwrites the previous contents of the file. If you want it to create the file instead, you'll have to change the code. If you want it to append the line to the end of the file instead of overwriting it, you'll also have to change the code.

After that it gets the person currently logged on's username, and it attempts to write the .ini file in the format "username.ini" to a network drive that you specified in the code.

The code is in VBScript. I have no idea weather you know how to use it, so just in case: copy and paste it into a normal text file and save it as a .vbs file on your drive. Then go to the command prompt and execute it by typing "cscript filename.vbs" where filename is the name and path you saved it as earlier. Finally, this script will run on both Windows 2000 and Windows XP.

Option Explicit
On Error Resume Next

Function IsAlphaNumeric(ByVal strTest)
    Dim RE
    Set RE = New RegExp

    With RE
        .Pattern = "[^a-z_0-9]"
        .IgnoreCase = True
        .Global = True
    End With

    IsAlphaNumeric = (StrTest = RE.Replace(strTest, ""))
End Function

Function GetUserName()
    Dim objNet
    Set objNet = CreateObject("WScript.Network")
   
    If Len(objNet.UserName) Then
       GetUserName = objNet.UserName
    Else
       WScript.Echo "ERROR: Couldn't retrieve username."
    End If
End Function

Sub WriteToFile(Byval strFilePath, ByVal strLineToWrite)
    Dim objFSO, objTxtFile
    Const ForWriting = 2
   
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objTxtFile = objFSO.OpenTextFile(strFilePath, ForWriting)
   
    objTxtFile.WriteLine strLineToWrite
    objTxtFile.Close

    If Err <> 0 Then
       WScript.Echo "ERROR: File does not exist"
       Err.Clear
    Else
       WScript.Echo "WROTE: " & strFilePath
    End If
   
    Set objTxtFile = Nothing
    Set objFSO = Nothing
End Sub

Sub Main()
    Dim strAnswer, strUserName
   
    Do Until IsAlphaNumeric(strAnswer) And (Len(strAnswer) = 4)
       WScript.StdOut.Write ("Your question here: ")
       strAnswer = Trim(WScript.StdIn.ReadLine)
       If IsAlphaNumeric(strAnswer) = False Or (Len(strAnswer) <> 4) Then
          WScript.Echo "ERROR: Answer is too long/short or not alpha numeric."
       End If
    Loop
   
    strUserName = GetUserName
    Call WriteToFile("C:\test.ini", strAnswer)
 
    If Len(strUserName) Then
       Call WriteToFile("\\YourNetworkPath\" & strUserName & ".ini", strAnswer)
    End If
   
    WScript.Echo "Done."  
End Sub

Call Main()

If you have any questions, please feel free to leave them here.
Regards,
TM
0
 

Author Comment

by:mikehugs
ID: 12144901
THANK YOU SO MUCH!!!

I am not a VBScript guy so your writing this out has helped tremendously!

I need a couple of tweaks on this script and since I have no idea of how to VBScript, I'll ask for it to be tweaked a little more...

1>  I need the script to EDIT an EXISTING file on the local drive:  "c:\path\test.ini"
2>  I need the script to CREATE a NEW file on the network drive:  "\\NetworkPath\Folder\"%USERNAME%".ini"
3>  I need the 2-line text file to read:

loc="ANSWER FROM QUESTION"
&close browser=y

Thanks to all for reading, and especially TM for your script!
Michael
0
 
LVL 3

Accepted Solution

by:
thunder_moose earned 250 total points
ID: 12161410
Hey there,

Sorry for taking so long to get back to you... weekend and all.

Well, here's the modified code. This code will open the c:\path\test.ini file and create the other one. It'll then APPEND those two lines you gave to the end of the file it opens and write them in the newly created file on the network drive.

Option Explicit

Function IsAlphaNumeric(ByVal strTest)
    Dim RE
    Set RE = New RegExp

    With RE
        .Pattern = "[^a-z_0-9]"
        .IgnoreCase = True
        .Global = True
    End With

    IsAlphaNumeric = (StrTest = RE.Replace(strTest, ""))
End Function

Function GetUserName()
    Dim objNet
    Set objNet = CreateObject("WScript.Network")
   
    If Len(objNet.UserName) Then
       GetUserName = objNet.UserName
    Else
       WScript.Echo "ERROR: Couldn't retrieve username."
    End If
End Function

Sub WriteToFile(Byval strFilePath, ByVal strLineToWrite, ByVal blnCreateNew)
    Dim objFSO, objTxtFile
    Const ForWriting = 2
    Const ForAppend = 8
   
    On Error Resume Next
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    If blnCreateNew = True Then
       Set objTxtFile = objFSO.CreateTextFile(strFilePath)
    Else
       Set objTxtFile = objFSO.OpenTextFile(strFilePath, ForAppend)
    End If
   
    If Err.Number <> 0 Then
       WScript.Echo "ERROR: " & Err.Description & " (" & strFilePath & ")"
       Err.Clear
    Else
       objTxtFile.WriteLine "loc=" & Chr(34) & Ucase(strLineToWrite) & Chr(34)
       objTxtFile.WriteLine "&close browser=y"
       objTxtFile.Close
       WScript.Echo "WROTE: " & strFilePath
    End If
   
    Set objTxtFile = Nothing
    Set objFSO = Nothing
End Sub

Sub Main()
    Dim strAnswer, strUserName
   
    Do Until IsAlphaNumeric(strAnswer) And (Len(strAnswer) = 4)
       WScript.StdOut.Write ("Your question here: ")
       strAnswer = Trim(WScript.StdIn.ReadLine)
       If IsAlphaNumeric(strAnswer) = False Or (Len(strAnswer) <> 4) Then
          WScript.Echo "ERROR: Answer is too long/short or not alpha numeric."
       End If
    Loop
   
    strUserName = GetUserName
   
    Call WriteToFile("C:\test.ini", strAnswer, False)
 
    If Len(strUserName) Then
       Call WriteToFile("\\MyNetwork\Path\" & strUserName & ".ini", strAnswer, True)
    End If
   
    WScript.Echo "Done."  
End Sub

Call Main()


Hope this helps you
TM
0
 

Author Comment

by:mikehugs
ID: 12221012
TM,

I have went ahead and accepted your answer because you did a wonderful job and helped me out tremendously!  

If I can ask though, is there anyway to get the script to just OVERWRITE the file if it already exists.  The way it stands right now I need to delete the added text if I must re-enter a new 4 digit alphanumeric value on the same PC.

If not, thats OK too... you have been a GREAT help!

Thanks again,
Michael
0
 
LVL 3

Expert Comment

by:thunder_moose
ID: 12224396
Hey there,

Thanks for the points and the grade. I'm not entirely sure what you mean. To check weather the file exists or not is a simple matter, however, you say "I need to delete the added text" which makes me think you might mean Append instead of Overwrite?

In other words, do you mean that if the two lines already exist in the textfile, you want it to overwrite just the two lines that were added? So you're referring to the file on the harddisk? In other words, you want to avoid something like this:

loc="AB12"
&close browser=y
loc="ZZ99"
&close browser=y

If that's not what you mean, then I don't understand, because it ALWAYS overwrites the text file on the network drive, as it re-creates the file each time you run the script.

If you could clarify a bit, I'll be glad to see if I can help you,
TM
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:mikehugs
ID: 12262813
TM,

Sorry a few days to get back with you... It's been a B U S Y week.  

You are CORRECT in what you've determined, and in your description.  I am trying to avoid a network file AND a local file like this:

loc="AB12"
&close browser=y
loc="ZZ99"
&close browser=y

The way the script is now, the network file replaces every time... but the local file does not, it simply appends the new text to the end of the file.

I really apologize for asking you to tweak this file but I must ask for this once more as so I can eliminate alot of the repetitious work I do for the machine I support.  I TRULY appreciate ALL your help and continued patience with me and this problem.

Thanks again,
Michael
0
 
LVL 3

Expert Comment

by:thunder_moose
ID: 12263335
Michael,

It's really no problem. Replace the Sub WriteToFile in the script with the new one provided below:

Sub WriteToFile(Byval strFilePath, ByVal strLineToWrite, ByVal blnCreateNew)
    Dim objFSO, objTxtFile
    Dim arrTempFile, strText, I
   
    Const ForWriting = 2
    Const ForReading = 1
   
    On Error Resume Next
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    If blnCreateNew = True Then
       Set objTxtFile = objFSO.CreateTextFile(strFilePath)
       objTxtFile.WriteLine "loc=" & Chr(34) & Ucase(strLineToWrite) & Chr(34)
       objTxtFile.WriteLine "&close browser=y"
    Else
       Set objTxtFile = objFSO.OpenTextFile(strFilePath, ForReading)
       Do Until objTxtFile.AtEndOfStream
          strText = strText & ";" & objTxtFile.ReadLine
       Loop
       
       objTxtFile.Close
       arrTempFile = Split(strText, ";")
       
       For I = 0 to UBound(arrTempFile)
           If Instr(arrTempFile(I), "loc=") Then
              arrTempFile(I) = "loc=" & Chr(34) & Ucase(strLineToWrite) & Chr(34)
           End If
       Next
       
       Set objTxtFile = objFSO.OpenTextFile(strFilePath, ForWriting)
       For I = 1 to UBound(arrTempFile)
           objTxtFile.WriteLine arrTempFile(I)
       Next
    End If
   
    If Err.Number <> 0 Then
       WScript.Echo "ERROR: " & Err.Description & " (" & strFilePath & ")"
       Err.Clear
    Else
       objTxtFile.Close
       WScript.Echo "WROTE: " & strFilePath
    End If
   
    Set objTxtFile = Nothing
    Set objFSO = Nothing
End Sub

This one will CREATE a NEW file on the network drive, as before. It will EDIT the existing file and only CHANGE the line that contains the previous answer.

Is this allright? Anything else?
Regards,
TM

0
 
LVL 3

Expert Comment

by:thunder_moose
ID: 12267566
Whoops, sorry, that was a mistake. Now if there is no loc="answer" line in the file, it won't do anything. I'm writing this on my mac at home, so I can't test it, but I think this sub will work:

Sub WriteToFile(Byval strFilePath, ByVal strLineToWrite, ByVal blnCreateNew)
    Dim objFSO, objTxtFile
    Dim arrTempFile, strText, I, blnFound
   
    Const ForWriting = 2
    Const ForReading = 1
    Const ForAppend = 8

    On Error Resume Next
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    If blnCreateNew = True Then
       Set objTxtFile = objFSO.CreateTextFile(strFilePath)
       objTxtFile.WriteLine "loc=" & Chr(34) & Ucase(strLineToWrite) & Chr(34)
       objTxtFile.WriteLine "&close browser=y"
    Else
       Set objTxtFile = objFSO.OpenTextFile(strFilePath, ForReading)
       Do Until objTxtFile.AtEndOfStream
          strText = strText & ";" & objTxtFile.ReadLine
       Loop
       
       objTxtFile.Close
       arrTempFile = Split(strText, ";")
       blnFound = False

       For I = 0 to UBound(arrTempFile)
           If Instr(arrTempFile(I), "loc=") Then
              arrTempFile(I) = "loc=" & Chr(34) & Ucase(strLineToWrite) & Chr(34)
              blnFound = True
           End If
       Next
       
       If blnFound Then
          Set objTxtFile = objFSO.OpenTextFile(strFilePath, ForWriting)
          For I = 1 to UBound(arrTempFile)
                objTxtFile.WriteLine arrTempFile(I)
          Next
       Else
          Set objTxtFile = objFSO.OpenTextFile(strFilePath, ForAppend)
          objTxtFile.WriteLine "loc=" & Chr(34) & Ucase(strLineToWrite) & Chr(34)
          objTxtFile.WriteLine "&close browser=y"
       End If
    End If

    If Err.Number <> 0 Then
       WScript.Echo "ERROR: " & Err.Description & " (" & strFilePath & ")"
       Err.Clear
    Else
       objTxtFile.Close
       WScript.Echo "WROTE: " & strFilePath
    End If
   
    Set objTxtFile = Nothing
    Set objFSO = Nothing
End Sub


This one reads from the textfile first, and if the line loc= already exists in it, then it just changes the answer in that line, but if it doesn't already exist, then it adds it to the file. At least I think this should work properly, but like I said, i can't test it right now.

Let me know if you need anything else,
TM
0
 

Author Comment

by:mikehugs
ID: 12375107
TM

Sorry for such a long time since reply...

My latest test came up with the following prob:

Writes to LOCAL drive fine.
Write to NEtwork drive gives this error:  "Error:  Object required (Network drive\path)

This is for a machine that DOES NOT have a %USERNAME%.ini file on network drive... so it would need to create a new file.

Thanks if you can help ANY further.

Michael
0
 

Author Comment

by:mikehugs
ID: 12383929
TM

Never mind, it was a network issue.  Thanks again for your help.

Michael
0
 
LVL 3

Expert Comment

by:thunder_moose
ID: 12385304
Hi Michael,

Glad to hear you got it sorted out, because I couldn't find anything wrong with the code. Is everything working fine now? It replaces the line and so on correctly without making a double entry? Are you satisfied with the script?

TM
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now