How to write date and time to a file name? - file

My AutoIt script doesn't work. It should rename files by actual date and time.
#include <Date.au3>
#include <File.au3>
FileMove("C:\file.csv", "C:\file" & _NowDate() & _NowTime() & ".csv")
There is no syntax error, but the file isn't renamed. I think Windows rejects symbols like : or /. How to convert time to this format: hh-mm-ss_dd-mm-yyyy?

"... how to convert time in this format : hh-mm-ss_dd-mm-yyyy?"
As per Documentation - Macro Reference (as there is nothing to convert):
Global Const $g_sPathFile = 'C:\file.csv'
Global Const $g_sFormat = '%s-%s-%s_%s-%s-%s'
Global Const $g_sTime = StringFormat($g_sFormat, #HOUR, #MIN, #SEC, #MDAY, #MON, #YEAR)
Global Const $g_sNameNew = StringReplace($g_sPathFile, '.', $g_sTime & '.', -1)
FileMove($g_sPathFile, $g_sNameNew)
yyyymmddhhmmss -format conforms to string sort (displays chronological order by Windows Explorer).
Related.

you can sanitize the output inline
#include <Date.au3>
FileMove("file.csv", "file" & stringreplace(_NowTime(5) , ":" , "-") & "_" &
stringregexpreplace(_NowCalcDate() , "(\d\d\d\d)/(\d\d)/(\d\d)" , "$3-$2-$1") &
".csv")

Related

How to escape equal = sign in VBS Shell command parameter

Using VBS on Windows 2012 R2 I am trying to pass a command line parameter isActive="false" but I cannot get the equal sign to appear in the command line.
Create a dummy batch file like test.bat
echo %1
Pause
Then in the created VBScript
Set oShell = WScript.CreateObject("WSCript.Shell")
oShell.CurrentDirectory = "C:\test"
'strEqual = Chr(61)
strCommand = "test.bat" & " " & "isActive=" &"""false"""
return = oShell.Run(strCommand, 1, True)
Set oShell = Nothing
I get isActive "false" but no equal sign.
I have tried separating out as a unique value
like & Chr(61) & and have tried escaping with / and \ and // and \\ before and after the equal sign. I have tried to use as a variable, strEqual = Chr(61).
I am at a loss as to how to get the = to be part of the string when passed to the command shell. I can write it to a text file and the equal sign is written, but not in the shell.
You observe this behavior because CMD uses not only spaces and tabs, but also commas, semicolons, and the = character as parameter delimiters. Meaning that isActive="false" is parsed as 2 distinct arguments: isActive and "false". If you want it to be parsed as a single argument you need to put the whole key/value pair in quotes: "isActive=false".
Note that the double quotes inside VBScript string literals must be escaped by doubling them. If you require double quotes around the value part of the argument simply add another set of escaped double quotes.
Set oShell = CreateObject("WScript.Shell")
strCommand = "test.bat ""isActive=""false"""""
return = oShell.Run(strCommand, 1, True)
There is also no need to concatenate string literals (except for readability reasons when you want to wrap a long string). Just define your command as a single string.
You may pass a value from VBS to BAT/CMD using process environment variable.
Save the below code as test.vbs:
strCurDir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) & "\"
CreateObject("WScript.Shell").Environment("process").Item("myvar") = "isActive=""false"""
CreateObject("WSCript.Shell").Run strCurDir & "test.bat"
And this code save as test.bat in the same folder:
echo %myvar%
pause
Run test.vbs and console output will be
C:\Windows\system32>echo isActive="false"isActive="false"

Include files from directory (at run-time)

I want to include files from a folder in my script (I tried to Google but can't seem to find any way to do this with AutoIt). Example of what I want to achieve:
LoadFiles()
Func LoadFiles()
$FL = _FileListToArray(#ScriptDir&"\Test\", "*")
$X=1
Do
#include $FL[$X] <== How ?
$X=$X+1
Until $X=$FL[0]
EndFunc
Can anyone point me in the right direction?
In order to include a file(s) in your compiled script, you need FileInstall.
FileInstall ( "source", "dest" [, flag = 0] )
source The source path of the file to compile. This must be a literal string; it cannot be a variable or the result of a function call. It can be a relative path (using .\ or ..\ in the path) to the source file (.au3).
dest The destination path of the file with trailing backslash if only the directory is used. This can be a variable.
flag [optional] this flag determines whether to overwrite files if they already exist:
$FC_NOOVERWRITE (0) = (default) do not overwrite existing files
$FC_OVERWRITE (1) = overwrite existing files
Another way is adding the files as a resource
Good afternoon! There isn't currently a good way to do what you're asking. I've been working on building a UDF to do what you'd like, but I've been running into a couple of issues with it. I have a working prototype but there are some bugs in it. First things first, download this script and call it _includeDir.au3.
_includeDir.au3
#CS
Name: _includeDir.au3
Developer: Timothy Bomer
Copyright: Amarok Studios LLC 2016
Version: 1.0
Description:
The purpose of this UDF is to dynamically include all files inside of a folder.
It works for the most part, but I am still working on a couple of bugs.
#CE
#Include <File.au3>
Global $mainUDF = "IncludeDirUDF"
Global $includeLib = $mainUDF & "\" & "loadIncludes.au3"
Global $tempLib = $mainUDF & "\" & "lib.txt"
Global $includeRewrite = $mainUDF & "\rewrite.au3"
Global $iDirHolder = ""
Func _includeDir($iDir, $lineToInc = 1, $restart = True)
If (checkInclude()) = 1 Then
FileDelete($tempLib)
return
EndIf
If NOT (FileExists($iDir)) Then
MsgBox(16,"Directory Doesn't Exists | _includeDir","The directory " & $iDir & " does not exist!")
return 0
EndIf
$iDirHolder = $iDir
initializeCheck()
; MsgBox(0,"Include Directory", "Attempting to include: " & $iDir)
populateLib($iDir)
populateIncLib()
finalize($lineToInc, $restart)
EndFunc
Func checkInclude()
FileOpen(#ScriptName, 0)
For $i = 1 to _FileCountLines(#ScriptName)
$checkLine = FileReadLine(#ScriptName, $i)
If ($checkLine = '#Include "IncludeDirUDF\loadIncludes.au3"') Then
return 1
EndIf
Next
EndFunc
; START Initialize Check
Func initializeCheck()
; MsgBox(0,"Checking. . .", "Is this initialized?")
If (FileExists($mainUDF)) Then
If NOT (FileExists($includeLib)) Then
isError(2)
return
EndIf
; MsgBox(0,"Initialized","The UDF has been initialized")
Else
isError(1)
return
EndIf
EndFunc
; END Initialize Check
; START Library Population
Func populateLib($iDir = $iDirHolder)
; MsgBox(0,"Populating","Attempting to populate the library")
If (FileExists($tempLib)) Then
; MsgBox(0,"Temp File Found","The temporary library file has been found. Attempting to populate.")
$tLibCont = _FileListToArray(#ScriptDir & "\" & $iDir & "\", "*")
$iDirSize = $tLibCont[0]
; MsgBox(0,"Size of Included Directory", $iDir & " contains " & $iDirSize & " files to include!")
$writeLib = FileOpen($tempLib, 1)
While $iDirSize > 0
FileWriteLine($writeLib, '#Include "..\' & $iDir & '\' & $tLibCont[$iDirSize] & '"')
$iDirSize -= 1
WEnd
FileClose($writeLib)
Else
isError(3)
return
EndIf
EndFunc
; END Library Population
; START Include Library Population
Func populateIncLib()
; MsgBox(0,"Rewriting. . .", "Attempting to re-write the include library")
#CS
If (FileExists($includeLib)) Then
FileDelete($includeLib)
_FileCreate($includeLib)
EndIf
#CE
FileOpen($tempLib, 0)
For $i = 1 to _FileCountLines($tempLib)
$line = FileReadLine($tempLib, $i)
$reWriteLib = FileOpen($includeLib, 9)
FileWriteLine($reWriteLib, $line)
FileClose($reWriteLib)
Next
FileClose($tempLib)
EndFunc
; END Include Library Population
; START Finalize
Func finalize($lineToInc, $restart)
_FileWriteToLine(#ScriptName, $lineToInc, '#Include "IncludeDirUDF\loadIncludes.au3"', False)
If ($restart = True) Then
runFile(#ScriptName)
EndIf
exit
return
EndFunc
Func runFile($rFile)
$file_loc = $rFile
If #Compiled = 1 Then
$file_exe = FileGetShortName(#AutoItExe & ' /AutoIt3ExecuteScript "' & $file_loc & '"')
Run($file_exe)
Else
$file_au3 = FileGetShortName($file_loc)
Run(#AutoItExe & " " & $file_au3, "", #SW_HIDE)
EndIf
EndFunc
; START Error Reporting
Func isError($eFlag = "", $eMessage = "There was an error!")
If ($eFlag = "") Then
; MsgBox(16,"ERROR", $eMessage)
Exit
EndIf
If ($eFlag = 1) Then
; MsgBox(16,"Not Initialized","This UDF has not been initialized")
DirCreate($mainUDF)
Sleep(250)
initializeCheck()
return
ElseIf ($eFlag = 2) Then
; MsgBox(16,"Missing File","Missing the include library!")
_FileCreate($includeLib)
initializeCheck()
return
ElseIf ($eFlag = 3) Then
; MsgBox(16,"Missing File", "Missing the temporary library! Creating it now!",3)
_FileCreate($tempLib)
populateLib()
return
EndIf
EndFunc
; END Error Reporting
To use this UDF, include the file with:
Include "_includeDir.au3"
Next, call the function by following the below format.
_includeDir("Directory to Include", $lineToIncludeOn, $restart)
The directory to include would be the name of the directory with all of the files you're trying to include.
The $lineToIncludeOn specifies what line of the script the #Include will be written on. This is an optional parameter, and will default to line 1.
Lastly, $restart specifies if the script needs to be restarted or not. Sadly, the biggest bug is that the script needs to be restarted in order for the UDF to include all of the files. Which probably takes away the useful functionality of the entire script. This is an optional parameter, by default, it will be set to True and automatically restart the script.
Here's an example.
INSIDE OF WORKING DIRECTORY
Includes Folder
Example.au3
_includeDir.au3
INSIDE OF Includes Folder
One.au3
Two.au3
Three.au3
Four.au3
Five.au3
One.au3
$oneVar = "First variable"
Two.au3
$twoVar = "Second variable"
Three.au3
$threeVar = "Third variable"
Four.au3
$fourVar = "Fourth variable"
Five.au3
$fiveVar = "Fifth variable"
So, we are going to try to include One.au3, Two.au3, Three.au3, Four.au3, and Five.au3 into Example.au3.
Example.au3
; Exclude the numbers before the code. It's there just to show you the line the code is written on.
(1) #Include "_includeDir.au3"
(2)
(3) _includeDir("Includes Folder")
(4) MsgBox(0,"Included Variables","Variable One: " & $oneVar & #CRLF & "Variable Two: " & $twoVar & #CRLF & "Variable Three: " & $threeVar & #CRLF & "Variable Four: " & $fourVar & #CRLF & "Variable Five: " & $fiveVar)
This will add the line:
#Include "IncludeDirUDF\loadIncludes.au3"
to line one of Examples.au3, then restart Example.au3 to display the variables from the included files. If you changed the files inside of the Included Files directory, you will need to remove the #Include line for the loadIncludes.au3, and delete the folder that was generated. (IncludeDirUDF).
Let's say you don't want the #Include to be written to line one of Example.au3... To specify what line you want it to be written to, simply add the next parameter to the function call. For example, we want to write it to line 5 of Example.au3, we would use this:
_includeDir("Includes Folder", 5)
The last parameter is the restart parameter. This specifies if Example.au3 should be restarted after the directory is included. It is set to True by default. If you want Example.au3 to exit and stay terminated, simply add False to the end of the function call.
_includeDir("Includes Folder", 5, False)
In order to do what you're trying to do, the best way to use this would be to put it at the top of your Example.au3 (or whatever your script is) right underneath the includes. The reason for this is because it will auto-restart your script if when it generates the library and it could cause an error if it's not at the top. I hope this poorly written UDF helps you out! Let me know if there's something it's not doing that you need it to do. If not, let me know and I will fix it! Happy programming my friend! If this is too hard to follow, see my more detailed demonstration on the official AutoIt forum HERE
Thanks,
Tim
This is how i fixed it if anyone have the same issue ..
Only thing IncludeList.au3 have to exsist in the directory before you run the script or you will get include error
#include <WinAPIFiles.au3>
#include <File.au3>
; Delete Old IncludeList.au3
If FileExists("IncludeList.au3") Then
FileDelete("IncludeList.au3")
EndIf
; Get Files From Dir
$IL = _FileListToArray(#ScriptDir&"\Functions\", "*")
; Create New IncludeList.au3
$FH = FileOpen("IncludeList.au3", $FO_APPEND)
; Check For Errors
If #error <> 1 or #error <> 4 Then
; Loop True Files In Dir
For $FC = 1 To UBound($IL)-1 Step +1
; Write New #Include '.\Function\FilesToInclude.au3'
FileWrite($FH, "#Include '.\Functions\"&$IL[$FC]&"'"& #CRLF)
Next
EndIf
; Close File Handler
FileClose($FH)
; Include All The Files In Directory True IncludeList We Created
#include "IncludeList.au3"
; And Now You Can Call Any Functions From The Scripts From That Directory

Replace Number Strings in Text File

I need a code in VBScript or batch to replace 5 Caracters (the bold numbers below) in a line of a text file to change ports numbers.
change_port.vbs:
prefsFile = "%userprofile%\Desktop\teste.msrcincident"
prefsFile = CreateObject("WScript.Shell").ExpandEnvironmentStrings(prefsFile)
newPrefs = "5500"
Set fso = CreateObject("Scripting.FileSystemObject")
json = fso.OpenTextFile(prefsFile).ReadAll
Set re = New RegExp
re.Pattern = "":*?",*,"
json = re.Replace(json, ": & newPrefs & ",*,")
fso.OpenTextFile(prefsFile, 2).Write(json)
Original text file:
RCTICKET="65538,1,10.0.0.1:54593,*,ucIdnri2n4QPf/bv92mtx4w2qliCNdyDgBpHPr7nJFdxYL2/dR+iel9Mh4zgD6QR,*,*,Fbjf5rcIrdrlnibnisrzRcO8tsY=" PassStub="HG)7HbhIZPTiKy" RCTICKETENCRYPTED="1" DtStart="1457700115" DtLength="142560" L="0"/></UPLOADINFO>
Expected result text file:
RCTICKET="65538,1,10.0.0.1:5500,*,ucIdnri2n4QPf/bv92mtx4w2qliCNdyDgBpHPr7nJFdxYL2/dR+iel9Mh4zgD6QR,*,*,Fbjf5rcIrdrlnibnisrzRcO8tsY=" PassStub="HG)7HbhIZPTiKy" RCTICKETENCRYPTED="1" DtStart="1457700115" DtLength="142560" L="0"/></UPLOADINFO>
Can anyone help me?
Your search and replacement expressions are messed up. You're looking for a colon (:) followed by one or more digits (\d+ or [0-9]+) followed by a comma (,), and want to replace that with a colon followed by the new port number and a comma.
Change this:
re.Pattern = "":*?",*,"
json = re.Replace(json, ": & newPrefs & ",*,")
into this.
re.Pattern = ":\d+,"
json = re.Replace(json, ":" & newPrefs & ",")
Always keep your expressions as simple as possible.

Code giving me an ArgumentExeption?

This code is giving me an ArgumentExeption when the correct values are put in both ComboBoxes, executing the code. The code basically just deletes a file and replaces it with a modified version taken from another folder.
Here is the exact text of the error message:
An unhandled exception of type 'System.ArgumentException' occurred in Microsoft.VisualBasic.dll
Additional information: The given file path ends with a directory separator character.
Here's the code:
If ComboBox1.Text = "Nokia" And ComboBox2.Text = "HTC" And My.Computer.FileSystem.FileExists("C:\Users\" + user + "\Documents\Fiddler2\Scripts\CustomRules.js") Then
My.Computer.FileSystem.DeleteFile("C:\Users\" + user + "\Documents\Fiddler2\Scripts\CustomRules.js")
My.Computer.FileSystem.CopyFile("Config\OEM\NokiaHTC.js", destinationFileName:="C:\Users\" + user + "\Documents\Fiddler2\Scripts\")
Else
My.Computer.FileSystem.CopyFile("Config\OEM\NokiaHTC.js", destinationFileName:="C:\Users\" + user + "\Documents\Fiddler2\Scripts\")
End If
The problem is that the destination file path ends with a "\" value. This isn't legal for the CopyFile API. Switch it to include the file name and this should fix the problem
My.Computer.FileSystem.CopyFile( _
"Config\OEM\NokiaHTC.js", _
destinationFileName:="C:\Users\" + user + "\Documents\Fiddler2\Scripts\NokiaHTC.js")

Help with SSIS Package

Hi all i've got a complex SSIS package, however i'm hitting my head against a brick wall with a particular part. I've got a maintenance part that will delete files that are older than 3 months old (from today's date). The files all have the date in the filename, for example AA-CDR-20110606030000-2-001A648E6F74-026874.xml
So i've written a task that will loop over all the files in a particular folder using a Foreach loop, then i have a script that will load in the filename using a variable set using the foreach loop. Then delete the file using the script below. This works fine when running in debug mode. However when trying to execute this on the server i get a failure with a "System.FormatException: String was not recognized as a valid DateTime.". I really dont understand why, any ideas?
DateTime deleteDate = DateTime.Today.AddMonths(-3);
String file = Dts.Variables["FileName"].Value.ToString();
String fileDateString = file.Substring(42, 8);
String fileDateYear = fileDateString.Substring(0, 4);
String fileDateMonth = fileDateString.Substring(4, 2);
String fileDateDay = fileDateString.Substring(6, 2);
DateTime fileDateTime = Convert.ToDateTime(fileDateDay + "-" + fileDateMonth + "-" + fileDateYear);
if (fileDateTime < deleteDate)
{
System.IO.File.Delete(file);
}
It seems that there is a file on the production server that does not follow the pattern and the date cannot be extracted from its name.
Try to use something like this:
try
{
DateTime fileDateTime = Convert.ToDateTime(fileDateDay + "-" + fileDateMonth + "-" + fileDateYear);
if (fileDateTime < deleteDate)
{
System.IO.File.Delete(file);
}
}
catch (System.FormatException)
{
// log the Dts.Variables["FileName"] value here to see why it could not be parsed
}

Resources