I trying to go from cmd script to vbscript in MS window xp
cmd code yes works
set home_=%~dp0
set part001=part001
set part002=part002
set part003=part003
set part004=part004
::get the dir in part001
for /f "delims=" %%A in ('dir /s/b/o:n/a:d ^"%home%%part001%\^"') do (
echo show have dir path
echo %%A
pause
)
echo to the end
pause
goto :eof
to vbscript
the part I do not know to convert are those that are foramtted as cmd{cmd codeing}
dim strHome as strimg =cmd{[%~dp0]}
dim strPart001 as sting = part001
dim strPart002 as sting = part002
dim strPart003 as sting = part003
dim strPart004 as sting = part004
'get the dir in part001
Dim objFSo, objFile
Set objFSo = CreateObject("Scripting.FileSystemObject")
set objDirPart001list = objFS.getfolder(strHome&strPart001\)
set subDirPart001list = objDirPart001list.SubFolders
for each subDirPart001Name in subDirPart001list
WScript.Echo show dir path
WScript.Echo part
cmd{pause}
)
cmd{pause}
what are the corresponding vbscript commands for:
%~dp0
pause
The %~dp0 is a so-called magic command but more technically this method is known as variable substition. The %n variables are used to reference the command line parameters of the script. The most common, %0 will return the full path to the script that is executing. The d and p are special modifiers that will return the drive and path portion of that path, respectively. There is also n which returns the filename portion as well as others. These modifiers can be combined as necessary. So the %~dp0 command will return the full drive and path to the directory where the executing script resides. To do this in VBScript, you can use any of the following that rely on the WScript Object's ScriptFullName method:
Set objShell = CreateObject("WScript.Shell")
Set objFso = CreateObject("Scripting.FileSystemObject")
strPath = objFso.GetParentFolderName(WScript.ScriptFullName)
Or
strPath = Left(WScript.ScriptFullName, Len(WScript.ScriptFullName) - Len(WScript.ScriptName))
Or my favorite:
Replace(WScript.ScriptFullName, WScript.ScriptName, "")
The pause command is used to stop the command interpreter and prompt the user to press any key to continue. This is typically done so that the user has time to read the information in the command window before it closes. Here's a subroutine to do that in CScript. (For WScript, you would just use a simple MessageBox.)
Sub Pause
WScript.StdOut.Write "Press any key to continue . . . "
WScript.StdIn.Read(1)
End Sub
Related
the script is executed from the network and is supposed to bring in a config file located in the local machines C: drive with a path for mapping.
I've tried a few different ideas but every time I get "System error 67 has occurred. The network name cannot be found." Any help is appreciated as I can't resolve the issue. (I'm a newbie to command line)
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "cmd /k cd.. & cd CIEB_Group3 & set /p RootServer=<Server.txt & net use K: %RootServer% /pers:yes", 1, True
Instead of creating a VBS file that calls a single long command, it would be possible to do this using more VBScript, allowing further development at a later date if you so wished.
The below script makes the assumption that your "CIEB_Group3" stays in the same place (one cd .. up, then one cd down again) and that the text file remains as "server.txt" and only contains one entry.
Set WshShell = CreateObject("WScript.Shell")
'strpath = script execution directory
strPath = WshShell.CurrentDirectory
strPathReverse = StrReverse(strpath)
'create the parent folder filepath, equivalent to cd..
strParentFilePath = Left(strPath, Len(StrPath) - InStr(strPathReverse,"\"))
'open the text file, making the assumption it is in CIEB_Group3 and is called server.txt
Set objfso = CreateObject("Scripting.FileSystemObject")
Set textfile = objfso.OpenTextFile (strParentFilePath & "\CIEB_Group3\Server.txt", 1)
'read the text file first line into a variable
strNetworkShare = textfile.ReadLine
'map the drive, chr(32) = <space>, chr(34) = "
WshShell.Run "net use K:" & Chr(32) & Chr(34) & strNetworkShare & Chr(34) & Chr(32) & "/pers:yes", 1, 1
Alternatively, if you still would like to use the single CMD line - you may wish to try expanding the environment variable outside the CMD command, as per below.
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "cmd /k cd.. & cd CIEB_Group3 & set /p RootServer=<Server.txt & net use K: " & wshShell.ExpandEnvironmentStrings("%RootServer%") & " /pers:yes", 1, True
I am new to batch scripting and vbscript. What I want to do is convert .xlsx Excel files into .csv Excel files, in multiple directories (Recursively). For example:
Main directory
subdirectory1
file1.xlsx
file2.xlsx
subdirectory2
file3.xlsx
file4.xlsx
I have made this batch script:
FOR /r %%a in (*.xlsx) do (
SET filename=%%a
ExceltoCSV.vbs %filename% *.csv
)
Inside the for loop is the ExceltoCSV.vbs. I got this code from this thread Convert XLS to CSV on command line, and I have tried the top 2 answers already (Both don't require downloading anything).
if WScript.Arguments.Count < 2 Then
WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv"
Wscript.Quit
End If
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
oBook.SaveAs WScript.Arguments.Item(1), 6
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
The error is saying that the ExceltoCSV.vbs file cannot be accessed. However, I believe the batch script is working, for example it would say:
SET filename=C:\folder\subfolder\test1.xlsx
then it calls:
ExceltoCSV.vbs C:\folder\subfolder\test1.xlsx *.csv
I am not sure what the problem is and I am currently very confused.
The VBS needs to be in the same directory as the BAT file.
The issue is that variable expansion rules in a FOR loop mean that filename wont be set to the current file variables value; just use %%a instead:
FOR /r %%a in (*.xlsx) do (
ExceltoCSV.vbs "%%a" "%%~dpna.csv"
)
You are passing the string "*.CSV" to the script which wont work, %%~dpna.csv takes the file name in %%a and changes the extension to .CSV.
The quotes are there to allow for spaces in paths.
You're using VBScript to convert. Why not just use it to iterate your folders as well? Then you don't have to worry about calling a VBS from a BAT and passing the proper args.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set oExcel = CreateObject("Excel.Application")
DoFolder "c:\mainfolder"
oExcel.Quit
Sub DoFolder(strFolder)
' Recursively process each subfolder...
For Each objSubFolder In objFSO.GetFolder(strFolder).SubFolders
DoFolder objSubFolder.Path
Next
' Convert any XLSX files...
For Each objFile In objFSO.GetFolder(strFolder).Files
If StrComp(objFSO.GetExtensionName(objFile.Name), "xlsx", vbTextCompare) = 0 Then
strNewName = Left(objFile.Path, Len(objFile.Path) - 4) & "csv"
' Convert...
Set oBook = oExcel.Workbooks.Open(objFile.Path)
oBook.SaveAs strNewName, 6
oBook.Close False
End If
Next
End Sub
I am trying to run the following command and return the output of it using VBscript:
dir /A-d "C:\Windows\Minidump" | find /c "/"
And I have the following script but it does not work (probably because of " charachters:
Wscript.Echo runCMD("dir /A-d "C:\Windows\Minidump" | find /c "/"")
Function runCMD(strRunCmd)
Set objShell = WScript.CreateObject("WScript.Shell")
Set objExec = objShell.Exec(strRunCmd)
strOut = ""
Do While Not objExec.StdOut.AtEndOfStream
strOut = strOut & objExec.StdOut.ReadLine()
Loop
Set objShell = Nothing
Set objExec = Nothing
runCMD = strOut
End Function
Any suggestions on how to achieve this?
dir is intrinsic; you need %comspec%.
Double quotes need to be escaped by double double quotes in VBScript:
Wscript.Echo runCMD("%comspec% /c dir /A-d ""C:\Windows\Minidump"" | find /c ""/""")
Currently I have a batch file that calls a VBScript and executes the script and exits from that script into the command prompt window that I called the batch file from. I am wanting to return to the batch file from the VBScript and loop back into the beginning of the batch file and ask for the information from the user again and then go back into the script and repeat. I would also like to query the user as to whether they would like to quit or repeat after the VBscript has been run.
Here is my batch file:
#echo off
C:
cd C:\Users\Jared\Documents\Research\jared
Set "File=basic.dat"
Del "%File%" 2>NUL & If exist "%File%" (
Echo [+] File failed to delete: "%File%" >> "Report.txt"
)
Set /P datafile=Please enter data file to be analyzed:
Set /P filename=Please enter name for canvas file:
mklink basic.dat %datafile%
cscript Root_VBS_Script_1.vbs %filename%
And here is my VBScript (Disregard the SendKeys method, I understand how unreliable it is and will modify this later to not use it):
Set wshShell = CreateObject("Wscript.Shell")
Set args = WScript.Arguments
arg1 = args.Item(0)
Dim filename
filename = ""&arg1&""
WshShell.AppActivate "Command Prompt"
WshShell.SendKeys "root -b"
WshShell.SendKeys "~"
WshShell.AppActivate "ROOT session"
WshShell.SendKeys ".x analysis.C"
WshShell.SendKeys "~"
WshShell.SendKeys ".x double_gaus.C"
WshShell.SendKeys "~"
WshShell.AppActivate "ROOT session"
WshShell.SendKeys "c1->SaveAs{(}"""&filename&"""{)}"
WshShell.SendKeys "~"
WshShell.SendKeys ".q"
WshShell.SendKeys "~"
WScript.Quit
I have tried various ways of using the IF ERRORLEVEL command and keeping in mind that it must be in descending order when checked, but nothing is working.
#echo off
C:
cd C:\Users\Jared\Documents\Research\jared
Set "File=basic.dat"
:loop
Del "%File%" 2>NUL & If exist "%File%" (
Echo [+] File failed to delete: "%File%" >> "Report.txt"
)
set "datafile="
Set /P datafile=Please enter data file to be analyzed:
if not defined datafile echo all done - exiting&goto :eof
set "filename="
Set /P filename=Please enter name for canvas file:
if not defined filename echo all done - exiting&goto :eof
mklink basic.dat %datafile%
cscript Root_VBS_Script_1.vbs %filename%
goto loop
This should get you going.
Can't see what errorlevels have to do with anything. You appear not to be setting the vbscript exit code (need WScript.Quit yourerrorlevel else it will exit with errorlevel 0, I am told)
If you clear the values before they are input, then you can take advantage of the set /p behaviour that the value will remain unchanged if you simply reply with Enter
You can also use this characteristic to establish a default value, if that suits.
OR you could define a specific exit codeword like quit or exit. Using this method, you'd code a line
if /i "%var%"=="exit" echo Bye-bye&goto :eof
where the quotes protect against an empty or space-containing entry by the user into var, the & is an inline statement-separator and :eof is a special label predefined and understood by cmd to mean end of file (the colon is required)
This has a loop and a method to exit from the loop.
#echo off
:loop
C:
cd C:\Users\Jared\Documents\Research\jared
Set "File=basic.dat"
Del "%File%" 2>NUL & If exist "%File%" (
Echo [+] File failed to delete: "%File%" >> "Report.txt"
)
"set datafaile="
Set /P datafile=Please enter data file to be analyzed or press Enter to Quit:
if not defined datafile goto :EOF
Set /P filename=Please enter name for canvas file:
mklink basic.dat %datafile%
cscript Root_VBS_Script_1.vbs %filename%
goto :loop
As #brianadams suggested, there's no need for a batch script here. You can do the entire prompting and looping in VBScript and shell out for external commands like mklink.
Set sh = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Function qq(str) : qq = Chr(34) & str & Chr(34) : End Function
sh.CurrentDirectory = "C:\Users\Jared\Documents\Research\jared"
basicfile = "basic.dat"
Do
If fso.FileExists(basicfile) Then
On Error Resume Next
fso.DeleteFile basicfile, True
If Err Then fso.OpenTextFile("Report.txt", 8, True).WriteLine _
"[+] File failed to delete: " & qq(basicfile)
On Error Goto 0
End If
datafile = InputBox("Please enter data file to be analyzed:")
filename = InputBox("Please enter name for canvas file:")
sh.Run "cmd /c mklink " & qq(basicfile) & " " & qq(datafile)
sh.AppActivate "Command Prompt"
sh.SendKeys "root -b"
'...
Loop
I have a batch file that calls a vbscript file. I am trying to have the vbscript file change an environment variable that is later used in the batch file that calls the vbscript file.
Here are snippetes from the files.
Parent.bat
Set Value="Initial Value"
cscript Child.vbs
ECHO Value = %VALUE%
Child.vbs
Set wshShell = CreateObject( "WScript.Shell" )
Set wshSystemEnv = wshShell.Environment( "Process" )
wshSystemEnv("VALUE") = "New Value"
You can't. A process can pass environment variables to child processes, but not to its parent - and in this case the parent is cmd.exe, which is running your Parent.bat file.
There are of course other ways to communicate information back to the parent batch file - outputting to stdout or a file is an obvious way, e.g.
== Child.vbs ===
WScript.echo "New Value"
== Parent.cmd ===
for /f "tokens=*" %%i in ('cscript //nologo child.vbs') do set Value=%%i
echo %Value%
yes, you can.... however, you'll have to resetvars in your session. see the following link:
Is there a command to refresh environment variables from the command prompt in Windows?
'RESETVARS.vbs
Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)
set oEnv=oShell.Environment("System")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
path = oEnv("PATH")
set oEnv=oShell.Environment("User")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
path = path & ";" & oEnv("PATH")
oFile.WriteLine("SET PATH=" & path)
oFile.Close
This is how I did it:
SET oShell = CREATEOBJECT("Wscript.Shell")
dim varSet
SET varSet = NOTHING
SET varSet = oShell.Environment("SYSTEM")
varSet("WinVer") = "6.0.2008"
Then in a separate VB script (resetvars.vbs) I called from CMD script:
cscript //nologo \\%APPSERVER%\apps\IE9.0\restartvars.vbs
call %TEMP%\resetvars.bat
I don't think you can do this. At least, you would need to mess with the environment block in the calling process, and there's no guarantee that it will respect this...
Ho about this:
#echo off
set vbsFile=%temp%\createguid.vbs
call :CreateVbs
call :GetGuid NewGuid
echo.%NewGuid%
del %vbsFile%>nul
GOTO:EOF
:CreateVbs
echo.set obj = CreateObject("Scriptlet.TypeLib")>%vbsFile%
echo.WScript.StdOut.WriteLine obj.GUID>>%vbsFile%
GOTO:EOF
:GetGuid
for /f "tokens=*" %%i in ('cscript //nologo %vbsFile%') do set %1=%%i
GOTO:EOF
It is not pure batch script but works ok.
#echo off&color 4a&title %~n0&AT>NUL
IF %ERRORLEVEL% EQU 0 (
goto 2
) ELSE (
echo.
)
if not "%minimized%"=="" goto 1
set minimized=true & start /min cmd /C "%~dpnx0"&cls&exit
:1
wmic process where name="cmd.exe" CALL setpriority "realtime">nul&echo set shell=CreateObject("Shell.Application") > %~n0.vbs&echo shell.ShellExecute "%~dpnx0",,"%CD%", "runas", 1 >> %~n0.vbs&echo set shell=nothing >> %~n0.vbs&start %~n0.vbs /realtime&timeout 1 /NOBREAK>nul& del /Q %~n0.vbs&cls&exit
:2
echo %~dpnx0 admin mode look up&wmic process where name="cmd.exe" CALL setpriority "realtime"&timeout 3 /NOBREAK>nul
:3
echo x=msgbox("end of line" ,48, "%~n0") > %~n0.vbs&start %~n0.vbs /realtime&timeout 1 /NOBREAK>nul& del /Q %~n0.vbs&cls&exit