I need some assistance changing a date range on line 13 of a file:
01/01/201101/31/2011
I plan on setting the script to run every day from the windows scheduler.
I would like the script to change the begining date -15 days from current date and the ending date +15 days f开发者_StackOverflow中文版rom the current date.
I found the DateAdd.cmd written by Rob van der Woude (http://www.robvanderwoude.com) but I am not sure how to pass the values back to my main (calling) script?
Without any ~batch~ assistance, I did the following in C#:
static void Main(string[] args)
{
string inputFile = Path.Combine("C:/temp","textfile.txt");
string outputFile = Path.Combine("C:/temp","textfile2.txt");
using(StreamReader input = File.OpenText(inputFile))
using(Stream output = File.OpenWrite(outputFile))
using(StreamWriter writer = new StreamWriter(output))
{
int count = 1;
while(!input.EndOfStream)
{
// read line
string line = input.ReadLine();
// Get dates 15 days on either side of current date
if(count == 13)
{
DateTime beginRange = DateTime.Today.AddDays(-15);
DateTime endRange = DateTime.Today.AddDays( 15 );
string strBeginDate = beginRange.ToShortDateString();
string strEndDate = endRange.ToShortDateString();
// replace line with new date range
line = "0001" + strBeginDate + strEndDate + "Report submitted by";
}
// increment counter
count++;
// write the file to temp file
writer.WriteLine(line);
}
}
File.Delete(inputFile); // delete original file
File.Move(outputFile,inputFile); // rename temp file to original file name
The batch file language hasn't been significantly updated decades. You still can't do a conventional for
loop. I suggest looking into PowerShell. It is just as powerful (if not more) than the *nix shell languages, but can also leverage the entire .NET framework. If you use PowerShell, this problem would be as simple as
- Open file, go to line 13
- Parse the line as two dates
- Subtract 15 days from one date object and add 15 to the next
- Write the file back out
The fact that you're trying to do real programming in a batch file is truly honorable (I would have commited Seppuku). Try to switch to a more powerful shell language that is more feature complete. Besides, PowerShell is the future of Windows scripting.
I found the DateAdd.cmd written by Rob van der Woude (http://www.robvanderwoude.com) but I am not sure how to pass the values back to my main (calling) script?
I would agree with others that you're better off using a different scripting language (VBS, PowerShell, ...), but to answer this specific question, the DateAdd.cmd batch file sets an environment variable DATEADD to the result of its deliberations.
You can do something like:
CALL DATEADD -15 >NUL:
SET FROMDATE=%DATEADD%
CALL DATEADD 15 >NUL:
SET TODATE=%DATEADD%
echo %FROMDATE%%TODATE%
Note that DateAdd.cmd uses the current user's short date format from the registry, so will give different results depending on the user's locale.
精彩评论