How to close all sub folders of one folder? - windows

For example I have this folder "C:\Series" and I have this script below which closes this folder when it is opened
#echo off
cd /d C:\ start C:\Windows\explorer.exe CD_Restored
rem Terminate process: taskkill /F /FI "WINDOWTITLE eq Music" /IM explorer.exe > nul
It works successfully, but when I open any folder inside it, this code surely doesn't work, and I need to close any opened folder inside it. I have over 15 subfolders inside it, so I can't make a script line for each of them, especially that I am always updating it.
So could any one tell me how to make a script which closes a folder and its subfolders?

Just give a try for this batch file that use a vbscript :
#echo off
Title Close Opened Folders
Set "MainFolderName=series"
Call :CloseAllOpenedFolders "%MainFolderName%"
Pause & Exit
::---------------------------------------------------------------------------------------
:CloseAllOpenedFolders <MainFolderName>
Set "VBSFILE=%Temp%\CloseAllOpenedFolders.vbs"
(
echo Dim MainFolder,shell,oWindows,W
echo MainFolder = "%~1"
echo Set shell = CreateObject("Shell.Application"^)
echo set oWindows = shell.windows
echo For Each W in oWindows
echo If InStr(LCase(W.document.folder.self.Path^),LCase(MainFolder^)^)^> 0 Then
echo wscript.echo W.document.folder.self.Path
echo W.Quit
echo End If
echo Next
)>"%VBSFILE%"
Cscript //NoLogo "%VBSFILE%"
Exit /B
::---------------------------------------------------------------------------------------
EDIT : Powershell Solution
$mainFolder= "c:\series"
$shell = New-Object -ComObject Shell.Application
$window = $shell.Windows() | ? { $_.LocationURL -like "$(([uri]$MainFolder).AbsoluteUri)*" }
$window.document.Folder.Self.Path
$window | % { $_.Quit() }

Related

Extract list of path in a file using batch script

Here is my text file:
==================================================
Folder : D:\T\New folder
==================================================
==================================================
Folder : D:\T\Z-Ai
==================================================
==================================================
Folder : D:\T\Z-BiN
==================================================
I need to extract the paths from this file, so I have something like this:
D:\T\New folder
D:\T\Z-Ai
D:\T\Z-BiN
It seems I should use findstr TargetWord TargetFile.txt command. and Also it seems I can use regex like this: findstr /r "^[a-z][a-z]$ ^[a-z][a-z][a-z]$"
But I do not know how to loop through found targets or get the list of output. any help is really appreciated.
Based on your comment, you want to use the result to perform an xcopy task, it seems you really want something like this. Note I used example.txt as input file, and DESTINATION where you should add your destination, including the relevant xcopy switches you require:
#echo off
for /f "tokens=2*" %%i in ('type example.txt ^| findstr /i ":\\"') do xcopy "%%~j\*" DESTINATION
Alternatively we can use the findstr directly on Folder
#echo off
for /f "tokens=2*" %%i in ('type example.txt ^| findstr /i "Folder"') do xcopy "%%~j\*" DESTINATION
You can do like this :
#echo off
Title Extract list of path in a file using batch script
set "TxtList=MyList.txt"
Set "OutPutData=Output.txt"
Call :Extract "%TxtList%" "%OutPutData%"
Start "" "%OutPutData%"
Exit
::*****************************************************
:Extract <InputData> <OutPutData>
(
echo Data = WScript.StdIn.ReadAll
echo Data = Extract(Data,"[\w]:(\\[0-9\sA-Za-z\-]*)+"^)
echo WScript.StdOut.WriteLine Data
echo '************************************************
echo Function Extract(Data,Pattern^)
echo Dim oRE,oMatches,Match,Line
echo set oRE = New RegExp
echo oRE.IgnoreCase = True
echo oRE.Global = True
echo oRE.Pattern = Pattern
echo set oMatches = oRE.Execute(Data^)
echo If not isEmpty(oMatches^) then
echo For Each Match in oMatches
echo Line = Line ^& Trim(Match.Value^) ^& vbcrlf
echo Next
echo Extract = Line
echo End if
echo End Function
echo '************************************************
)>"%tmp%\%~n0.vbs"
cscript /nologo "%tmp%\%~n0.vbs" < "%~1" > "%~2"
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
exit /b
::****************************************************
For Windows. you can use powershell.
select-string -Path c:\tmp\file.txt -Pattern '[A-Z]:(\\[0-9\ A-Za-z\-]*)+' -AllMatches | % { $_.Matches } | % { $_.Value }
In my opinion, For /F is all you need for the task. Although using Type may be useful in some situations, there's no need to use find.exe or findstr.exe for this task as you don't need to match a particular glob/pattern:
#For /F "EOL==Tokens=2*UseBackQ" %%A In ("TargetFile.txt")Do #"%__AppDir__%xcopy.exe" "%%B" "Destination\" /Options
Please note that it may be wise, if there's a chance that one or more of theses Folders do not exist, that you prepend using If Exist "%%B\". Importantly, if each of the lines containing the Folder paths, is space padded up to the end of its line, this solution will not work for you.

A windows batch script open a file chooser dialog or drag-and-drop file to it

I try to write a batch script that, when you drag and drop another file to it, it will do something. If you don't drop anything, just double click it, it will open a file selection dialog window.
For the first part, it's easy:
#echo off
bin\dosomething "%~1"
For the second part, I googled this thread: https://stackoverflow.com/a/15885133/1683264
It also works.
But, I can't combine these two to one. I've tried
if "%~1" == [] goto select
then add :select before the second part, it just don't work. Codes below:
#ECHO OFF
if "%~1" == [] goto select
bin\dosomething "%~1"
goto :EOF
:select
<# : chooser.bat
:: launches a File... Open sort of file chooser and outputs choice(s) to the console
:: https://stackoverflow.com/a/15885133/1683264
#echo off
setlocal
for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
echo You chose %%~I
bin\dosomething "%%~I"
)
goto :EOF
: end Batch portion / begin PowerShell hybrid chimera #>
Add-Type -AssemblyName System.Windows.Forms
$f = new-object Windows.Forms.OpenFileDialog
$f.InitialDirectory = pwd
$f.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
$f.ShowHelp = $true
$f.Multiselect = $true
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }
I tried If "%~1"=="", it jumped as purpose, but the dialog windows still don't appear, CMD directly output error lines as:
You chose + iex (${D:\Program Files (x86)\BBB\choose list file.bat} | out-strin ...
Solved
It's solved. Only "%~1" works right.
I paste code here:
<# : chooser.bat
:: drop file to execute, or open a file chooser dialog window to execute.
:: code mostly comes from https://stackoverflow.com/a/15885133/1683264
#ECHO OFF
if "%~1" == "" goto SELECT
bin\dosomething "%~1"
goto :EOF
:SELECT
setlocal
for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
echo You chose %%~I
bin\dosomething "%%~I"
)
goto :EOF
: end Batch portion / begin PowerShell hybrid chimera #>
Add-Type -AssemblyName System.Windows.Forms
$f = new-object Windows.Forms.OpenFileDialog
$f.InitialDirectory = pwd
$f.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
$f.ShowHelp = $true
$f.Multiselect = $true
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }
The trick with those Hybrid scripts is, to hide the batch code for the Powershell parser and to hide the Powershell code for the batch parser.
For Powershell, the part between <# and #> is a comment. Thanksfully <# : comment does no harm for the batch parser. So your batch code is supposed to be inside that Powershell comment.
On the other hand, the last batch command is goto :EOF, which means, all below ( the "end of comment"-line" for Powershell and the Powershell code itself ) will be ignored by the Batch parser.
So just move up your line <# : chooser.bat as very first line.

Access is denied when use del /f in windows 10 64bit

I'm going to delete 1.mp3 but it gives me the error "Access is denied".
More info about file's perms:
attrib 1.mp3
A C:\Users\Alipour\Desktop\1\1.mp3
I also used attrib -s -h 1.mp3
but still it can not be deleted by
del /f/s/q 1.mp3 > NUL
or
del /f/s/q 1.mp3
or
del /f 1.mp3
There are several methods to remove such a file:
1. Process Explorer if the file is in use:
You can use ProcessExplorer from Windows Sysinternals to identifiy which program locks the file. Download and start ProcessExplorer and go to Find|Find Handle or DLL... Ctrl+F and enter the name of the locked file: 1.mp3.
ProcessExplorer will show you the process that is responsible for the lock because of accessing the file. If you've got the proccess kill that one and delete the file.
Example with MS Word accessing a file called LockedFile.docx:
2. Safe mode boot:
Another possibility is to boot into safe mode. In pre Windows 8 era this was done by pressing F8 before Windows boots.
In Windows 8 and higher you can press Shift+F8 before Windows boots or more easily you can hold Shift and click Restart in the login screen or even in Windows. If this was too short, look here how to get into safe mode.
Once you're in the safe mode you can try again deleting that file.
3. Remove file on Windows boot via PendingFileRenameOperations:
With PendingFileRenameOperations you can rename and even delete a file on Windows boot procedure when nothing else can access and block that file.
PendingFileRenameOperations will be entered in the Windows registry and consists of pairs of file paths.
You can do it manually as described below or again with a Windows Sysinternals program called MoveFile. Download that program and use it in a console window (Start -> Run or Windows-Key+R, type cmd and press ENTER).
Type movefile foo.exe "" to delete a file on reboot.
Manual method via registry:
The 1st path is the file to be renamed.
The 2nd path is the new file path.
If the 2nd path is empty (0x0000) the file get's removed.
Start -> Run or Windows-Key+R
Type in regedit, and press ENTER
Goto HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager
Create a new Multi-String value: PendingFileRenameOperations
Enter \??\filepath as the data (e.g. \??\C:\Users\xyz\Desktop\foo.exe)
Press OK
Right-click on the key, click Modify Binary Data
At the end of the hex string, add 0000 (4 zeros which represent an empty string)
Press OK
Restart your computer
Lean and mean batch-file only alternatives for PendingFileRenameOperations:
~ Scripts will add an entry to right-click -- "SendTo" menu
~ Accepting a single parameter, either File or Folder
~ Confirmation prompt ([Cancel] to Clear previous entries)
~ Basic idiot proofing (don't process %Windir% for example)
Rename_On_Boot.bat
goto="Batch" /* Rename_On_Boot by AveYo v1
:RenOnBoot
set "input=%*" & call set "input=%%input:?=%%" &rem line below adds entry to right-click -- "SendTo" menu
if /i "_%~dp0"=="_%APPDATA%\Microsoft\Windows\SendTo\" (set .=) else copy /y "%~f0" "%APPDATA%\Microsoft\Windows\SendTo\" >nul 2>nul
if "_%1"=="_" color 4f & echo ERROR! No input provided & ping -n 6 localhost >nul & exit /b
for %%# in ("C:\" "C:\Boot" "C:\Recovery" "%WINDIR%" "%WINDIR%\system32" "%ProgramData%" "%ProgramFiles%" "%USERPROFILE%") do (
if /i "_%input%"=="_%%~#" color 4f & echo ERROR! %%# is not safe to delete & ping -n 6 localhost >nul & exit /b
)
color 0B & echo Please wait, folders might take a while .. & call cscript /nologo /e:JScript "%~f0" RenOnBoot "%input%" & exit /b
:RenOnBoot_Run_As_Admin
color 4f & echo Asking permission to run as Admin.. & call cscript /nologo /e:JScript "%~f0" RunAsAdmin "%~f1???" & exit /b
:"Batch"
#echo off & setlocal disabledelayedexpansion & mode 96,4 & echo. & title %~nx0 by AveYo & if not exist "%~f1" goto :RenOnBoot
reg query HKEY_USERS\S-1-5-20\Environment /v temp 1>nul 2>nul && goto :RenOnBoot || goto :RenOnBoot_Run_As_Admin
:"JScript" */
function RenOnBoot(f){
var HKLM=0x80000002, k='SYSTEM\\CurrentControlSet\\Control\\Session Manager', v='PendingFileRenameOperations';
var reg=GetObject('winmgmts:{impersonationLevel=impersonate}!//./root/default:StdRegProv'), ws=WSH.CreateObject('WScript.Shell');
var confirmation=ws.Popup(" Rename on next boot? [OK]\n Clear previous entries? [Cancel]\n\n "+f,0,'Rename_On_Boot by AveYo',33);
if (confirmation == 2) { reg.DeleteValue(HKLM, k, v); WSH.quit(); } // Clear existing entries on Cancel press and quit script
var mtd=reg.Methods_('GetMultiStringValue').InParameters.SpawnInstance_(); mtd.hDefKey=HKLM; mtd.sSubKeyName=k; mtd.sValueName=v;
var query=reg.ExecMethod_('GetMultiStringValue', mtd), regvalue=(!query.ReturnValue) ? query.SValue.toArray():[,], entries=[];
var fso=new ActiveXObject('Scripting.FileSystemObject'), fn=fso.GetAbsolutePathName(f);
entries.push('\\??\\'+fn,'\\??\\'+fn+'.ren');
reg.CreateKey(HKLM, k); reg.SetMultiStringValue(HKLM, k, v, entries.concat(regvalue));
}
if (WSH.Arguments.length>=2 && WSH.Arguments(0)=='RenOnBoot') RenOnBoot(WSH.Arguments(1));
function RunAsAdmin(self, arguments) { WSH.CreateObject('Shell.Application').ShellExecute(self, arguments, '', 'runas', 1) }
if (WSH.Arguments.length>=1 && WSH.Arguments(0)=='RunAsAdmin') RunAsAdmin(WSH.ScriptFullName, WSH.Arguments(1));
//
Delete_On_Boot.bat
goto="Batch" /* Delete_On_Boot by AveYo v1
:DelOnBoot
set "input=%*" & call set "input=%%input:?=%%" &rem line below adds entry to right-click -- "SendTo" menu
if /i "_%~dp0"=="_%APPDATA%\Microsoft\Windows\SendTo\" (set .=) else copy /y "%~f0" "%APPDATA%\Microsoft\Windows\SendTo\" >nul 2>nul
if "_%1"=="_" color 4f & echo ERROR! No input provided & ping -n 6 localhost >nul & exit /b
for %%# in ("C:\" "C:\Boot" "C:\Recovery" "%WINDIR%" "%WINDIR%\system32" "%ProgramData%" "%ProgramFiles%" "%USERPROFILE%") do (
if /i "_%input%"=="_%%~#" color 4f & echo ERROR! %%# is not safe to delete & ping -n 6 localhost >nul & exit /b
)
color 0B & echo Please wait, folders might take a while .. & call cscript /nologo /e:JScript "%~f0" DelOnBoot "%input%" & exit /b
:DelOnBoot_Run_As_Admin
color 4f & echo Asking permission to run as Admin.. & call cscript /nologo /e:JScript "%~f0" RunAsAdmin "%~f1???" & exit /b
:"Batch"
#echo off & setlocal disabledelayedexpansion & mode 96,4 & echo. & title %~nx0 by AveYo & if not exist "%~f1" goto :DelOnBoot
reg query HKEY_USERS\S-1-5-20\Environment /v temp 1>nul 2>nul && goto :DelOnBoot || goto :DelOnBoot_Run_As_Admin
:"JScript" */
function DelOnBoot(f){
ListDir=function(src, _root,_list) {
_root=_root || src, _list=_list || [];
var root=fso.GetFolder(src), files=new Enumerator(root.Files), dirs=new Enumerator(root.SubFolders);
while (!files.atEnd()) { _list.push(files.item()); files.moveNext(); }
while (!dirs.atEnd()) { _list=ListDir(dirs.item().path, _root,_list); _list.push(dirs.item()); dirs.moveNext(); }
return _list;
};
var HKLM=0x80000002, k='SYSTEM\\CurrentControlSet\\Control\\Session Manager', v='PendingFileRenameOperations';
var reg=GetObject('winmgmts:{impersonationLevel=impersonate}!//./root/default:StdRegProv'), ws=WSH.CreateObject('WScript.Shell');
var confirmation=ws.Popup(" Delete on next boot? [OK]\n Clear previous entries? [Cancel]\n\n "+f,0,'Delete_On_Boot by AveYo',33);
if (confirmation == 2) { reg.DeleteValue(HKLM, k, v); WSH.quit(); } // Clear existing entries on Cancel press and quit script
var mtd=reg.Methods_('GetMultiStringValue').InParameters.SpawnInstance_(); mtd.hDefKey=HKLM; mtd.sSubKeyName=k; mtd.sValueName=v;
var query=reg.ExecMethod_('GetMultiStringValue', mtd), regvalue=(!query.ReturnValue) ? query.SValue.toArray():[,], entries=[];
var fso=new ActiveXObject('Scripting.FileSystemObject'), fn=fso.GetAbsolutePathName(f);
if (fso.FolderExists(fn)) { var list=ListDir(fn); for (var i in list) entries.push('\\??\\'+list[i],''); }
entries.push('\\??\\'+fn,'');
reg.CreateKey(HKLM, k); reg.SetMultiStringValue(HKLM, k, v, entries.concat(regvalue));
}
if (WSH.Arguments.length>=2 && WSH.Arguments(0)=='DelOnBoot') DelOnBoot(WSH.Arguments(1));
function RunAsAdmin(self, arguments) { WSH.CreateObject('Shell.Application').ShellExecute(self, arguments, '', 'runas', 1) }
if (WSH.Arguments.length>=1 && WSH.Arguments(0)=='RunAsAdmin') RunAsAdmin(WSH.ScriptFullName, WSH.Arguments(1));
//
You can find out which program is locking a certain file with “Process Explorer → Find → Find handles or DLLs.”
For example, if the locker is explorer.exe, the Windows explorer, you can delete the file after killing Windows explorer in Task manager.
When del /f <FILE> producing an Access Denied error, you need to firstly take owner and grant access using takeown and icacls command line utilities, Please see an example: Delete a specific file on Windows.

How to End a VBScript Called from a Batch File and loop through the Batch File

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

Batch Command Line to Eject CD Tray?

I'm currently trying to move my CD's of backup to my Backup HDD.
To automate the task I'm trying to create a batch to copy the files with the label of the CD than eject the media.
The code looks like this so far:
#echo off
SET dest=F:\Backup\
d:
:: routine to retrieve volume label.
for /f "tokens=1-5*" %%1 in ('vol') do (
set vol=%%6 & goto done
)
:done
:: create destination folder
set dest=%dest%%vol%
mkdir "%dest%"
:: copy to destiny folder
xcopy "d:" "%dest%" /i /s /exclude:c:\excludes.txt
::eject CD
c:
I'm stuck at eject part. I'm trying to eject the CD because I want a clear line to draw my attention when the copy finished (I thought opening the tray to be a good one).
Any ideas how to do it using Batch? Or any other ways to "draw the attention" to the end of the copy event?
Thanks :)
if you have no installed media player or anti virus alarms check my other answer.
:sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%\System32\doskey.exe '.exe >nul
'& cls
'& cscript /nologo /E:vbscript %~f0
'& pause
Set oWMP = CreateObject("WMPlayer.OCX.7" )
Set colCDROMs = oWMP.cdromCollection
if colCDROMs.Count >= 1 then
For i = 0 to colCDROMs.Count - 1
colCDROMs.Item(i).Eject
Next ' cdrom
End If
This is a batch/vbscript hybrid (you need to save it as a batch) .I don't think is possible to do this with simple batch.On windows 8/8.1 might require download of windows media player (the most right column).Some anti-virus programs could warn you about this script.
I know this question is old, but I wanted to share this:
#echo off
echo Set oWMP = CreateObject("WMPlayer.OCX.7") >> %temp%\temp.vbs
echo Set colCDROMs = oWMP.cdromCollection >> %temp%\temp.vbs
echo For i = 0 to colCDROMs.Count-1 >> %temp%\temp.vbs
echo colCDROMs.Item(i).Eject >> %temp%\temp.vbs
echo next >> %temp%\temp.vbs
echo oWMP.close >> %temp%\temp.vbs
%temp%\temp.vbs
timeout /t 1
del %temp%\temp.vbs
just make sure you don't have a file called "temp.vbs" in your Temp folder. This can be executed directly through a cmd, you don't need a batch, but I don't know any command like "eject E:\". Remember that this will eject all CD trays in your system.
UPDATE:
A script that supports also ejection of a usb sticks - ejectjs.bat:
::to eject specific dive by letter
call ejectjs.bat G
::to eject all drives that can be ejected
call ejectjs.bat *
A much better way that does not require windows media player and is not recognized by anti-virus programs (yet) .Must be saves with .bat extension:
#cScript.EXE //noLogo "%~f0?.WSF" //job:info %~nx0 %*
#exit /b 0
<job id="info">
<script language="VBScript">
if WScript.Arguments.Count < 2 then
WScript.Echo "No drive letter passed"
WScript.Echo "Usage: "
WScript.Echo " " & WScript.Arguments.Item(0) & " {LETTER|*}"
WScript.Echo " * will eject all cd drives"
WScript.Quit 1
end if
driveletter = WScript.Arguments.Item(1):
driveletter = mid(driveletter,1,1):
Public Function ejectDrive (drvLtr)
Set objApp = CreateObject( "Shell.Application" ):
Set objF=objApp.NameSpace(&H11&):
'WScript.Echo(objF.Items().Count):
set MyComp = objF.Items():
for each item in objF.Items() :
iName = objF.GetDetailsOf (item,0):
iType = objF.GetDetailsOf (item,1):
iLabels = split (iName , "(" ) :
iLabel = iLabels(1):
if Ucase(drvLtr & ":)") = iLabel and iType = "CD Drive" then
set verbs=item.Verbs():
set verb=verbs.Item(verbs.Count-4):
verb.DoIt():
item.InvokeVerb replace(verb,"&","") :
ejectDrive = 1:
exit function:
end if
next
ejectDrive = 2:
End Function
Public Function ejectAll ()
Set objApp = CreateObject( "Shell.Application" ):
Set objF=objApp.NameSpace(&H11&):
'WScript.Echo(objF.Items().Count):
set MyComp = objF.Items():
for each item in objF.Items() :
iType = objF.GetDetailsOf (item,1):
if iType = "CD Drive" then
set verbs=item.Verbs():
set verb=verbs.Item(verbs.Count-4):
verb.DoIt():
item.InvokeVerb replace(verb,"&","") :
end if
next
End Function
if driveletter = "*" then
call ejectAll
WScript.Quit 0
end if
result = ejectDrive (driveletter):
if result = 2 then
WScript.Echo "no cd drive found with letter " & driveletter & ":"
WScript.Quit 2
end if
</script>
</job>
Requiring administrator's rights is too abusing :)
I am using wizmo:
https://www.grc.com/WIZMO/WIZMO.HTM

Resources