Jump to content

File read issues after modification


Recommended Posts

I have been writing a script to backup computers.  Part of the script requires running a batch file as eventually it will be a scheduled job in  Windows.  The script works unless I modify the batch file during the running of the script.  The only thing I am changing is line one in the batch file so that it reflects a proper IP address for that location.  I do not understand why this is not working any suggestions would be greatly appreciated.

The flowing is the script.

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Outfile=AdminNASBackup.exe
#AutoIt3Wrapper_Compression=4
#AutoIt3Wrapper_UseUpx=y
#AutoIt3Wrapper_Res_Fileversion=0.1.0.0
#AutoIt3Wrapper_Res_SaveSource=y
#AutoIt3Wrapper_AU3Check_Stop_OnWarning=y
#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w
#AutoIt3Wrapper_Run_Tidy=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
;#RequireAdmin
#include <File.au3>
#include <INet.au3>

;Backup file location
Global $sBackupFileLocation = "c:\Backup", $sIPAddressAdmin, $sIPAddressPersonal

EmbedBackupFiles()
GetLocalIP()

;Get local wired and wireless IP address Call SetNASIP function
Func GetLocalIP()
    Local $sIPLocal = "LocalNotConnected"
    Local $sIPWireless = "WirelessNotConnected"
    Local $objWMI = ObjGet("winmgmts:\\.\root\cimv2")
    Local $colNICs1 = $objWMI.ExecQuery("Select * From Win32_NetworkAdapter WHERE NetConnectionID LIKE 'Local%' AND NetConnectionStatus = '2'")

    For $objNIC In $colNICs1
        Local $colNICcfg = $objWMI.ExecQuery("Select * From Win32_NetworkAdapterConfiguration Where MACAddress = '" & $objNIC.MACAddress & "' AND IPEnabled = 'true'")
        For $objItem In $colNICcfg
            $sIPLocal = $objItem.IPAddress(0)
            If $sIPWireless = "LocalNotConnected" Then
                ;MsgBox(0, "", "LocalNotConnected")
            Else
                ;MsgBox(0, "", $sIPLocal)
            EndIf
        Next
    Next

    Local $colNICs2 = $objWMI.ExecQuery("Select * From Win32_NetworkAdapter WHERE NetConnectionID LIKE 'Wireless%' AND NetConnectionStatus = '2'")
    For $objNIC In $colNICs2
        $colNICcfg = $objWMI.ExecQuery("Select * From Win32_NetworkAdapterConfiguration Where MACAddress = '" & $objNIC.MACAddress & "' AND IPEnabled = 'true'")
        For $objItem In $colNICcfg
            $sIPWireless = $objItem.IPAddress(0)
            If $sIPWireless = "WirelessNotConnected" Then
                ;MsgBox(0, "", "WirelessNotConnected")
            Else
                ;MsgBox(0, "", $sIPWireless)
            EndIf
        Next
    Next

    SetNASIP($sIPLocal, $sIPWireless)
EndFunc   ;==>GetLocalIP


;Set NAS IP address, modify backup scripts and call Backup function
Func SetNASIP(ByRef $sIPLocal, ByRef $sIPWireless)
    Local $sIPAddress
    Local $sIPO4Admin = ".230"
    Local $sIPO4Personal = ".225"

    If $sIPLocal <> "LocalNotConnected" Then
        $sIPAddress = $sIPLocal
        ;MsgBox(0, "Local", $sIPAddress)
    ElseIf $sIPWireless <> "WirelessNotConnected" Then
        $sIPAddress = $sIPWireless
        ;MsgBox(0, "Wireless", $sIPAddress)
    Else
        Exit
    EndIf

    Local $aRet = StringRegExp($sIPAddress, "(\d{1,3})", 3)
    Local $sIPAddress3Octet = $aRet[0] & "." & $aRet[1] & "." & $aRet[2]
    $sIPAddressAdmin = $sIPAddress3Octet & $sIPO4Admin
    $sIPAddressPersonal = $sIPAddress3Octet & $sIPO4Personal

    Local $sIPAddressAdminPing = Ping($sIPAddressAdmin, 4000)

    If $sIPAddressAdminPing Then

        Local $sAdminNASPath = "\\" & $sIPAddressAdmin & "\backups"
        Local $sAdminBackupFileName = $sAdminNASPath & "\" & @ComputerName & "\" & @ComputerName & "_Backup.bkf"

        FileOpen($sBackupFileLocation & "\runBackupWin7.bat", 1)
        _FileWriteToLine($sBackupFileLocation & "\runBackupWin7.bat", 1, "pushd " & $sAdminNASPath, 1)
        FileClose($sBackupFileLocation & "\runBackupWin7.bat")
        FileOpen($sBackupFileLocation & "\runBackupWinXP.bat", 1)
        _FileWriteToLine($sBackupFileLocation & "\runBackupWinXP.bat", 1, "pushd " & $sAdminNASPath, 1)
        FileClose($sBackupFileLocation & "\runBackupWinXP.bat")
        Backup()
        ;ReportStatusUpAdmin($sAdminBackupFileName)
    Else
        Local $sIPAddressPersonalPing = Ping($sIPAddressPersonal, 4000)
        If $sIPAddressPersonalPing Then
            Local $sPersonalNASPath = "\\" & $sIPAddressPersonal & "\backups"
            Local $sPersonalBackupFileName = $sPersonalNASPath & "\" & @ComputerName & "\" & @ComputerName & "_Backup.bkf"
            FileOpen($sBackupFileLocation & "\runBackupWin7.bat", 1)
            _FileWriteToLine($sBackupFileLocation & "\runBackupWin7.bat", 1, "pushd " & $sPersonalNASPath, 1)
            FileClose($sBackupFileLocation & "\runBackupWin7.bat")
            FileOpen($sBackupFileLocation & "\runBackupWinXP.bat", 1)
            _FileWriteToLine($sBackupFileLocation & "\runBackupWinXP.bat", 1, "pushd " & $sPersonalNASPath, 1)
            FileClose($sBackupFileLocation & "\runBackupWinXP.bat")
            Backup()
            ReportStatusUpPersonal($sPersonalBackupFileName)
        Else
            ReportStatusDown()
            Exit
        EndIf
    EndIf
EndFunc   ;==>SetNASIP



;Execute backup scripts based on operating systems.
Func Backup()
    BackupExclusions()

    If @OSVersion = "WIN_7" Then
        Run("runBackupWin7.bat")
    ElseIf @OSVersion = "Win_XP" Then
        Run("runBackupWinXP.bat")
    EndIf
    Exit
EndFunc   ;==>Backup

Func ReportStatusDown()
    RegWrite("HKEY_LOCAL_MACHINE\Software\CED\NASBackup", "NASstatus", "REG_SZ", "Down")
    RegWrite("HKEY_LOCAL_MACHINE\Software\CED\NASBackup", "BackupFileName", "REG_SZ", "Unknown")
EndFunc   ;==>ReportStatusDown

Func ReportStatusUpAdmin(ByRef $sAdminBackupFileName)
    RegWrite("HKEY_LOCAL_MACHINE\Software\CED\NASBackup", "NASstatus", "REG_SZ", "Up")
    RegWrite("HKEY_LOCAL_MACHINE\Software\CED\NASBackup", "BackupFileName", "REG_SZ", $sAdminBackupFileName)
    Local $stime = FileGetTime($sAdminBackupFileName, 0)
    If Not @error Then
        Local $dmyyyy = $stime[2] & "/" & $stime[1] & "/" & $stime[0] & " " & $stime[3] & ":" & $stime[4] & ":" & $stime[5]
        ;MsgBox(0, "Modify date", "Date modified: " & $dmyyyy)
    EndIf
    RegWrite("HKEY_LOCAL_MACHINE\Software\CED\NASBackup", "BackupFileDate", "REG_SZ", $dmyyyy)
    Local $AdminFileSize = FileGetSize($sAdminBackupFileName)
    RegWrite("HKEY_LOCAL_MACHINE\Software\CED\NASBackup", "BackupFileSize", "REG_SZ", $AdminFileSize & "MB")
EndFunc   ;==>ReportStatusUpAdmin

Func ReportStatusUpPersonal(ByRef $sPersonalBackupFileName)
    RegWrite("HKEY_LOCAL_MACHINE\Software\CED\NASBackup", "NASstatus", "REG_SZ", "Up")
    RegWrite("HKEY_LOCAL_MACHINE\Software\CED\NASBackup", "BackupFileName", "REG_SZ", $sPersonalBackupFileName)
    Local $stime = FileGetTime($sPersonalBackupFileName, 0)
    If Not @error Then
        Local $dmyyyy = $stime[2] & "/" & $stime[1] & "/" & $stime[0] & " " & $stime[3] & ":" & $stime[4] & ":" & $stime[5]
        ;MsgBox(0, "Modify date", "Date modified: " & $dmyyyy)
    EndIf
    RegWrite("HKEY_LOCAL_MACHINE\Software\CED\NASBackup", "BackupFileDate", "REG_SZ", $dmyyyy)
    Local $PersonalFileSize = FileGetSize($sPersonalBackupFileName)
    RegWrite("HKEY_LOCAL_MACHINE\Software\CED\NASBackup", "BackupFileSize", "REG_SZ", $PersonalFileSize & "MB")
EndFunc   ;==>ReportStatusUpPersonal


;Add backup exclusions and disable removable storage device not found settings into the registry
Func BackupExclusions()
    RegWrite("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToBackup", "LANDeskBackupExclusions", "REG_MULTI_SZ", "C:\*mp3 /s" & @CRLF & "C:\*mp4 /s" & @CRLF & "C:\*m4v /s" & @CRLF & "C:\*pst /s" & @CRLF & "C:\*ost /s" & @CRLF)
    RegWrite("HKEY_USERS\S-1-5-18\Software\Microsoft\Ntbackup", "Dont Show MS Warning", "REG_QWORD", 00000001)
    RegWrite("HKEY_USERS\.DEFAULT\Software\Microsoft\Ntbackup", "Dont Show MS Warning", "REG_QWORD", 00000001)
    ;MsgBox(0, "", @error)
EndFunc   ;==>BackupExclusions


;Embed backup files into script and extract backup files to c:\Backup upon execution
Func EmbedBackupFiles()
    If Not FileExists("c:\Backup") Then
        DirCreate("c:\Backup")
    EndIf
    FileChangeDir("c:\Backup")
    Local $ntbackup = "C:\Backup\ntbackup.exe"
    Local $ntmsapi = "C:\Backup\Orgntmsapi.dll"
    Local $runBackup = "C:\Backup\runBackup.bat"
    Local $selections = "C:\Backup\selections.bks"
    Local $vssapi = "C:\Backup\vssapi.dll"
    If FileExists($ntbackup And $ntmsapi And $runBackup And $selections And $vssapi) Then
        Return
    Else
        FileInstall("C:\BackupOrg\ntbackup.exe", @WorkingDir & "\")
        FileInstall("C:\BackupOrg\ntmsapi.dll", @WorkingDir & "\")
        FileInstall("C:\BackupOrg\runBackupWinXP.bat", @WorkingDir & "\")
        FileInstall("C:\BackupOrg\runBackupWin7.bat", @WorkingDir & "\")
        FileInstall("C:\BackupOrg\selectionsWinXP.bks", @WorkingDir & "\")
        FileInstall("C:\BackupOrg\selectionsWin7.bks", @WorkingDir & "\")
        FileInstall("C:\BackupOrg\vssapi.dll", @WorkingDir & "\")
    EndIf
    FileCopy(@WorkingDir, "C:\Backup\")
EndFunc   ;==>EmbedBackupFiles

The following is an example of the batch file only line one is changed in the script.

pushd \\10.99.232.230\backups
c:
cd\backup
ntbackup backup "@C:\Backup\selectionsWin7.bks" /j "Admin NAS Backup" /m copy /f "z:\%COMPUTERNAME%\%COMPUTERNAME%_Backup.bkf" /r:yes /SNAP:off
popd z:
Link to comment
Share on other sites

Isn't if a program is already opened it can't be opened by another file?

You'll need to wait to modify it till its either closed or the script has already ran.

At least I'm pretty sure, as this is what I understood your question to be. :)

Snips & Scripts


My Snips: graphCPUTemp ~ getENVvars
My Scripts: Short-Order Encrypter - message and file encryption V1.6.1 ~ AuPad - Notepad written entirely in AutoIt V1.9.4

Feel free to use any of my code for your own use.                                                                                                                                                           Forum FAQ

 

Link to comment
Share on other sites

Isn't if a program is already opened it can't be opened by another file?

You'll need to wait to modify it till its either closed or the script has already ran.

At least I'm pretty sure, as this is what I understood your question to be. :)

 

The script opens the batch file, modifies the first line then closed the file.  Then batch file is executed.

The script works fine if I don't modify the batch file but it is necessary to modify the batch file because each of the location IP addresses are different.  I am not sure why it should make a difference as I am opening, modifying and closing the file before the execution of the batch file.  Any ideas?

Link to comment
Share on other sites

Why are you using a batch file when you can do everything from within your script?

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Why are you using a batch file when you can do everything from within your script?

 

There are certain commands that don't work when you are not in an interactive session.   ie Task Scheduler job but using third partly software.  I can't "open" a command window  and send commands when the session is not interactive.  A batch file allow the commands to be executed without opening command window.

Link to comment
Share on other sites

There's no need to open a command window and send commands to one, use the run command with @ComSpec and keep it hidden (only use @SW_HIDE AFTER you've determined that your commands work as intended). This will work in an interactive or non-interactive session.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

There's no need to open a command window and send commands to one, use the run command with @ComSpec and keep it hidden (only use @SW_HIDE AFTER you've determined that your commands work as intended). This will work in an interactive or non-interactive session.

I will try it again TY.

Link to comment
Share on other sites

AutoIt is basically superior than batch scripting tenfold. Okay you have to invest a little bit of time learning, but when you do you'll appreciate just how quick it is to bang out a script than do it manually yourself.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...