batch to search in a folder - batch-file

I am trying to write a batch file . which looks in a folder for specific files, takes their path and uses them for calling a java script: for example: i have a folder cbacklog in desktop which include *.xls file and i have a converter.js java script. i want to look in cbacklog if it has excell files , i will take this file path and call converter.js converter will convert this file. then batch file will move to next excell file... take its pats and uses it for convert.js
var fso = new ActiveXObject("Scripting.FileSystemObject");
var xls03Path = WScript.Arguments(0);
xls03Path = fso.GetAbsolutePathName(xls03Path);
var xls95Path = xls03Path.replace("cbacklog", "dbacklog");
xls95Path =xls95Path.replace(/\.xls[^.]*$/, ".xls");
var objExcel = null;
try
{
WScript.Echo("Saving '" + xls03Path + "' as '" + xls95Path + "'...");
objExcel = new ActiveXObject("Excel.Application");
objExcel.Visible = false;
var objExcl = objExcel.Workbooks.Open(xls03Path);
var wdFormatxls = 39;
objExcl.SaveAs(xls95Path, wdFormatxls);
objExcl.Close();
fso.MoveFile(xls03Path,"C:\\Users\\cguneyel\\Desktop\\cbacklog\\processed\\");
}
finally
{
if (objExcl != null)
{
objExcl.Quit();
}
}

for %%a in ("c:\somewhere\cbacklog\*.xls") do cscript converter.js "%%~fa"
for each xls file in folder call the script with the full path to file as argument

Related

SSIS Archiving a file

I have an SSIS package that outputs a csv file what I want to do is look in the destination folder before I generate a csv and if one already exists (I produce them on a daily basis ) then move it to an archive folder.
my file name structure is "NAME_YYMMDD_HHMM.csv" I'm not sure how I go about looking for a file as the date and time will always be different. i've created a variable for the filename "NAME_*_.csv but not sure how id add this to a file system task? if a file doesn't exist id like it to just move on to next step in package if it does exist then move file to archive folder
You should use a script task to do this:
Use a variable in string file instead which holds your values from YYMMDD since HHMM is unable to get when you created it run time.
Date formats can be found here
Use namespace using System.IO;
string filepath = #"D:\new";
string file = "test_171205_1010.txt";
string fullpath = filepath + #"\" + file;
string newpath = #"D:\arch\";
string newfullpath = newpath + file;
if(
File.Exists(fullpath))
{
File.Move(fullpath, newfullpath);
}
Update
And if you wanna use something about todays date, you can do like below where i look for all files of today and move them. Its up to your what the logic should be.
string txtFile = null;
string txtMoveFile = null;
string date = DateTime.Now.ToString("yyMMdd");
string filepath = #"D:\new";
/*USE THIS LINE IF YOU WANNA USE VARIABLE FROM FOREACH LOOP CONTAINER*/
string file = Dts.Variables["User::name"].Value.ToString() +"_*_*.txt";
//string file = "test_"+date+"_*.txt";
string[] allfilesfromcurrentdate = Directory.GetFiles(filepath, file);
string fullpath = filepath + #"\" + file;
string newpath = #"D:\arch\";
string newfullpath = newpath + file;
foreach(string fileName in allfilesfromcurrentdate)
{
if(fileName.Contains("test_"+date))
{
txtFile = fileName;
txtMoveFile = txtFile.Replace("new", "arch");
if(File.Exists(txtFile))
{
File.Move(txtFile, txtMoveFile);
}
}
}

Convert sed replace rule to batch/windows

I am trying to replace a version number in my bower file with one supplied to the batch file. In *nix with "sed" available to me this would be easy and done as follows:
sed -i -e "s/\(\"version\":\).*/\1\"$RELEASE_NUMBER\",/" bower.json
Which searches the version: and replaces the part after it with the RELEASE_NUMBER variable (plus a ","). However, I can't seem to get this right in batch using
for /f .. in bower.json ..
kind of setups. I can't use cygwin so I have to convert the sed to windows runnable code.
Closest thing to a one-liner without requiring non-native utilities would be to use PowerShell's replace method.
set "RELEASE_NUMBER=4.8"
powershell "(gc bower.json) -replace '(\"version\":\s*)[^,]+', '$1\"%RELEASE_NUMBER%\"' | out-file bower.json"
Scraping and manipulating structured data (such as JSON, XML, HTML, etc) as complicated flat text always makes me cringe though. What if your JSON were minified? If I were you, I'd parse the JSON as JSON and manipulate it as an object. It takes a little more effort, but it's safer. Save this with a .bat extension.
#if (#CodeSection == #Batch) #then
#echo off & setlocal
set "RELEASE_NUMBER=4.8"
set "JSONfile=bower.json"
cscript /nologo /e:Jscript "%~f0" "%RELEASE_NUMBER%" "%JSONfile%"
goto :EOF
#end // end Batch / begin JScript hybrid chimera
var fso = WSH.CreateObject('scripting.filesystemobject'),
htmlfile = WSH.CreateObject('htmlfile'),
args = { 'version': WSH.Arguments(0), 'file': WSH.Arguments(1) },
fHandle = fso.OpenTextFile(args.file, 1);
// import JSON methods from htmlfile COM object
htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
var JSON = htmlfile.parentWindow.JSON;
var struct = JSON.parse(fHandle.ReadAll());
struct.version = args.version;
fHandle.Close();
fHandle = fso.CreateTextFile(args.file, true);
fHandle.write(JSON.stringify(struct, null, '\t'));
fHandle.Close();
You might need to modify the struct.version = args.version line depending on the hierarchical structure of your JSON (i.e. struct.childName[0].grandChild.version = args.version). If the position of the "version" key can't be predicted, you can search for and modify it with a recursive function:
function findKey(haystack, needle) {
for (var i in haystack) {
if (needle == i) return haystack;
else if (key = findKey(haystack[i], needle)) return key;
}
}
var struct = JSON.parse(fHandle.ReadAll());
findKey(struct, 'version').version = args.version;

How can I overwrite a file's "Date created" with its "Date modified" in Windows?

I have a folder full of files with correct Date modified times but incorrect date created times. I want to set the dateCreated file attribute to the time of the Date modified.
The closest thing I have to my solution is a batch file that sets the date modified time to the when the file was created ( https://stackoverflow.com/a/24951475/2780666 ) but I want to do the opposite. How do I do this if possible?
Assuming the script you found works, I would try the following.
#if (#This==#IsBatch) #then
#echo off
rem **** batch zone *********************************************************
setlocal enableextensions disabledelayedexpansion
set "targetFolder=%~1"
if not defined targetFolder set "targetFolder=%cd%"
rem call javascript part of batch file
cscript //nologo //e:Javascript "%~f0" /startFolder:"%targetFolder%"
rem End of batch area. End batch execution before reaching js zone
endlocal
exit /b
#end
// **** Javascript zone *****************************************************
if (!WScript.Arguments.Named.Exists('startFolder')) {
// if no start folder is given, leave
WScript.Quit(1);
};
// retrieve start folder
var startFolder = WScript.Arguments.Named.Item('startFolder');
// instantiate needed components
var fso = WScript.CreateObject('Scripting.FileSystemObject');
var shell = WScript.CreateObject('Shell.Application');
// recursive function to set the ModifyDate to the CreationDate
(function processFolder( folderPath ){
// test for valid paths
folderPath = fso.GetAbsolutePathName((folderPath || '' ));
if (!fso.FolderExists(folderPath)) return ;
// retrieve a reference to the folder namespace
var folderNS = shell.NameSpace(folderPath);
// process files inside this folder
for (var files = new Enumerator(fso.GetFolder( folderPath ).Files ); !files.atEnd() ; files.moveNext()){
var file = files.item();
WScript.StdOut.WriteLine( file.Path );
folderNS.ParseName( file.Name ).DateCreated = file.ModifyDate;
};
// process files under child folders
for (var folders = new Enumerator(fso.GetFolder( folderPath ).SubFolders); !folders.atEnd() ; folders.moveNext()){
processFolder( folders.item().Path );
};
})( startFolder );
WScript.Quit(0);

check if a number of files exists in a directory - matlab

How could I check if a number of csv files are present in the current directory?
I have a csv file called PowerOutput.csv, I can see if this exists with
exist('PowerOutput.csv','file')
However, I could have a number of these files e.g. PowerOutput1.csv, PowerOutput2.csv, PowerOutput3.csv and so on.
What is the best way of finding which files exist in a directory?
At the moment I have tried:
TopFolder = pwd;
SubFolder = dir(TopFolder);
SubFolder = {SubFolder.name};
SubFolder(strncmp(SubFolder,'.',1)) = [];
% -- find the number of PowerOutput
num_Power = strncmp({'PowerOutput'}, SubFolder,length('PowerOutput'));
num_Power(num_Power == 0) = [];
num_Power = 1:length(num_Power);
and then I can import the data by:
% -- import inflow
for i = 1:length(num_Power);
filename = fullfile(TopFolder,horzcat('PowerOutput',num2str(num_Power(i)),'.csv'));
fid = fopen(filename);
headers = textscan(fid, '%s%s', 1, 'delimiter',',');
dat = textscan(fid,'%s%f%f','delimiter',',','headerlines',1);
fclose(fid);
end
But this seems like a really long-winded way of doing it. Any suggestions?
use * in dir:
files = dir( fullfile( TopFolder, SubFolder.name, 'PowerOutput*.cvs' ) );

running a batch file from another batch file as an admisitrator

I need to run a batch file (setup.bat) which will call another batch file (make_dir.bat) which will create a folder in the "C:\Program Files" directory. This is for an internal installer. All the users will be logged in with their user names but will have local administrator rights. I've tried two approaches but neither work.
Approach 1:
SET PRGFILES=%programfiles%\mySoftware
SET admin=N
SET domain=%USERDOMAIN%\
IF /i "%domain%" EQU "%computername%\" set domain=
SET user=%domain%%username%
FOR /f "Tokens=*" %%a IN ('net localgroup administrators^|find /i "%user%"') DO SET admin=Y
IF "%admin%"=="Y" (
MD "%PRGFILES%"
)
This says Access is denied
Approach 2:
runas /user:%Username% shell\make_dir.bat
where make_dir.bat is
md "%programfiles%\mySoftware"
This asks for the current username and password but somehow fails after that. I have checked that all users have local admin rights and can manually create a folder in their programfiles folder.
Thanks for the help.
I use such script to run .bat file as administrator, using JScript:
var batch = "fixuac.bat"
var fso = new ActiveXObject("Scripting.FileSystemObject");
var curdir = fso.GetParentFolderName(WScript.ScriptFullName);
var wbemFlagReturnImmediately = 0x10;
var wbemFlagForwardOnly = 0x20;
var objWMIService = GetObject("winmgmts:\\\\.\\root\\CIMV2");
// var objWMIService = GetObject("winmgmts:" + "{impersonationLevel=impersonate}!\\" + "." + "\root\cimv2");
var colItems = objWMIService.ExecQuery("SELECT * FROM Win32_OperatingSystem", "WQL",
wbemFlagReturnImmediately | wbemFlagForwardOnly);
var enumItems = new Enumerator(colItems);
var objItem = enumItems.item();
// http://en.wikipedia.org/wiki/Ver_(command)
var major_ver = objItem.Version.split(".")[0];
var objShell = new ActiveXObject("shell.application");
// http://msdn.microsoft.com/en-us/library/windows/desktop/gg537745.aspx
// Shell.ShellExecute method
// iRetVal = Shell.ShellExecute( sFile, [ vArguments ], [ vDirectory ], [ vOperation ], [ vShow ] )
// If (vShow==1) open the application with a normal window.
// Check for Vista and upper.
if (major_ver >= 6) {
// Request admin permission.
objShell.ShellExecute(batch, curdir, "", "runas", 1);
} else {
objShell.ShellExecute(batch, curdir);
}

Resources