Batch Script to run a computer test - batch-file

I am not really a programmer. I am a newbie.
Can you guys please help me with a windows batch file that will run a computer test?
Detect any hard drives then run a chkdisk on them
Detect any usb port
Detect any flash drive plug in the pc
Check the display pixels
I have started with this to detect the USB but somehow getting some errors
#echo off
setlocal EnableDelayedExpansion
set PNPDeviceID=4002FDCCE0E4D094
set Q='wmic diskdrive where "interfacetype='USB' and PNPDeviceID like '%%%PNPDeviceID%%%'" assoc /assocclass:Win32_DiskDriveToDiskPartition'
echo %Q%
for /f "tokens=2,3,4,5 delims=,= " %%a in (%Q%) do (
set hd=%%a %%b, %%c %%d
call :_LIST_LETTER !hd!)
goto :_END
:_LIST_LETTER
(echo %1 |find "Disk ") >nul|| goto :_EOF
for /f "tokens=3 delims==" %%a in ('WMIC Path Win32_LogicalDiskToPartition ^|find %1') do set TMP_letter=%%a
set Part_letter=%TMP_letter:~1,2%
echo %Part_letter% %1
goto :_EOF
:_END
:_EOF
:: *** end
pause

Here is a batch script that does almost everything you need.
Checkdisk will run against any local fixed drives. You can have it run in a new window (chkdskAsync=true) or have it run inside the program (chkdskAsync=false). Additionally, specify the chkdsk flags using the chkdskLaunchArguments= variable.
#ECHO OFF
CLS
SETLOCAL ENABLEDELAYEDEXPANSION
:: Use these lines to specify how CHKDSK and Notepad will run
:: ===============================================
SET chkdskLaunchArguments=/F /R
SET chkdskAsync=true
SET launchNotepad=true
:: ===============================================
COPY /Y NUL C:\Users\public\data.txt >nul 2>&1
ECHO Getting drive(s) information
FOR /F "tokens=*" %%A IN ('wmic logicaldisk get caption^, description^, providername^, volumename') DO (
ECHO.%%A>>C:\Users\public\data.txt
)
FOR /F "tokens=1,2 skip=1" %%A IN ('wmic logicaldisk get caption^, drivetype') DO (
IF %%B EQU 3 (
IF "!chkdskAsync!" EQU "true" (
START CMD /C CHKDSK %%A %chkdskLaunchArguments%
) ELSE (
CHKDSK %%A %chkdskLaunchArguments%
)
)
)
ECHO Getting resolution information
FOR /F "tokens=*" %%A IN ('wmic path Win32_VideoController get CurrentHorizontalResolution^,CurrentVerticalResolution') DO (
ECHO.%%A>>C:\Users\public\data.txt
)
ECHO Information gathered ... saved to C:\Users\public\data.txt
ECHO Showing results.
IF "!launchNotepad!" EQU "true" (
START /WAIT notepad.exe /A C:\Users\public\data.txt
)
ENDLOCAL
EXIT
When it is complete it saves everything to C:\Users\Public\data.txt. It will also launch the file in notepad (if launchNotepad=true is set to ... true).
The output looks like so:
Caption Description ProviderName VolumeName
A: Network Connection \\somefileserver.domain\ New Volume
C: Local Fixed Disk
E: Removable Disk someuser Drive
H: Network Connection \\somefileserver.domain\users$\someuser Data Share and User Home Dirs
P: Network Connection \\somefileserver.domain\Data Data Share and User Home Dirs
S: Network Connection \\somefileserver.domain\share
CurrentHorizontalResolution CurrentVerticalResolution
1920 1080
NOTE: Make sure to run this as an administrator. If you want chkdsk to run
Unfortunately, there isn't a way to grab all USB devices other than storage. Hope this helps!
I didn't realize this question is 4 years old. Going to leave my answer for posterity and anyone digging for answers.

I would recommend trying
chkdsk volume=C:\ D:\ E:\ F:\
to check the disks each as a separate volume

Related

Aquiring USB Drive Letters from command and use them as choice variables

I'm trying to create a batch file for backing up folders to a usb drive. In a certain point I want the batch to show a list of all avalaible USB Drives connected to the computer and then asking the user to select the drive letter of one of them to proceed.
As for the the list: I want to combine those two outputs in one line per usb drive
wmic logicaldisk where DriveType^=2 get deviceid
wmic diskdrive where mediatype^="removable media" get Caption, SerialNumber
As for the choice command: How can i use the drive letters as choices for the user to select from?
The following code should:
Determine your USB drive letter(s).
If there are none found notify you then close.
If only one is found, select it automatically.
If several are found, offer a selection choice.
#Echo Off
SetLocal EnableExtensions EnableDelayedExpansion
Set "USBDrv="
For /F Tokens^=2^ Delims^=^" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe
DiskDrive Where "InterfaceType='USB'" Assoc:List
/AssocClass:Win32_DiskDriveToDiskPartition 2^>NUL
^| %SystemRoot%\System32\findstr.exe "^__R"'
) Do For /F Tokens^=4^ Delims^=^" %%H In ('%SystemRoot%\System32\wbem\WMIC.exe
Path Win32_LogicalDiskToPartition ^| %SystemRoot%\System32\findstr.exe /C:"%%G"
2^>Nul') Do Set "USBDrv=!USBDrv!%%H"
If Not Defined USBDrv Echo No USB drive connected.&& GoTo :EndIt
If "%USBDrv:~2%" == "" (GoTo Selected) Else Echo Which USB drive %USBDrv::=: %?
For /F "Tokens=2 Delims=?" %%G In ('%SystemRoot%\System32\choice.exe
/C %USBDrv::=% 2^>NUL') Do Set "USBDrv=%%G:"
:Selected
Call :Task %USBDrv%
:EndIt
%SystemRoot%\System32\timeout.exe /T 5 1>NUL
GoTo :EOF
:Task
Rem Place your commands here [%1 will be the USB drive e.g. E:].
All you should need to do is to place your backup command(s) etc. at the bottom.

Batch Scripting Backing up files in USB

Iv got my code to show a list of USb devices connected to my laptop and i can select the USB as well but when i try to back up a folder into the USB what i get instead is a folder named f in the folder i was trying to save. This is the code i have for selectong a USB device
for /f "delims=" %%a in ('wmic logicaldisk where drivetype^=2 get deviceid ^| find ":"') do set "$List=!$List! %%a"
:USB
echo Avaiable Drive ==^> !$List!
set /p "$Drive=Enter the letter of the Backup drive : "
echo !$List! | find /i "%$Drive::=%:" && Echo drive OK || Echo drive do not exist && goto:USB
set backupcmd=robocopy
and this is the code that backup the folder
%backupcmd% "%cd%" "%$Drive%"
Give this one a go:
#echo off
setlocal enabledelayedexpansion
set num=0
for /f %%a in ('wmic logicaldisk where drivetype^=2 get drivetype^, deviceid ^| find ":"') do (
set /a num+=1
set cnt=!cnt!!num!
echo (!num!^) %%a
set "d!num!=%%a"
)
choice /c !cnt! /M "select a number to choose a drive: "
echo You've chosen drive !d%errorlevel%! you can do everything with it from here..
You will notice that I set delayedexpansion here because of the setting and using of variables inside of the parenthesised code block.
Choice is a good option here as it does not allow typing the wrong values.

Batch File Skipping over FOR LOOP

UPDATE
I removed the tokens=4 and it started outputting data. It is not skipping past the FOR LOOP. I was skipping too far ahead with the tokens. I am still a little confused as to why it works as a single batch and not from this batch but now at least I know what the issue was. Thank you to everyone that was looking into this for me.
I am writing a script to copy over data from one computer to another. The issue is that it is skipping over the FOR LOOP that I am calling from another FOR LOOP. If you are testing the script it requires two PC's and a mapped T: drive to somewhere on the second computer. I can write the script so it looks for an external drive if that is more helpful to someone.
FOR /F "tokens=4 skip=1" %%a in ('REG QUERY "%_regshell%" /v "%_regdesktop%"') DO (
SET _dt=%%a
echo robocopy "!_dt!" "!_NetworkDrive!\!_fndesktop!" !_params!
echo attrib -h -r "!_NetworkDrive!\!_fndesktop!"
)
If I write the FOR LOOP above in a batch by itself and just echo out %%a then it works without a problem. In this, I can see that it is indeed calling :_backup but it skips directly over the FOR Loop and I am not sure why. I have written scripts like this many times but never had any that just completely ignore the FOR Loop. Can anyone take a look and assist? Thank you.
#echo off
:: Set Variables
SET _driveID=T:
SET _params=/Z /E /COPY:DT /R:1 /W:0 /XD LocalService NetworkService temp "temporary internet files" winsxs Content.IE5 cache /XF ntuser.* *.tmp /XJ /FP /NC /NS /NP /NJH
SET _regshell=HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
SET _regdesktop=Desktop
:: Set Current Directory
pushd %SystemDrive%\
:: Start Menu - Create Choices and Options. Send to various places to perform the actions.
:_start
cls
ECHO Please type either option 2 or 3 and then press ENTER on the keyboard?
Echo 2. TRANSFER FILES FROM DESKTOP TO LAPTOP
Echo 3. EXIT THE PROGRAM
echo.
set /p choice=Enter Number:
if '%choice%'=='2' goto _desktopToLaptop
if '%choice%'=='3' goto :EOF
echo "%choice%" is not a valid option. Please try again
echo.
goto _start
:: Detect Drive Letters
:_desktopToLaptop
setlocal EnableDelayedExpansion
FOR /F "usebackq skip=1" %%a IN (`WMIC logicaldisk where DeviceID^="%_driveID%" get caption`) DO (
SET _NetworkDrive=%%a
if exist %%a (
CALL :_backup
goto :EOF
) else (
echo.
echo The laptop does not appear to be attached to the computer.
echo.
pause
goto :EOF
)
)
:_backup
:: Detect the folder locations and begin to backup each location to the laptop.
FOR /F "tokens=4 skip=1" %%a in ('REG QUERY "%_regshell%" /v "%_regdesktop%"') DO (
SET _dt=%%a
echo robocopy "!_dt!" "!_NetworkDrive!\!_fndesktop!" !_params!
echo attrib -h -r "!_NetworkDrive!\!_fndesktop!"
)
echo we are past the for loop
pause
:: Return to directory program was run from
popd
If anyone else runs into this issue or something similar, check your tokens and your skip. Mine worked just fine as a single batch but when I included as a call I had to change the options from tokens=4 skip=1 to tokens=3* skip=2 in order to get the correct output.
The correct tokens in that FOR LOOPS should be:
#echo off
:: Set Variables
SET _driveID=T:
SET _params=/Z /E /COPY:DT /R:1 /W:0 /XD LocalService NetworkService temp "temporary internet files" winsxs Content.IE5 cache /XF ntuser.* *.tmp /XJ /FP /NC /NS /NP /NJH
SET _regshell=HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
SET _regdesktop=Desktop
:: Set Current Directory
pushd %SystemDrive%\
:: Start Menu - Create Choices and Options. Send to various places to perform the actions.
:_start
cls
ECHO Please type either option 2 or 3 and then press ENTER on the keyboard?
Echo 2. TRANSFER FILES FROM DESKTOP TO LAPTOP
Echo 3. EXIT THE PROGRAM
echo.
set /p choice=Enter Number:
if '%choice%'=='2' goto _desktopToLaptop
if '%choice%'=='3' goto :EOF
echo "%choice%" is not a valid option. Please try again
echo.
goto _start
:: Detect Drive Letters
:_desktopToLaptop
setlocal EnableDelayedExpansion
FOR /F "usebackq skip=1" %%a IN (`WMIC logicaldisk where DeviceID^="%_driveID%" get caption`) DO (
SET _NetworkDrive=%%a
if exist %%a (
CALL :_backup
goto :EOF
) else (
echo.
echo The laptop does not appear to be attached to the computer.
echo.
pause
goto :EOF
)
)
:_backup
:: Detect the folder locations and begin to backup each location to the laptop.
FOR /F "tokens=3* skip=2" %%a in ('REG QUERY "%_regshell%" /v "%_regdesktop%"') DO (
SET _dt=%%a
echo robocopy "!_dt!" "!_NetworkDrive!\!_fndesktop!" !_params!
echo attrib -h -r "!_NetworkDrive!\!_fndesktop!"
)
echo we are past the for loop
pause
:: Return to directory program was run from
popd
Given that the main issue in your script appears to be the setting of a variable to the data within the defined registry key and value, you could use:
Set "_regshell=HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
Set "_regdesktop=Desktop"
Set "_dt="
For /F "EOL=H Tokens=2*" %%A In ('Reg Query "%_regshell%" /V "%_regdesktop%"'
) Do Set "_dt=%%~B"
If Not Defined _dt GoTo :EOF
Echo "%_dt%"

find specific folder in any mapped drive and report its full UNC path

I was wondering if it was possible using a batch file to find a specific folder in any mapped drive of a PC and have it report the folders full UNC path. Lets say a PC has drives mapped of N:\ & S:\ (or any usual network drive letter for that matter). The folder could be in either folder and I run some code to find where the folder is, it will be in the root of the drive share (avoiding need for recursive subfolder scanning) e.g. N:\Special_Folder however, the end result of the code will report the FULL UNC e.g.
Folder Found!..
\server-vm01\data\shared_area\special_folder
Hope that makes sense. I have tried with some code I already use to identify a USB stick, but am having difficulty porting it to the needs above. Any pointers would be great, thank you.
for %%a in (d: e: f: g: h: i: j: k: l: m: n: o: p: q: r: s: t: u: v: w: x: y: z:) do | find "special_folder" >nul && set unc=%%a:
echo %unc%
pause
edit for troubleshoot, output net use
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.
C:\Users\Admin>net use
New connections will be remembered.
Status Local Remote Network
-------------------------------------------------------------------------------
OK Y: \\DISKSTATION\NetBackup Microsoft Windows Network
OK Z: \\DISKSTATION\NetBackup Microsoft Windows Network
The command completed successfully.
C:\Users\Admin>
I tried to fix and I got as far as trying FOR /F "tokens=2-3 delims= " in the first line and that removes the Microsoft Windows Networ but then drops a letter out the path e.g \DISKSTATION\NetBacku\specialfolder
also If I run as admin, as will need to, the code doesn't echo any path, does non admin ? Thanks
EDIT (final)
Thank you both for these really helpful codes. I shall edit the original question with what works, both do as it happens, but I can only tick one solution by the looks of it.
Test Environment:-
Win10 (UAC is ON)
Win7 (UAC is off)
Two Mapped Drives in each with a test Folder called Daphne in root of just one of the 2 drives.
#echo off
FOR /F "skip=2 delims=" %%G IN ('"wmic logicaldisk where drivetype=4 get name,providername /format:csv"') do (
FOR /F "tokens=2,3 delims=," %%H IN ("%%G") DO (
IF EXIST "%%I\Daphne\" echo %%I\Daphne
)
)
pause
The above works perfectly on the Win7 (UAC is off) test system, Admin or not. Works as non Admin Win10 (UAC is ON), doesn't work running as "Admin" though.
Below worked everywhere regardless of admin or not, in both environments.
The original code suggested works fine (FYI) but I just needed it to output the path with no quotations or additional texts, so I am just adding the authors generous efforts (tweaked slightly) to conclude the original question in line with my original intentions.
#ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
set "_FolderToSearch=Daphne"
for /F "delims=" %%D in ('reg query "HKCU\Network"') do (
for /F "tokens=1,2,*" %%f in ('reg query "%%~D" /v RemotePath ^| find /I "RemotePath"') do (
if exist "%%~h\%_FolderToSearch%\" echo %%~h\%_FolderToSearch%
)
)
pause
Below is the output on the screen from both code snippets in their working forms:-
\\DISKSTATION\NetBackup\Daphne
Press any key to continue . . .
\\DISKSTATION\NetBackup\Daphne
Press any key to continue . . .
I can now easily set this as a path statement in a config file to completely automate client software installations by having the customer just tell me the folder name of where they want our data on their network. I shall test first and report back.
Thankyou!
Mapped drives are not available from an elevated prompt when UAC is configured to "Prompt for credentials" in Windows.
Next code snippet should work even from an elevated command prompt:
#ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
set "_FolderToSearch=models" folder name to be searched for
echo no recursion: folder in the root of the drive share:
for /F "delims=" %%D in ('reg query "HKCU\Network"') do (
for /F "tokens=1,2,*" %%f in ('reg query "%%~D" /v RemotePath ^| find /I "RemotePath"') do (
if exist "%%~h\%_FolderToSearch%\" echo # FOUND [%%~nD:] "%%~h\%_FolderToSearch%"
)
)
echo recursive search:
for /F "delims=" %%D in ('reg query "HKCU\Network"') do (
for /F "tokens=1,2,*" %%f in ('reg query "%%~D" /v RemotePath ^| find /I "RemotePath"') do (
for /F "delims=" %%# in ('dir /B /S /AD "%%~h\%_FolderToSearch%*" 2^>NUL') do (
if /I "%%~nx#"=="%_FolderToSearch%" echo # found [%%~nD:] "%%~#"
)
)
)
I was way over thinking the code. Using WMIC and a simple IF EXIST should work.
FOR /F "skip=2 delims=" %%G IN ('"wmic logicaldisk where drivetype=4 get name,providername /format:csv"') do (
FOR /F "tokens=2,3 delims=," %%H IN ("%%G") DO (
IF EXIST "%%I\SpecialFolder\" echo %%I\SpecialFolder
)
)
pause

Batch file - Switch USB from read/write to read-only and vice versa

I was wondering if you can write a Batch file to make a USB from read/write to read-only and visa versa?
What the program should do is, if you double click on the batch file it searches for the USB drive, check if it is read/write or just read-only then swaps it to the other setting.
EDIT
I know the name of the USB and also the drive letter.
EDIT
I need this for work where we use USB drives to install programs on peoples laptops, we used CD's before, but they get lost inside.
Code would be appreciated, but directions to sites will help as well.
Tested and works flawlessly with the 4 drives I have tested.
I have the below for you if you would like. It requires 3 files though. The batch then 1 text file per each Read only or Read Write command. Simple setup but requires you to have an input, it will overwrite what ever it currently is to what ever you select.
Thanks JBin for advising that it needs to be run as Administrator, I forgot that was a thing.
cls
#Echo OFF
#Echo Toggle between read only and Read write
:choice
set /P c=Change to [R]ead Only or Read/[W]rite?
if /I "%c%" EQU "R" goto :read
if /I "%c%" EQU "W" goto :write
:read
DISKPART /s Readonly.txt
cls
#Echo -----------------------
#Echo ^| Disk is now READ ONLY ^|
#Echo -----------------------
#Echo.
goto :choice
:write
DISKPART /s Readwrite.txt
cls
#Echo ------------------------
#Echo ^| Disk is now READ WRITE ^|
#Echo ------------------------
#Echo.
goto :choice
Make two text files with the below in them. Name them what ever you like but dont forget to change the *.txt in the batch. This is also assuming you only have 1 usb device plugged into the computer
Readonly.txt file:
Sel disk 1
att dis set readonly
exit
Readwrite.txt file:
sel disk 1
att dis clear readonly
exit
It is possible to do this is Batch (via Diskpart command), but it will be VERY convoluted.
Anyways, this code detects removable drives (so floppies, I think, are included), creates a menu, then swaps the setting (read-only/read-write). It makes flash drives "write-protected", but I tested my code...
#echo off
setlocal enabledelayedexpansion
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::Detect removable drives using DiskPart...
set "diskcnt=0"
for /f "tokens=1-2 delims= " %%A in (
'^(echo list disk^)^|diskpart^|findstr /ic:"Online"'
) do (
for /f "tokens=1-3 delims= " %%X in (
'^(echo select disk %%B^&echo detail disk^)^|diskpart^|findstr /ic:"Removable"'
) do (
set /a diskcnt+=1
set "vol!diskcnt!=%%B_%%Z:"
)
)
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::After detecting drives, print a menu...
echo.The script detected %diskcnt% removable drive/s:
echo.
if %diskcnt% equ 0 echo No drives found.
for /l %%X in (1,1,%diskcnt%) do (
echo. %%X. Drive !vol%%X:~2,2!
)
echo.
:choice_loop
set /p "choice=Choose a Number: "
if !choice! geq 1 if !choice! leq %diskcnt% goto :doIt
goto choice_loop
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::Get and set the setting...
:doIt
echo.
set "disknum=!vol%choice%:~0,1!"
for /f "tokens=1-2 delims=:" %%F in (
'^(echo select disk %disknum%^&echo attribute disk^)^|diskpart^|findstr /bic:"Read-Only"'
) do (
set "ro_state=%%G"&set "ro_state=!ro_state: =!"
)
if /i "%ro_state%" equ "No" (
(echo select disk %disknum%&echo attribute disk set readonly)|diskpart >nul
echo Drive !vol%choice%:~2,2! is now read-only from being read/write.
) else (
(echo select disk %disknum%&echo attribute disk clear readonly)|diskpart >nul
echo Drive !vol%choice%:~2,2! is now read/write from being read-only.
)
endlocal
pause
EDIT: My only concern here is that this is language dependent, so this will not work if the language is not English.
EDIT #2: Forgive me from misunderstanding the problem. If you already have a USB name to be modified, then try this: (Make sure there are no 2 flash drives with the same name that are plugged in at the same time.)
#echo off
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::Put the name of flash drive here... (Case-sensitive)
set "name=[PUT NAME HERE]"
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::Detect that removable drive using DiskPart...
set "disk_num="
for /f "tokens=1-2 delims= " %%A in (
'^(echo list disk^)^|diskpart^|findstr /ic:"Online"'
) do (
for /f "tokens=1-4 delims= " %%W in (
'^(echo select disk %%B^&echo detail disk^)^|diskpart^|findstr /ic:"Removable"'
) do (
if "%%Z"=="%name%" set "disk_num=%%B"
)
)
if not defined disk_num (
echo Flash drive '%name%' not found.
goto end_this
)
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::Get and set the setting...
for /f "tokens=1-2 delims=: " %%F in (
'^(echo select disk %disk_num%^&echo attribute disk^)^|diskpart^|findstr /bic:"Read-Only"'
) do (
set "ro_state=%%G"
)
if /i "%ro_state%" equ "No" (
(echo select disk %disk_num%&echo attribute disk set readonly)|diskpart >nul
echo Flash drive '%name%' is now read-only from being read/write.
) else (
(echo select disk %disk_num%&echo attribute disk clear readonly)|diskpart >nul
echo Flash drive '%name%' is now read/write from being read-only.
)
:end_this
pause
exit /b
EDIT #3: For Windows 8 and up, Run the Batch Files as Administrator for this to work.

Resources