阅读脚本并替换特定行。vbscript

阅读脚本并替换特定行。vbscript,vbscript,Vbscript,我正在开发一个脚本,对用户的Tacacs密码进行加密,并将此字符串写入另一个脚本。我的脚本打开,读取并将Tacacs密码写入我的其他脚本,但它不会覆盖它 首次运行: strTacacs=“Test1234” 第二轮: strTacacs=“Test1234”strTacacs=“Test1234” 我当前的脚本: '***********Write to auto-logon script************ Const ForReading = 1 Const ForWriting =

我正在开发一个脚本,对用户的Tacacs密码进行加密,并将此字符串写入另一个脚本。我的脚本打开,读取并将Tacacs密码写入我的其他脚本,但它不会覆盖它

首次运行:

strTacacs=“Test1234”

第二轮:

strTacacs=“Test1234”strTacacs=“Test1234”

我当前的脚本:

'***********Write to auto-logon script************

Const ForReading = 1
Const ForWriting = 2
newline = "strTacacs = " & chr(34) & Tacacs & chr(34)
line = 30


Set objFSO = CreateObject("Scripting.FileSystemObject")

Dim lineCount : lineCount = 0
Dim firstContent : firstContent = ""

Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
    If LCase(objFSO.GetExtensionName(objFile)) = "vbs" Then
        lineCount = 0
        firstContent = ""
        FileName = objStartFolder & objFile.Name
        Set objStream = objFSO.OpenTextFile(strFile, ForReading)
        Do Until objStream.AtEndOfStream
            lineCount = lineCount + 1
            firstContent = firstContent & objStream.ReadLine & vbCrLf
            'msgbox(firstContent)
            if lineCount = 30 Then 
                firstContent = firstContent & newline
                msgbox(firstContent)
            End if
        Loop  
        Set objStream = objFSO.OpenTextFile(FileName, ForWriting)
        objStream.WriteLine firstContent
        objStream.Close 
    End If  
Next

有人知道我做错了什么吗? 我是脚本编写领域的新手,非常感谢您的帮助


谢谢

当您到达第30行时,看起来您正在编写原始行和新行。仅当
lineCount
为30时才应写入
newline
,否则应写入原始行:

Do Until objStream.AtEndOfStream
    
    lineCount = lineCount + 1
    
    If lineCount = 30 Then
        ' Replace line with newline
        firstContent = firstContent & newline & vbCrLf
    Else
        ' Write original line
        firstContent = firstContent & objStream.ReadLine & vbCrLf
    End If
Loop
如果您知道原始文件中的密码,则可以使用以下命令一次性读取整个文件内容:

然后使用替换密码,最后写回内容

如果您不知道密码,只需替换特定行,则当前的逐行方法更容易。您还可以检查行是否以
strTacacs=
开头,这样您就不用硬编码行号了:

Dim sLine
Dim sPasswordLine
sPasswordLine = "strTacas ="

Do Until objStream.AtEndOfStream

    ' Read line
    sLine = objStream.ReadLine

    If Left(sLine, Len(sPasswordLine)) = sPasswordLine Then
        ' Replace line with newline
        firstContent = firstContent & newline & vbCrLf
    Else
        ' Write original line
        firstContent = firstContent & sLine & vbCrLf
    End If
    
Loop

很好的解释。
Dim sLine
Dim sPasswordLine
sPasswordLine = "strTacas ="

Do Until objStream.AtEndOfStream

    ' Read line
    sLine = objStream.ReadLine

    If Left(sLine, Len(sPasswordLine)) = sPasswordLine Then
        ' Replace line with newline
        firstContent = firstContent & newline & vbCrLf
    Else
        ' Write original line
        firstContent = firstContent & sLine & vbCrLf
    End If
    
Loop