running a batch file from another batch file as an admisitrator - batch-file

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);
}

Related

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);

vbscript to select file and save directory?

I'm currently working on a program that can start other Programs. Its in batch. But i need it to be user friendly. I want a code that can open a file select window, and save the directory of what i selected into a txt file (or csv or whatever). I'm new on VBS so forgive me if I'm missing something simple. But i searched for a while and got close, only to fail.
Here's what i have so far...
Set shell = CreateObject( "WScript.Shell" )
defaultLocalDir = shell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Desktop"
Set shell = Nothing
file = ChooseFile(defaultLocalDir)
wscript.echo file
Function ChooseFile (ByVal initialDir)
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
Dim winVersion
' This collection should contain just the one item
For Each objItem in colItems
'Caption e.g. Microsoft Windows 7 Professional
'Name e.g. Microsoft Windows 7 Professional |C:\windows|...
'OSType e.g. 18 / OSArchitecture e.g 64-bit
'Version e.g 6.1.7601 / BuildNumber e.g 7601
winVersion = CInt(Left(objItem.version, 1))
Next
Set objWMIService = Nothing
Set colItems = Nothing
If (winVersion <= 5) Then
' Then we are running XP and can use the original mechanism
Set cd = CreateObject("UserAccounts.CommonDialog")
cd.InitialDir = initialDir
cd.Filter = "ZIP files|*.zip|Text Documents|*.txt|Shell Scripts|*.*sh|All Files|*.*"
' filter index 4 would show all files by default
' filter index 1 would show zip files by default
cd.FilterIndex = 1
If cd.ShowOpen = True Then
ChooseFile = cd.FileName
Else
ChooseFile = ""
End If
Set cd = Nothing
Else
' We are running Windows 7 or later
Set shell = CreateObject( "WScript.Shell" )
Set ex = shell.Exec( "mshta.exe ""about: <input type=file id=X><script>X.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(X.value);close();resizeTo(0,0);</script>""" )
ChooseFile = Replace( ex.StdOut.ReadAll, vbCRLF, "" )
Set ex = Nothing
Set shell = Nothing
End If
End Function
Maybe you are looking for something like next bat code snippet?
#echo OFF
SETLOCAL enableextensions
set "_chosen="
if exist "_saved.txt" (
rem read previously saved value
<"_saved.txt" set /P "_chosen="
echo read previously saved value
) else (
for /f "delims=" %%G in ('
cscript //NOLOGO "D:\VB_scripts\SO\31656148.vbs"
') do (
set "_chosen=%%G"
rem save value to a file
>"_saved.txt" echo(%%G
echo file chosen, value saved
)
)
if defined _chosen (
echo("%_chosen%"
) else (
echo no file chosen
)

batch to search in a folder

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

Creating a frame in Batch?

I was wondering, is it possible to create a frame such as a JFrame in Batch? If so I'd really like to know how so that the program I am writing will look better. I'm aware that JFrame is for java, I was giving that as an example, but is it really possible to create something that resembles a JFrame in Batch??
Hope you'll find this answer more satisfying:
mshta "about:<button type='button' onclick='alert("clckd!")'>clck here</button>"
~
rem bat file version
mshta "about:<img src='http://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%%2C_by_Leonardo_da_Vinci%%2C_from_C2RMF_retouched.jpg/402px-Mona_Lisa%%2C_by_Leonardo_da_Vinci%%2C_from_C2RMF_retouched.jpg'>"
~
rem paste in command prompt
mshta "about:<img src='http://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/402px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg'>"
You can create HTA directly from command line / bat file. Though it has a lot of limitations it can be useful.
EDIT
more examples(save them as .bat files):
1.Submit password:
#if (#X)==(#Y) #end /*JScript comment
#echo off
mshta "about:<body onload='prepare()'><script language='javascript' src='file://%~dpnxf0'></script><input type='password' name='pass' size='15'></input><hr><button onclick='pipePass()'>Submit</button><body>" |findstr "^"
exit /b 0
**/
function prepare(){
//document.write("<input type='password' name='pass' size='15'></input><hr><button onclick='pipePass()'>Submit</button>");
}
function pipePass() {
//alert("blabla");
var pass=document.getElementById('pass').value;
var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
close(fso.Write(pass));
}
2.Select a file
#if (#X)==(#Y) #end /*JScript comment
#echo off
mshta "about:<body onload='prepare()'><script language='javascript' src='file://%~dpnxf0'></script><input type='file' name='file' size='30'></input><hr><button onclick='pipeFile()'>Submit</button><body>" |findstr "^"
exit /b 0
**/
function prepare(){
}
function pipeFile() {
var file=document.getElementById('file').value;
var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
close(fso.Write(file));
}
3.Choose button:
#if (#X)==(#Y) #end/*JScript comment
#echo off
mshta "about:<title>chooser</title><body onload='prepare()'><script language='javascript' src='file://%~dpnxf0'></script><span id='container'>buttons:</span></body>" |findstr "^"
exit /b 0
**/
function clckd(a){
// alert(a);
var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
;
close(fso.Write(a));
}
function prepare(){
var element1 = document.createElement("input");
element1.setAttribute("type", "button");
element1.setAttribute("value", "yes");
// this will not work on IE or MSHTA
//element1.setAttribute("onclick", "clckd('yep');");
element1.onclick= function() {clckd('yep');};
var element2 = document.createElement("input");
element2.setAttribute("type", "button");
element2.setAttribute("value", "no");
// this will not work on IE or MSHTA
//element2.setAttribute("onclick", "clckd('nope');");
element2.onclick= function() {clckd('nope');};
var container = document.getElementById('container');
container.appendChild(element1);
container.appendChild(element2);
//alert(document.getElementById('container').innerHTML);
}
No, there are no built-in Windows facilities for making arbitrary GUI widgets from batch files.

edit a specific line in text file using batch command

I have a textfile which contains the following text.
"Module"
{
"ModuleSignature" = "8:MergeModule.6F1248514B3047E99E4EE8A129CB8605"
"Version" = "8:1.0.0.0"
"Title" = "8:uoipmsm"
"Subject" = "8:"
"Author" = "8:Microsoft"
"Keywords" = "8:"
"Comments" = "8:"
"SearchPath" = "8:"
"UseSystemSearchPath" = "11:TRUE"
"TargetPlatform" = "3:1"
"PreBuildEvent" = "8:"
"PostBuildEvent" = "8:"
"RunPostBuildEvent" = "3:0"
}
In the above; I want to change the Version number which I will give when I trigger a build from a tool.
I wanna pass a parameter $Version in batch file, it has to take the version number from the tool I use and update the same in that text file.
For ex: in the above text i wanna code it as "Version" = "8:$Version" hence when ever I provide a version number while triggering a build, it has to update the same in this text file.
Could you please guide me how to edit the specific line. I am new to windows batch scripting.
and i hav to add one more point... in the text file i have to modify the version in the line number 399. So the batch file has to jump to line num 399 in that text file and modify the same. Kindly help me to fix the same ...
I had saved the above script in a text pad and saved the same as ver.bat; and also in the same folder I saved the Intext file. When I mention the line number which to be replaced, it is removing the contents which are present after "=" symbol, from line 1 to 399 .
Before running the batch file:
"ModuleSignature" = "8:MergeModule.6F1248514B3047E99E4EE8A129CB8605"
"Version" = "8:1.0.0.0"
"Title" = "8:uoipmsm"
"Subject" = "8:"
"Author" = "8:Microsoft"
"Keywords" = "8:"
"Comments" = "8:"
"SearchPath" = "8:"
"UseSystemSearchPath" = "11:TRUE"
"TargetPlatform" = "3:1"
"PreBuildEvent" = "8:"
"PostBuildEvent" = "8:"
"RunPostBuildEvent" = "3:0"
I mentioned the line number as 10 and after tat if I run the batch file; i get the following output;
"ModuleSignature" =
"Version" = ""
"Title" =
"Subject" =
"Author" =
"Keywords" =
"Comments" =
"SearchPath" =
"UseSystemSearchPath" =
"TargetPlatform" =
"PreBuildEvent" =
"PostBuildEvent" =
"RunPostBuildEvent" =
Any idea??
This should do it. Of course this will have to change if your input file ever changes. You may also have to make an adjustment if there are blank lines in your input file (they don't count). Note that you only need to pass the version (not the entire new line 399). In your example that would be "8:1.0.0.0". Best to quote the string in case there are ever spaces in there.
By way of explanation, this will:
This bat file must be called with an argument
Use a FOR LOOP to echo the first 398 lines to a temp file
Add a new line 399 using the version passed as an argument
Use MORE to append the remaining lines to the temp file
Copy the temp file to the original file
Delete the temp file
x
#echo off
REM %1=Version (use quotes if there are spaces in version)
set ReplaceLine=399
set InFile=Test.txt
set TempFile=TempTest.txt
if exist "%TempFile%" del "%TempFile%"
if "%~1"=="" (
color CF
echo.This program must be called with an argument!
pause
goto :eof
)
setlocal enabledelayedexpansion
set /A Cnt=1
for /F "tokens" %%a in (%InFile%) do (
echo.%%a>> "%TempFile%"
set /A Cnt+=1
if !Cnt! GEQ %ReplaceLine% GOTO :ExitLoop
)
:ExitLoop
endlocal
echo."Version" = "%~1">> "%TempFile%"
more +%ReplaceLine% < "%InFile%">> "%TempFile%"
copy /y "%TempFile%" "%InFile%"
del "%TempFile%"
goto :eof

Resources