I've made this code to change the date. But when i enter a wrong date, the errorlevel command appears beeing ignored.
#echo off
#setlocal enableextensions
#cd /d "%~dp0"
mode 48,12
:start
cls
echo.
echo 1 - Mudar data
echo 2 - Retornar a data atual
echo.
echo.
echo.
echo.
choice /n /c:12 /m "Digite uma op‡Æo:"%1
if errorlevel ==2 goto 2
if errorlevel ==1 goto 1
:1
cls
set /p "dd=Digite o dia: "
cls
set /p "mm=Digite o mes: %dd% - "
cls
set /p "aa=Digite o ano: %dd% - %mm% - "
cls
date %dd%-%mm%-%aa%
if not errorlevel 1 (
cls
echo Data modificada.
pause
goto start
)
if errorlevel 1 (
cls
echo Erro ao mudar a data.
pause
goto start
)
:2
cls
w32tm /resync >nul 2>nul
cls
goto start
I supposed that if the date was typed wrong, it would appears a echo Erro ao mudar a data. But it only opens the date command screen asking to change the date because was typed wrong.
Edit 1
Just update my code including the commands to stop the Windows Time Service, because even i changed the date, after sometime the real date was replaced again.
#echo off
setlocal enableextensions
cd /d "%~dp0"
mode 42,12
:begin
cls
echo ------------------------------------------
echo MUDAR A DATA DO WINDOWS
echo ------------------------------------------
echo( &echo(
echo 1 - Escolher a data & echo( &echo 2 - Retornar para a data atual
echo( & echo( &echo(
choice /n /c:12 /m "Digite uma op‡Æo:"%1
goto :lab%errorlevel%
:lab1
cls & set /p "dd=Digite o dia: "
cls & set /p "mm=Digite o mes: %dd% / "
cls & set /p "aa=Digite o ano: %dd% / %mm% / "
date %dd%/%mm%/%aa% <nul && (
cls
net stop w32time >nul 2>nul
sc config w32time start= disabled >nul 2>nul
echo Data modificada.
timeout /nobreak /t 2 >nul 2>nul
goto begin
) || (
cls & echo Erro ao mudar a data.
echo( &echo( &echo(
pause
goto begin
)
:lab2
net start w32time >nul 2>nul
sc config w32time start= demand >nul
cls & w32tm /resync >nul 2>&1
echo Data atual retornada.
timeout /nobreak /t 2 >nul 2>nul
cls & goto begin
If you redirect input to nul for the DATE command, you still get the error message and prompt to enter a valid date, but then the command immediately fails with an appropriate error return code.
I find it much easier to use && and || to handle success and failure instead of using IF.
date %dd%-%mm%-%aa% <nul && (
cls
echo Data modificada.
) || (
cls
echo Erro ao mudar a data.
)
pause
goto start
Rename your lables :1 and :2 with :lab1 and :lab 2 then remove these lines:
if errorlevel ==2 goto 2
if errorlevel ==1 goto 1
and replace them with this line:
goto :lab%errorlevel%
You should then only have:
choice /n /c:12 /m "Digite uma op‡Æo:"%1
goto :lab%errorlevel%
Then other observations, remove the echo. lines and replace them with echo(
cls lines on their own looks ugly, so I like to integrate them by running them with & with other commands to make it look nicer
So a total cleanup will be:
#echo off
setlocal enableextensions
cd /d "%~dp0"
mode 48,12
:begin
cls
echo( & echo 1 - Mudar data & echo 2 - Retornar a data atual
echo( & echo( &echo( &echo(
choice /n /c:12 /m "Digite uma op‡Æo:"%1
goto :lab%errorlevel%
:lab1
cls & set /p "dd=Digite o dia: "
cls & set /p "mm=Digite o mes: %dd% - "
cls & set /p "aa=Digite o ano: %dd% - %mm% - "
cls & echo %dd%-%mm%-%aa% | date
if not errorlevel 1 (
cls
echo Data modificada.
pause
goto begin
) else (
cls & echo Erro ao mudar a data.
pause
goto start
)
:lab2
cls & w32tm /resync >nul 2>&1
cls & goto begin
Related
Hoping someone can point me in the right direction. Have a working remote PC info scanning tool that collects computer name, serial number and model. Been trying to get the monitor info added for so time and found this Powershell script and have been trying to get intergraded without success.
Powershell function;
$Monitors = Get-WmiObject WmiMonitorID -Namespace root\wmi
$LogFile = ".\MonInfo.csv"
function Decode {
If ($args[0] -is [System.Array]) {
[System.Text.Encoding]::ASCII.GetString($args[0])
}
Else {
"Not Found"
}
}
ForEach ($Monitor in $Monitors) {
$Manufacturer = Decode $Monitor.ManufacturerName -notmatch 0
$Name = Decode $Monitor.UserFriendlyName -notmatch 0
$Serial = Decode $Monitor.SerialNumberID -notmatch 0
echo $Manufacturer, $Name, $Serial" >> $LogFile
}
Here's the network scan batch script I been using. (Basic info scan via ping and get info from remoter systems via WMI)
#echo off
cls
color 5f
setlocal EnableDelayedExpansion
net session >nul 2>&1
if %errorlevel% neq 0 set errormsg=This program must be run as Administrator& goto ERRORDISP
set "ip="
for /f "tokens=2 delims=:" %%a in ('ipconfig ^| findstr /c:"IPv4 Address"') do set ip=%%a
if not defined ip (set errormsg=No IP address detected - check network cable& goto ERRORDISP)
set ip=%ip: =%
for /f "tokens=1,2,3,4 delims=." %%a in ("%ip%") do set oct1=%%a& set oct2=%%b& set oct3=%%c& set oct4=%%d
set subnet=%oct1%.%oct2%.%oct3%
set scan=0
set found=0
set foundsv=0
set ipstart=51
set ipend=170
:SCAN
set /a totalip=ipend-ipstart+1
set "_d=%date%"
set "_t=%time%"
set "log=scanLog%-d%-%_t%.csv"
echo IP,Name,Serial,Model > %log%
echo.
for /l %%a in (%ipstart%,1,%ipend%) do (
set "ip=%subnet%.%%a"
set /a scan=scan+1
set /a pct=scan*100/totalip
echo Scanning !ip!...
call :BAR !pct! 40 progbar
title Simple Scanner ^| !totalip!/!scan!/!found!/!foundsv! ^| [!progbar!] !pct!%%%
ping -n 1 -w 200 !ip! | find "TTL" >nul
if !errorlevel! equ 0 (
set "output="
set /a found=found+1
call :GETWMI !ip! "bios get serialnumber" serial
call :GETWMI !ip! "computersystem get model" model
call :GETWMI !ip! "computersystem get name" name
REM *** DO "SV WORKSTATION" THINGS HERE
set "output=!ip!,!name!,!serial!,!model! !MonSN!"
) else (
REM *** DO "NON-SV WORKSTATION" THINGS HERE
set "output=!ip!,!name!,!serial!,!model! !MonSN!"
)
echo !output! >> %log%
) else (
REM *** DO "WORKSTATION NOT DETECTED" THINGS HERE
)
)
:END
cls
color 2f
echo.
echo SCAN COMPLETE
echo ______________________________________________________________________
echo.
echo
echo Range: %subnet%.%ipstart% - %ipend%
echo Scanned: %scan%
echo Found total: %found%
echo Found SV: %foundsv%
echo ______________________________________________________________________
echo.
echo Opening log file %log%...
echo.
start /max %log%
echo
echo Press any key to exit...
pause>nul
exit
:GETWMI
set "_s="
set _r=%2
set _r=%_r:"=%
(for /f "tokens=2 delims==" %%b in ('wmic /failfast:on /node:%1 %_r% /value') do set _s=%%b) 2>nul
if not defined _s set "_s=ERROR"
set "%~3=%_s%"
goto :eof
:BAR
if not defined xbar call :initBAR %2
for /l %%b in (1,1,%2) do (
set /a bars=%2*%1/100
set /a spcs=%2-bars
set "obar="
for %%c in (!bars!) do set "obar=!obar!!xbar:~0,%%c!"
for %%c in (!spcs!) do set "obar=!obar!!xspc:~0,%%c!"
set %3=!obar!
)
goto :eof
:initBAR
set "xbar=" & for /l %%b in (1,1,%1) do set "xbar=!xbar!l"
set "xspc=" & for /l %%b in (1,1,%1) do set "xspc=!xspc! "
goto :eof
:ERRORDISP
cls
color cf
echo.
echo ^>^>^> ERROR ^<^<^<
echo.
echo %errormsg%
echo
echo Press any key to exit...
pause>nul
exit
I have also tried calling for the .ps1 yet the variables are always empty and the corp network requires Powershell scripts to have sign cert to run by them selves.
Long time ago I wrote the script to get monitor serial number from registry.
It takes only first monitor value. But you can change this script or convert to Powershell. Anyway you can see script logic: get EDID-number, then parse it.
#for /f %%i in ('#wmic path win32_desktopmonitor get pnpdeviceid ^|#find "DISPLAY"') do #set val="HKLM\SYSTEM\CurrentControlSet\Enum\%%i\Device Parameters"
#reg query %val% /v EDID>NUL
#if %errorlevel% GTR 0 #echo BAD EDID&EXIT
#for /f "skip=2 tokens=1,2,3*" %%a in ('#reg query %val% /v EDID') do #set edid=%%c
#set /A Y=%edid:~34,1%*16+%edid:~35,1%+1990
#echo.Manufactured: %Y%
#set id=%edid:000000FC00=#%
#for /f "tokens=1,2* delims=#" %%a in ("%id%") do #set id=%%b
#set id=%id:~0,22%
#setlocal enableextensions enabledelayedexpansion
#echo off
#for /L %%i in (0,2,20) do (
#set p=!id:~%%i,2!
#if !p!==0A #goto nxt
#set m=!m!0x!p!
)
#echo on
:nxt
#forfiles /p %windir%\system32 /m shell32.dll /c "cmd /c #echo.Model : !m!"
#endlocal
#set edid=%edid:000000FF00=#%
#for /f "tokens=1,2* delims=#" %%a in ("%edid%") do #set id=%%b
#set id=%id:~0,20%
#setlocal enableextensions enabledelayedexpansion
#for /L %%i in (0,2,18) do #set sn=!sn!0x!id:~%%i,2!
#forfiles /p %windir%\system32 /m shell32.dll /c "cmd /c #echo.S.N. : !sn!"
#endlocal
Problematic
CHKDSK ran when my machine rebooted, and displayed some stuff.
Problem is I have no idea what it displayed, since it then proceeded
to reboot the machine when it was done. How do I get it to stop,
pause or otherwise let me see what it did ?
chkdsk cannot run because the volume is in use by another process mean
?, CHKDSK needs exclusive access to the disk it’s checking if it’s
been instructed to attempt fixes or repairs. If that disk is your
Windows drive (C:), CHKDSK can’t have exclusive access, because
Windows is using that drive simply to run your system.
When we restart, the CHKDSK is performed before Windows is loaded.
CHKDSK runs as it normally does, and when it completes, it reboots the system – which, of course, causes any progress or results that might have been displayed on-screen to disappear.
In order to create a helpful tool for maintenance of my hard drives to check, fix and repair them for errors.
I did this batch
#echo off
Title Check Disk drives for errors and fix them by Hackoo 2016
mode con cols=67 lines=5 & Color 0A
:::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights
:::::::::::::::::::::::::::::::::::::::::
set "TmpLog=%Tmp%\TmpLog.txt"
set "Log=%~dp0%computername%_%~n0.txt"
If Exist "%TmpLog%" Del "%TmpLog%"
If exist "%Log%" Del "%Log%"
REM --> Check for permissions
Reg query "HKU\S-1-5-19\Environment" >nul 2>&1
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
Echo.
ECHO **************************************
ECHO Running Admin shell... Please wait...
ECHO **************************************
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
::::::::::::::::::::::::::::
:: START ::
::::::::::::::::::::::::::::
( Echo Scan started # & Date /T & Time /T & echo ************************ ) > "%TmpLog%"
setlocal ENABLEDELAYEDEXPANSION
for /f "tokens=2" %%i in ('wmic logicaldisk where "drivetype=3" ^|find /i ":"') do (
set "fix=%%i"
Call :Affich !fix!
(
echo !fix! Drive
echo ************************
echo(
(echo O
echo Y) | CHKDSK !fix! /f
echo(
echo ************************
)>> "%TmpLog%"
)
EndLocal
Goto Question
Exit /b
:Question
( echo Scan finished # & Date /T & Time /T & echo ************************ )>> "%TmpLog%"
CMD /U /C Type "%TmpLog%" > "%Log%"
If Exist "%TmpLog%" Del "%TmpLog%"
(
echo Answ = MsgBox("Did you want to reboot the computer to complete the scanning ?",VbYesNo+VbQuestion,"Reboot the computer to check hard disk drives for errors by Hackoo"^)
echo If Answ = VbYes then
echo wscript.Quit(0^)
echo Else
echo wscript.Quit(1^)
echo End If
)>"%tmp%\%~n0.vbs"
Cscript /nologo "%tmp%\%~n0.vbs"
IF "%errorlevel%" EQU "1" (start "" "%Log%" & Exit ) else (goto Shutdown)
:Shutdown
echo(
cls
echo(
echo Save your work - Reboot of your computer in 20 seconds
echo(
echo Enregistrer vos documents - Redemarrage du PC dans 20 seconds
Shutdown.exe /r /t 20 /c "Enregistrer vos documents - Redemarrage du PC dans 20 secondes"
start "" %Log%
pause>nul
exit /b
:Affich
Cls
echo(
echo ***********************************
Echo Please wait a while Scanning "%~1"
echo ***********************************
Timeout /T 2 /nobreak>nul
exit /b
So, my question is : How can i get the results of a CHKDSK that run on boot by batch or powershell ?
The information is recorded in the eventlog. You should be able to obtain it like this (using PowerShell):
Get-EventLog -LogName Application -Source Wininit |
Where-Object { $_.Message -like '*checking file system*' } |
Sort-Object TimeGenerated -Descending |
Select-Object -First 1 -Expand Message
I found the answer here:
get-winevent -FilterHashTable #{logname="Application"; id="1001"}| ?{$_.providername –match "wininit"} | fl timecreated, message | out-file Desktop\CHKDSKResults.txt
In batch file we can do like that:
#echo off
set "Log=%tmp%\CHKDSKResults.txt"
If Exist "%Log%" del "%Log%"
Powershell -Command "& "Get-winevent -FilterHashTable #{logname='Application'; id='1001'}^|?{$_.providername -match 'wininit'} ^| fl timecreated, message ^| out-file '%Log%'"
Start "" "%Log%"
EDIT : On 27/07/2016 The final code :
#echo off
Title Check Disk drives for errors and fix them by Hackoo 2016
mode con cols=67 lines=5 & Color 0A
:::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights
:::::::::::::::::::::::::::::::::::::::::
set "TmpLog=%Tmp%\TmpLog.txt"
set "Log=%~dp0%computername%_%~n0.txt"
set "MyVBSFile=%~dp0%~n0_On_Boot.vbs"
set "Value=CHKDSK_ON_BOOT"
Set "Key=HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce"
If Exist "%TmpLog%" Del "%TmpLog%"
If exist "%Log%" Del "%Log%"
REM --> Check for permissions
Reg query "HKU\S-1-5-19\Environment" >nul 2>&1
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
Echo.
ECHO **************************************
ECHO Running Admin shell... Please wait...
ECHO **************************************
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
::::::::::::::::::::::::::::
:: START ::
::::::::::::::::::::::::::::
( Echo Scan started # & Date /T & Time /T & echo ************************ ) > "%TmpLog%"
setlocal ENABLEDELAYEDEXPANSION
for /f "tokens=2" %%i in ('wmic logicaldisk where "drivetype=3" ^|find /i ":"') do (
set "fix=%%i"
Call :Affich !fix!
(
echo !fix! Drive
echo ************************
echo(
(echo O
echo Y) | CHKDSK !fix! /f
echo(
echo ************************
)>> "%TmpLog%"
)
EndLocal
Goto Question
Exit /b
::******************************************************************
:Question
( echo Scan finished # & Date /T & Time /T & echo ************************ )>> "%TmpLog%"
CMD /U /C Type "%TmpLog%" > "%Log%"
If Exist "%TmpLog%" Del "%TmpLog%"
(
echo Answ = MsgBox("Did you want to reboot the computer to complete the scanning ?",VbYesNo+VbQuestion,"Reboot the computer to check hard disk drives for errors by Hackoo"^)
echo If Answ = VbYes then
echo wscript.Quit(0^)
echo Else
echo wscript.Quit(1^)
echo End If
)>"%tmp%\%~n0.vbs"
Cscript /nologo "%tmp%\%~n0.vbs"
IF "%errorlevel%" EQU "1" ( goto AddKey ) else ( goto Shutdown )
::******************************************************************
:Shutdown
echo(
cls
echo(
echo Save your work - Reboot of your computer in 120 seconds
echo(
echo Enregistrer vos documents - Redemarrage du PC dans 120 seconds
Call:AddKey && Shutdown.exe /r /t 120 /c "Enregistrer vos documents - Redemarrage du PC dans 120 secondes"
pause>nul
exit /b
::******************************************************************
:Affich
Cls
echo(
echo ***********************************
Echo Please wait a while Scanning "%~1"
echo ***********************************
Timeout /T 2 /nobreak>nul
exit /b
::******************************************************************
:AddKey
reg query "%key%" /v "%Value%" >nul 2>&1
If "%errorlevel%" EQU "0" ( Goto :EOF
) Else (
reg add "%Key%" /v "%Value%" /t REG_SZ /d "%MyVBSFile%">nul
(
echo Option Explicit
echo 'Run as Admin
echo If Not WScript.Arguments.Named.Exists("elevate"^) Then
echo CreateObject("Shell.Application"^).ShellExecute DblQuote(WScript.FullName^) _
echo , DblQuote(WScript.ScriptFullName^) ^& " /elevate", "", "runas", 1
echo WScript.Quit
echo End If
echo Dim ws,PSCommand,LogFile,ret
echo LogFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, "."^)^) ^& "txt"
echo set ws = createobject("wscript.shell"^)
echo PSCommand = "cmd /c Powershell -Command ""& ""Get-winevent -FilterHashTable #{logname='Application'; id='1001'}^|?{$_.providername -match 'wininit'} ^| fl timecreated, message ^| out-file "^& SimpleQuote(LogFile^) ^&""
echo ret = ws.run(PScommand,0,True^)
echo ws.run DblQuote(LogFile^)
echo '**************************************
echo Function DblQuote(Str^)
echo DblQuote = chr(34^) ^& Str ^& chr(34^)
echo End function
echo '**************************************
echo Function SimpleQuote(Str^)
echo SimpleQuote = ChrW(39^) ^& Str ^& ChrW(39^)
echo End Function
echo '**************************************
)>"%MyVBSFile%"
start "" "%Log%"
)
Exit /b
::*******************************************************************
This question already has answers here:
Can I mask an input text in a bat file?
(19 answers)
Closed 6 years ago.
I have a requirement like whenever we execute a test.bat file then it should ask enter password and entered password should be hidden with *****.
Is there any simplest way in batch programming for the above requirement?
I have written the below script using PowerShell is it fine/recommended to use PowerShell for this or any other simplest way is available?
#ECHO OFF
setlocal
set "psCommand=powershell -Command "$pword = read-host 'Enter password:' -AsSecureString ; ^
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /F "usebackq delims=" %%G in (`%psCommand%`) do set password=%%G
echo "%password%"
endlocal
Also suggest how to terminate the batch file as Ctrl+C is not working?
Give a try with this little example :
#echo off
Title %~n0 by Hackoo 2016
Mode 50,5 & Color 0E
:CreatePassword
cls & Color 0E
setlocal DisableDelayedExpansion
Call :InputPassword "Please choose your password" pass1
Call :InputPassword "Please confirm your password" pass2
setlocal EnableDelayedExpansion
If !pass1!==!pass2! ( Goto:Good ) Else ( Goto:Bad )
::***********************************
:InputPassword
Cls
echo.
echo.
set "psCommand=powershell -Command "$pword = read-host '%1' -AsSecureString ; ^
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set %2=%%p
Goto :eof
::***********************************
:Good
Color 0B
Cls
echo.
echo Good password
::TimeOut /T 2 /NoBreak>nul
echo Your password stored as : "!Pass2!" without quotes
pause>nul
Goto :Eof
::***********************************
:Bad
Color 0C
Cls
echo.
echo Wrong password try again
::TimeOut /T 2 /NoBreak>nul
echo Press any key to retry again
pause>nul
Goto :CreatePassword
::***********************************
And you can also give a try for this complete example Folder Loker.bat
Edit on 31/03/2016 # 14:43
Another way in pur batch based on replace command
#Echo Off
SetLocal EnableExtensions EnableDelayedExpansion
Set /P "=Enter a Password:" < Nul
Call :PasswordInput
Echo(Your input was:!Line!
pause
Goto :Eof
:PasswordInput
::Author: Carlos Montiers Aguilera
::Last updated: 20150401. Created: 20150401.
::Set in variable Line a input password
For /F skip^=1^ delims^=^ eol^= %%# in (
'"Echo(|Replace.exe "%~f0" . /U /W"') Do Set "CR=%%#"
For /F %%# In (
'"Prompt $H &For %%_ In (_) Do Rem"') Do Set "BS=%%#"
Set "Line="
:_PasswordInput_Kbd
Set "CHR=" & For /F skip^=1^ delims^=^ eol^= %%# in (
'Replace.exe "%~f0" . /U /W') Do Set "CHR=%%#"
If !CHR!==!CR! Echo(&Goto :Eof
If !CHR!==!BS! (If Defined Line (Set /P "=!BS! !BS!" <Nul
Set "Line=!Line:~0,-1!"
)
) Else (Set /P "=*" <Nul
If !CHR!==! (Set "Line=!Line!^!"
) Else Set "Line=!Line!!CHR!"
)
Goto :_PasswordInput_Kbd
And this is another version improved by aGerman
#echo off & setlocal
Title %~n0
Mode 50,5 & Color 9E
Set /P "Pass1=Please choose your Password:" < Nul
call :HInput Pass1
echo Input length is %errorlevel%
setlocal EnableDelayedExpansion
echo Your password is !Pass1!
pause
cls
Set /P "Pass2=Please confirm your Password:" < Nul
call :HInput Pass2
echo Input length is %errorlevel%
echo Your password is !Pass2!
pause
cls
If !Pass1!==!Pass2! (echo the two passwords are the same
) else (echo the two passwords does not match)
pause
goto :eof
:HInput [ByRef_VarName]
:: inspired by Carlos
if "%__HI__%" neq "__HI__" (
setlocal DisableDelayedExpansion EnableExtensions
set "CR=" &set "S=" &set "N=0" &set "__HI__=__HI__"
for /f "skip=1" %%i in ('echo(^|replace ? . /u /w') do if not defined CR set "CR=%%i"
for /f %%i in ('"prompt $H &for %%b in (1) do rem"') do set "BS=%%i"
)
set "C="
for /f skip^=1^ delims^=^ eol^= %%i in ('replace ? . /u /w') do if not defined C set "C=%%i"
setlocal EnableDelayedExpansion EnableExtensions
if "!CR!"=="!C!" (
echo(
if "%~1"=="" (
echo(!S!
endlocal &endlocal &exit /b %N%
) else (
if defined S (
for /f delims^=^ eol^= %%i in ("!S!") do endlocal &endlocal &set "%~1=%%i" &exit /b %N%
) else endlocal &endlocal &set "%~1=" &exit /b 0
)
)
if "!BS!"=="!C!" (
set "C="
if defined S set /a "N -= 1" &set "S=!S:~,-1!" &<nul set /p "=%BS% %BS%"
) else set /a "N += 1" &<nul set /p "=*"
if not defined S (
endlocal &set "N=%N%" &set "S=%C%"
) else for /f delims^=^ eol^= %%i in ("!S!") do endlocal &set "N=%N%" &set "S=%%i%C%"
goto HInput
Hi for everyone in stackoverflow !
I'm looking for a workaround to how delete this kind of file using a reserved name such :
(nul, aux, com1, prn, etc...)
So, i get as output error :
The syntax of the file name, directory or volume incorrect.
#echo off
echo hello world>\\?\"%temp%\nul:nul"
pause
more<"%temp%\nul:nul"
pause
set /p MyVar=<"\\?\%temp%\nul:nul"
echo %MyVar%
Pause
Del "\\?\%temp%\nul:nul" /F
pause
I'm using this trick to store the password shown like in this code below
so, i can set the password into this file and also, read from it, but i can't delete it.
#echo off
Title %~n0 with colors by Hackoo
Mode 50,5 & Color 0E
Setlocal EnableDelayedExpansion
:CreatePassword
Call :InputPassword "Please choose your password" pass1
Call :InputPassword "Please confirm your password" pass2
If !pass1!==!pass2! ( Goto:Good ) Else ( Goto:Bad )
::***********************************
:InputPassword
Cls
echo.
echo.
set "psCommand=powershell -Command "$pword = read-host '%1' -AsSecureString ; ^
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set %2=%%p
Goto :eof
::***********************************
:Good
Cls
echo.
echo.
Call :Color 0B " Good password " 1
TimeOut /T 2 /NoBreak>nul
Call :Write_Info
Call :Collect_Info
echo Your password stored as : "!SavedPass!" without quotes
pause
Goto :Eof
::***********************************
:Bad
Cls
echo.
echo.
Call :Color 0C " Wrong password try again " 1
TimeOut /T 2 /NoBreak>nul
Goto :CreatePassword
::***********************************
:Color
for /F "delims=." %%a in ('"prompt $H. & for %%b in (1) do rem"') do set "BS=%%a"
set nL=%3
if not defined nL echo Requires third argument & Pause > nul & goto :Eof
if %3 == 0 (
<nul set /p ".=%BS%">%2 & Findstr /V /A:%1 /R "^$" %2 nul & Del %2 2>&1
goto :Eof
) else if %3 == 1 (
echo %BS%>%2 & Findstr /V /A:%1 /R "^$" %2 nul & Del %2 2>&1
goto :Eof
)
::***********************************
:Write_Info
(echo !Pass2!)>\\?\"%temp%\nul:nul"
Call :Color 0A " Your password is set sucessfuly" 1
::***********************************
:Collect_Info
(set /P SavedPass=)<"\\?\%temp%\nul:nul"
goto :eof
::***********************************
This worked for me:
del "\\.\%temp%\nul"
As Microsoft says in
https://support.microsoft.com/en-us/kb/120716,
you need to use a syntax which bypasses the check for reserved names.
I get the file date from a file:
for %%x in (%file_test%) do set file_date_test=%%~tx
And then I get the system date:
set year=%date:~-4%
set month=%date:~3,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
And then do an if statement with goto:
IF %file_date_test% LSS %system_date_test% goto SOME
How can I compare both dates? I would like to check if the file date has more than 24H.
Which is the best way to do that? Can I use forfiles to do it?
Edited forfiles command will not even look at the hour of the file, so the previous answer (at the bottom in case someone find it useful) will not work if the file has different date but less than 24h.
For an alternative
robocopy "c:\backup" "c:\backup" "test.bak" /l /nocopy /is /minage:1 > nul
if errorlevel 1 (
echo MATCH
) else (
echo NO_MATCH
)
At least in windows 7, the robocopy command look at the timestamp of the file to determine its age.
Previous answer
You can use forfiles checking the errorlevel of the operation
#echo off
setlocal enableextensions disabledelayedexpansion
set "file_test=c:\backups\test.bak"
for %%a in ("%file_test%") do (
forfiles /p "%%~dpa." /m "%%~nxa" /d -1 >nul 2>nul && echo MATCH || echo NO MATCH
)
Or
#echo off
setlocal enableextensions disabledelayedexpansion
forfiles /p "c:\backups" /m "test.bak" /d -1 >nul 2>nul
if errorlevel 1 (
echo NO_MATCH
) else (
echo MATCH
)