Link to home
Start Free TrialLog in
Avatar of mikehugs
mikehugs

asked on

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

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.
Avatar of domj
domj

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
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
Avatar of mikehugs

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of thunder_moose
thunder_moose

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
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
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
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

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
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
TM

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

Michael
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