Windows Script to create folder in explorer using user prompted input - windows

Thanks in advance for any help...I've done some coding in the past in C, matlab, Java, VHDL, Verilog, however I'm unfamiliar with batch files and how they are structured.
I'm trying to write a batch file in windows using notepad to create a new job folder in windows explorer with a name given by user prompted input and then create a new hierarchy of folders in this new folder. As of now I can right click anywhere in windows explorer and execute my script to create a hierarchy of folders however I've be unsuccessful in trying to get user input. I can get the command prompt to come up and ask the user to "Enter Job Name:" but cannot seem to discover the correct way to use this input to create the folder. I would prefer it to be a windows pane but command line is fine if it's too involved to use a windows pane. Lastly I would like to be able to give the user a choice of what type of job they wish to create and then create a different hierarchy of folders based on their selection however I haven't gotten this far yet. Here is what I have so far, I have commented out some things I've tried:
#strfolder = InputBox("Please enter a name for your new folder:")
#set objFSO = CreateObject("Scripting.FileSystemObject")
#objFSO.CreateFolder "Z:\" & strfolder
#set mydir = %cd%
#cd %mydir%
set /p jobName = Enter Job Name:
ECHO %jobName% /b
md %jobName%
#cd /d \%jobName%
cd %cd%\%jobName%
#set objFSO = CreateObject("Scripting.FileSystemObject")
#objFSO.CreateFolder "C:\Users\jarcher\Downloads\ins\test" & strfolder
md 1.Development
md 1.Development\1.Budgets
md 1.Development\2.Manufacturers
md "2.Plans and Specs"
md "2.Plans and Specs"\1.Plans
md "2.Plans and Specs"\2.Specs
md 3.Pricing
md 3.Pricing\1.Quotes
md 3.Pricing\2.Worksheets
md 4.Sumbittals
md 4.Sumbittals\"1.Submittal Reviews"
md 5.Orders
md 5.Orders\"1.Order Summaries"
md 5.Orders\"2.Confirmation Pages"
md 6.Closeout
md 6.Closeout\"1.O&M Manuals"
md 6.Closeout\2.Warranty

Remove the spaces around the =:
set /p jobName=Enter Job Name:
Otherwise a space is part of the name of the variable!

Related

How to use CMD to backup files to .zip for archive?

So this one's a multi-parter (Windows 7).
I have a folder structure as so:
C:
SyncFolder
Backups
[User]
FolderA
Subfolder1
Subfolder2
FolderB
Subfolder3
My aim is to use the folder 'SyncFolder' as a backup system for certain files (Sync folder is actually a folder placed there by a file syncing service).
At present, I have the following within the Sync folder:
a .bat file containing a ROBOCOPY command (which copies 1 file)
a .vbs file which is used to call the .bat file (to avoid the CMD window appearing). This VBS file is being called once per hour by Windows Task Scheduler
the file which is being copied
So here are my questions:
I'm looking for a code (preferably an edit to the existing .bat, as I'm not overly-technical) which can:
Copy Subfolder1 in its entirety into a .zip file, which is named YYYYMMDDHHMM_SubFolder1_Backup (where the date & time is automatically populated)
Move the newly-created .zip file to SyncFolder\Backups (or create it there in the first place?)
Deletes (or overwrites?) the previous backup
Repeats for each Subfolder specified (perhaps as an additional command line?) -- I'm not expecting the commands to identify the folders. I would specify the folders myself
Logs the details of the backup to a .log file located in SyncFolder (i.e. Name of .zip created, Date&Time of backup, size of .zip created)
I'm aware this might be a bit ambitious for CMD or a .bat, but I'm open to any suggestions, but please do bear in mind that I'm not highly technical, so any walk-throughs would be immensely appreciated!
Edit:
Here is my attempt with the .bat code:
#echo off
robocopy "C:\[USER]\[FolderA]\[SubFolder1]" "C:[SyncFolder]\Backups\BackupTest1.zip" *.* /dcopy:T /r:5 /w:5 /log+:"C:\[SyncFolder]\CopyLog.log" /bytes /ts /np
... I've tried this, without luck. This command works, but only creates a folder named BackupTest1.zip (which isn't actually a .zip).
Create a file using notepad, let's save it as ZipCMD.vbs then add the following code.
Set objArgs = WScript.Arguments
Set FS = CreateObject("Scripting.FileSystemObject")
InputFolder = FS.GetAbsolutePathName(objArgs(0))
ZipFile = FS.GetAbsolutePathName(objArgs(1))
CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)
Set objShell = CreateObject("Shell.Application")
Set source = objShell.NameSpace(InputFolder).Items
objShell.NameSpace(ZipFile).CopyHere(source)
wScript.Sleep 3000
Now you can run from cmdline
ZipCMD.vbs "C:\Frank\Folder A\Sub Folder 1" "C:\SyncFolder\Backups\BackupTest1.zip"
if you want to manually zip anything from cmd line.
If you want to schedule it, you can either just add the VBS file, or write a mybackup.cmd file and put the full string below in it and schedule that instead.
mybackup.cmd
ZipCMD.vbs "C:\Frank\Folder A\Sub Folder 1" "C:\SyncFolder\Backups\BackupTest1.zip"
Okay, so building on Gerhard's answer, I've got this:
In C:\SyncFolder, create ZipCMD.vbs using the following code in Notepad
Set objArgs = WScript.Arguments
Set FS = CreateObject("Scripting.FileSystemObject")
InputFolder = FS.GetAbsolutePathName(objArgs(0))
ZipFile = FS.GetAbsolutePathName(objArgs(1))
CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)
Set objShell = CreateObject("Shell.Application")
Set source = objShell.NameSpace(InputFolder).Items
objShell.NameSpace(ZipFile).CopyHere(source)
wScript.Sleep 3000
I've also created a Backups.bat in C:\Syncfolder using the following code in Notepad
#echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
set stamp=%YYYY%%MM%%DD%%HH%%Min%
rem parameters set for use later
Del "C:\SyncFolder\*_BackupTest1.zip"
rem This line removes the old backup first (Not ideal. Open to suggestions)
ZipCMD.vbs "C:\Users\[USER]\[FolderA]\[SubFolder1]" "C:\[SyncFolder]\BackupTest1.zip"
rem This line copies files and folders from the Source to the Destination into a named .zip, without a date.
copy "C:\[SyncFolder]\BackupTest1.zip" "C:\[SyncFolder]\%stamp%_BackupTest1.zip"
rem This line creates a copy of the un-dated file, but appends a Date and Time from the parameters defined at the start of the file.
Del "C:\[SyncFolder]\BackupTest1.zip"
rem This line deletes the un-dated file, leaving only the current, dated backup.
Set File="*_BackupTest1.zip"
FOR /F "usebackq" %%A IN ('%file%') DO set size=%%~zA
rem These lines define a new parameter defined by the .zip's size
Echo %stamp%_BackupTest1.zip %Size% >>BackupLog.log
rem This last line appends a line to a log file containing the name of the .zip created (which contains its' date) and its' size.
The second section of the above .bat (after defining initial parameters) can be repeated for multiple folders.
Lastly, I create a RunBackups.vbs in C:\SyncFolder using the following code in Notepad
Set WshShell = CreateObject("WScript.Shell" )
WshShell.Run chr(34) & "C:\[SyncFolder]\Backups.bat" & Chr(34), 0
Set WshShell = Nothing
This runs the .bat without having the black CMD window appear (i.e. running in 'silent' mode), and is the file I call upon using Task Scheduler to automate the backup process.
Unfortunately, there are still some issues with this:
In the ZipCMD.vbs file, the wScript.Sleep 3000 line causes issues on any .zip files which would take longer than 3 seconds to create. This could be extended, but having it hard-coded may prove troublesome. Open to suggestions as to how to get around this?
In the Backups.bat file, the old backup is deleted prior to the creation of the new backup. This is because I use *_TestBackup1.zip to identify the old backup, which, if used after the backup's creation, would delete both new and old backups. Perhaps moving the first Del command to immediately after the first ZipCMD.vbs command would help, as a backup would always exist?

shortcut (.LNK) is copied from local network to user pc without his icon

I wrote a batch file script in order to copy shortcut from the local network to the user desktop station. everything is working perfect except that the shortcut that is copied to the user desktop is without his icon. I have no experience writing batch files, i will be grateful if someone can advice me how to solve that issue.
that is the script:
#echo off
setlocal
set alias=Reg query "HKLM\Software\Microsoft\NET Framework Setup\NDP"
FOR /F "TOKENS=6 DELIMS=\." %%A IN ('%alias%') DO set .NetVer=%%A
if [%.NetVer] ==[] GOTO noDotNet
if EXIST C:\Users\%USERNAME%\Desktop\Partner_Projects_System.lnk GOTO ShortCutAllreadyExist
if not exist "\\netapp2\public\all\INTERNET PROJECTS\PMS_Shortcut_noWhite\Partner_Projects_System.lnk" GOTO noPermissionToDir
copy "\\netapp2\public\all\INTERNET PROJECTS\PMS_Shortcut_noWhite\Partner_Projects_System.lnk" "C:\Users\%USERNAME%\Desktop"
:loop
ping -n 1 -w 3000 1.1.1.1 > nul
IF EXIST C:\Users\%USERNAME%\Desktop\Partner_Projects_System.lnk (
GOTO startApp
) ELSE (
GOTO loop
)
EXIT
pause
:noDotNet
msg "%username%" DOTNET Framework is not installed on your machine please contact partner helpdesk team
EXIT
:noPermissionToDir
msg "%username%" you need to have read and write permission to the path \\netapp2\public\all\INTERNET PROJECTS\ please contact partner helpdesk team
EXIT
:ShortCutAllreadyExist
msg "%username%" the shortcut is allredy exist on the desktop
EXIT
:startApp
msg "%username%" SHORTCUT TO PROJECT MANAGMENT SOFTWARE WAS CREATED ON YOUR DESKTOP
start C:\Users\%USERNAME%\Desktop\Partner_Projects_System.lnk
A shortcut can specify a separate path to a icon that is different from the actual shortcut target. If this path is not valid on the new machine the icon might not display correctly.
You cannot manipulate shortcuts with a batch file but you can with Windows Scripting Host. Try this script to print the shortcut properties.

Run batch CODE in a vbscript file

I am trying to make a vbscript file that can run batch code (Note: Not a batch file, but batch code)
The code, which works in a batch file:
IF EXIST "%appdata%\Microsoft\Windows\Start Menu\Programs\MyManufacturer\MyClickOnceApp.appref-ms" (
"%appdata%\Microsoft\Windows\Start Menu\Programs\MyManufacturer\MyClickOnceApp.appref-ms"
) ELSE (start /b "" cmd /c del "%~f0"&exit /b)
I can make the vbscript code almost do what I want using:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\myscript.bat" & Chr(34), 0
Set WshShell = Nothing
Now I would like to combine these two pieces of code into one file, so something along the lines of:
Set WshShell = CreateObject("WScript.Shell" )
WshShell.Exec "IF EXIST ""%appdata%\Microsoft\Windows\Start Menu\Programs\MyManufacturer\MyClickOnceApp.appref-ms"" (""%appdata%\Microsoft\Windows\Start Menu\Programs\MyManufacturer\MyClickOnceApp.appref-ms"") ELSE (start /b """" cmd /c del ""%~f0""&exit /b)"
Set WshShell = Nothing
However when I run this code I get The system cannot find the file specified. This is expected, since Exec (or Run, or Execute) runs a batch file and not batch code. So, is there a command similar to Exec that will run batch code and not a batch file?
Some extra info that I don't think is necessary to a solution (But included for the sake of completedness):
This code is placed in the startup folder
The code is created in C# in order to run a ClickOnce application on startup
The reason I want to use vbscript is that the batch file opens a cmd window for a second, which is undesirable. My understanding is that the line Set WshShell = Nothing will make the command run invisibly
I have tried including >nul at the end of each line of the batch file, since I read that it will stop the output. This did not work for me.
It is theoretically possible for this to work by using both a .bat and a .vbs file, but this would require putting the .bat file in some other directory and feels generally hackish
I am open to other solutions besides vbscript, provided they can check if the .appref file exists, run the file if so, and delete itself if the file doesn't exist. This may be trivial in vbscript but I've never used vbscript before.
EDIT:
According to #Jason's comment, I have modified the code as follows. Now it runs with no output and without running my app (AKA it doesn't do $#!+)
Set WshShell = CreateObject("WScript.Shell" )
WshShell.Run "cmd.exe /C ""IF EXIST ""%appdata%\Microsoft\Windows\Start Menu\Programs\MyManufacturer\MyClickOnceApp.appref-ms"" (""%appdata%\Microsoft\Windows\Start Menu\Programs\MyManufacturer\MyClickOnceApp.appref-ms"") ELSE (start /b """" cmd /c del ""%~f0""&exit /b)", 0
Set WshShell = Nothing
The problem are the string in the path ! like this it work :
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /c if exist test1.txt (echo ok & del test1.txt & pause) else (echo ko & pause)"
Try to work with 8.3 format. To resolve the composed-name and don't use string.
But if you're programming in VBS why do you want to use batch code in it ?
If you want to use both make a .BAT file. Or generate it from you're VBS and call it.
Here is a example:
you have a batch called regex.bat :
#echo off &setlocal
for /f "tokens=1* delims=:" %%i in (
'netsh wlan show interfaces ^| findstr /rxc:"[ ]* SSID [ ]*: ..*"'
) do for /f "tokens=*" %%k in ("%%j") do set "SSID=%%k"
echo %SSID% > regex.txt
the vbs looks like this:
Set WshShell = WScript.CreateObject( "WScript.Shell" )
WshShell.Run "regex.bat",0,True
This works for me fine. No cmd-Windows comes up. Hope this helpes you

Desktop Refresh via dll

My personal concern for this problem is because of a dynamic desktop program i am creating which the aim is for users to click a folder on a desktop and the contents of that folder becomes the new desktop. (I will post the code as an answer below as so to not convolute my actual question). However part of the code needs to kill and restart the explorer.exe process in order to reinitialize the desktop to display the new location.
Documentation of this problem is extremely difficult to find as its more technical than most people are willing to go for this particular field. This man is trying to do the exact same thing as me except using autoit, and here users looked more into doing it vbscript side but both came to the same result of killing and restarting explorer.exe in order to update the desktop.
My issue with killing the explorer.exe process in a forceful manner can result in unstable systems and the actual killing of the process takes a longer time to reboot the desktop than whatever action occurs when you simply move the desktop location. I want to know how i can update my desktop, by calling the dlls that update it, but from within a batch and vbscript hybrid.
EDIT:
Investigations to a command such as rundll32.exe user32.dll,LockWorkStation, and later to the user32.dll dependencies has uncovered multiple uses of desktop functions, in which i assume is used to update the desktop in some form. If you would like to view this, download dependency walker and open it to this folder from within the program. (C:\Windows\WinSxS\amd64_microsoft-windows-user32_31bf3856ad364e35_6.3.9600.18123_none_be367a2e4123fd9d\user32.dll)
Here is the manual changing of the desktop via batch and vbs hybrid. Its not perfect, but it provides a nice interface between moving in and out of directories to select the one you want to update to. This uses the taskkill which i want to depreciate with something else.
This is the initial batch script...
#echo off
setlocal enableextensions
::Below computes the desktop location that the program will reference
for /f %%a in ('cscript //nologo C:\HighestPrivelege\DesktopTools\findDesktop.vbs') do set "fold=%%a"
echo %fold%
::this loop will allow users to input new locations for the desktop by
moving through a terminal. Wildcards and autotab completion is usable are
and lack of input results in continuation of script
:loop
echo ################## %fold%
dir %fold% /A:D /B
echo _________________________
set loc=
set /p loc=[New Location?]
cd %fold%\%loc%
set fold=%cd%
IF [%loc%]==[] (goto cont) ELSE (goto loop)
:cont
::Below is the program that runs the regedit rewrite of the desktop variable
for the current user. It passes the decided folder value from earlier as the
new desktop.
cscript //nologo C:\HighestPrivelege\DesktopTools\setdesktop.vbs %fold%
::This restarts explorer.exe in order to reboot the newly created desktop
location. I wish i didnt have to kill explorer.exe forcefully in the process
but so far its the only way to make this program work.
taskkill /F /IM explorer.exe
explorer.exe
endlocal
pause
exit
and the VBS script that follows...
Option Explicit
'variable invocation
Dim objShell, strDesktop, strModify, strDelete, fso, f, File, content, parthe, args, arg1
Set args = WScript.Arguments
set objShell = CreateObject("WScript.Shell")
set fso = CreateObject("Scripting.FileSystemObject")
'this will take in the new desktop location.
set file= fso.OpenTextFile("C:\HighestPrivelege\DesktopTemporary.txt")
content = file.ReadAll
arg1 = args.Item(0)
parthe = ""&arg1&""
'The actual rewrite of the registry file containing the script lies below.
strDesktop = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Desktop"
strModify = objShell.RegWrite(strDesktop,parthe,"REG_EXPAND_SZ")
Activating the batch script will prompt user for where they would like to relocate their desktop to, and pass that variable into the VBscript to be rewrited to the registry. Upon VBScript completion, windows explorer will restart itself in order to reinitialize the new desktop location.
Until i can get a working model of the one where all i have to do is click/interact with the folder to initialize the program, this manual one will have to do.

Why is the following multiple DOS commands in one line not working correctly? (Passing Values)

I am trying to create a text file via DOS commands. The commands asks one for the name of the file prior to creating it. I have looked here and here and elsewhere to get me started.
I would like the code to work in one line. So, I should be able to type the entire code in Windows Start > Run box.
This is what I have:
cmd /k #ECHO OFF & SET /P filename=What File name: & copy NUL %filename%.txt & :End
This however ignores the name of the file I gave when asked, and creates %filename%.txt.
I have tried changing the operator before the word copy to |, &&, and & but these don't even ask me for a file name and simply create %filename%.txt
Also, the cmd box stays open after the text file is created.
P.S. I know I can use /q before /k for echo off.
I look forward to your help.
This works here: delayed expansion is used in another cmd process
cmd /c #ECHO OFF & SET /P filename=What File name: & cmd /v /c copy NUL !filename!.txt & exit
The command line has no path defined for the directory and when using the RUN box it will probably be created in the c:\windows\system32 folder, except you will not have write access to that folder.

Resources