How can I get the results of a CHKDSK that run on boot? - powershell

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
::*******************************************************************

Related

How to execute a powershell file in batch repeatadly

I have a question. With my batch program I want to call a powershell program to replace words. I tried it with batch, but in my files are very often exclamation marks and yeah...batch don`t like these. So I take my batch strings and put them into powershell. This works perfectly fine. But I want to repeat this with other words and there is my problem.
set /a loop=0
:inta
set /a loop=%loop%+1
call:DoReplace "%Torsten%" "%Torsten:~0,-1%%loop%" cache\%KlausDieter:~0,-5%%loop%%Rainer% cache1\%KlausDieter:~0,-5%%loop%%Rainer%
exit /b
:DoReplace
echo ^(Get-Content "%3"^) ^| ForEach-Object { $_ -replace %1, %2 } ^| Set-Content %4>Rep.ps1
Powershell.exe -executionpolicy remotesigned -File Rep.ps1
if exist Rep.ps1 del Rep.ps1
GOTO :wer
:wer
set installel=%errorlevel%
if %loop%==%count% goto fall
if %installel%==0 goto inta
:fall
set /a loop=0
:intal
set /a loop=%loop%+1
call:DoReplaceL "%Horst%" "%Horst:~0,-1%%loop%" cache0\%Bruno:~0,-5%%loop%%Rainer% cache1\%Bruno:~0,-5%%loop%%Rainer%
exit /b
:DoReplaceL
echo ^(Get-Content "%3"^) ^| ForEach-Object { $_ -replace %1, %2 } ^| Set-Content %4>Rep.ps1
Powershell.exe -executionpolicy remotesigned -File Rep.ps1
if exist Rep.ps1 del Rep.ps1
GOTO :werl
:werl
set installel=%errorlevel%
if %loop%==%count% goto falll
if %installel%==0 goto intal
:falll
When I call it a second time there come a error with: Argument "Rep.ps1" isnt available. Isnt it possible to do such things?
I am from Germany so sorry for the bad english.
Thank you for your help
Markus
My batch-code for search and replace was this. Maybe you will find a mistake to get rid of problems with exclamation marks:
set /a loop=0
:inta
set /a loop=%loop%+1
SET "quell_datei=cache\%KlausDieter:~0,-5%%loop%.cin"
SET "ziel_datei=cache1\%KlausDieter:~0,-5%%loop%.cin"
SET "suchen_nach=%Torsten%1"
SET "ersetzen_durch=%Torsten%%loop%"
IF NOT DEFINED suchen_nach (ECHO. Fehler: Die Variable suchen_nach nicht definiert^^!&GOTO :eof)
del "%ziel_datei%" >nul 2>&1
FOR /f "tokens=1,* delims=:" %%a IN ('type "%quell_datei%" ^| FINDSTR /n "^"') DO (
CALL :ers "%%b"
)
GOTO :wer
:ers
set "zeile=%~1"
if defined zeile set "zeile=!zeile:%suchen_nach%=%ersetzen_durch%!"
>>"%ziel_datei%" echo.!zeile!
GOTO :eof
:wer
set installel=%errorlevel%
if %loop%==%count% goto fall
if %installel%==0 goto inta
:fall
echo.

Calling powershell function in batch script

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

Is it possible to query a file or process hash using wmi?

I searched for any way to query a process hash.
assuming I was able to retrive the ExecutablePath using Win32_Process,
I would like to query the file's hash.
I'm trying to avoid using powershell but to achieve the same functiallity of "Get-FileHash".
Thank You!
edit:
I have tried to use win32_filespecification that supplied md5checksum, the problem was i could not find the relevant files (such as notepad.exe).
Here is a batch file to test :
#echo off
Title Get Notepad Hash
Set "App_Path=%windir%\system32\notepad.exe"
echo "%App_Path%"
#for /f "tokens=2 skip=3 delims= " %%a in ('Powershell Get-FileHash "%App_Path%"') do echo SHA256=%%a
Pause & Exit
EDIT :
Get Process File Hash using WMIC and Certutil in command line
You can give a try for the second batch file :
#echo off
cls & color 9E & Mode 95,5
Title Get Process File Hash using WMIC and Certutil in command line
Set "TmpFile=%~dpn0_Tmp.txt"
Set "LogPathExe=%~dpn0_PathExe.txt"
Set "Hashes=%~dpn0_Hashes.txt"
echo(
echo( ===========================================================
echo( Please wait a while ... Working is in progress....
echo( ===========================================================
Setlocal EnableDelayedExpansion
> "!TmpFile!" (
#for /f "delims=" %%a in ('wmic process get ExecutablePath /format:list') do (
#For /F "tokens=2 delims==" %%b in ("%%a") do (
set "Exe=%%b"
If not defined Exe Set !Exe!
echo "!Exe!"
)
)
)
Call :RemoveDuplicateEntry "!TmpFile!" "!LogPathExe!"
Del "!TmpFile!"
> "!Hashes!" (
#for /f "delims=" %%a in ('Type "!LogPathExe!"') do (
#for /f "skip=1 delims=" %%H in ('CertUtil -hashfile "%%~a" SHA256 ^| findstr /i /v "CertUtil"') do set "H=%%H"
echo %%a=!H: =!
)
)
)
If Exist "!Hashes!" Start "" "!Hashes!" & Exit
::----------------------------------------------------
:RemoveDuplicateEntry <InputFile> <OutPutFile>
Powershell ^
$Contents=Get-Content '%1'; ^
$LowerContents=$Contents.ToLower(^); ^
$LowerContents ^| select -unique ^| Out-File '%2'
Exit /b
::----------------------------------------------------
The third batch script to check hashes on virustotal :
#echo off
cls & color 9E & Mode 95,5
Title Get Process File Hash using WMIC and Certutil in command line
Set "TmpFile=%~dpn0_Tmp.txt"
Set "LogPathExe=%~dpn0_PathExe.txt"
Set "Hashes=%~dpn0_Hashes.txt"
Set "Hash2Check_VirusTotal=%~dpn0_Hash2Check_VirusTotal.txt"
If Exist "%Hash2Check_VirusTotal%" Del "%Hash2Check_VirusTotal%"
echo(
echo( ===========================================================
echo( Please wait a while ... Working is in progress....
echo( ===========================================================
Setlocal EnableDelayedExpansion
> "!TmpFile!" (
#for /f "delims=" %%a in ('wmic process get ExecutablePath /format:list') do (
#For /F "tokens=2 delims==" %%b in ("%%a") do (
set "ExecutablePath=%%b"
If not defined ExecutablePath Set !ExecutablePath!
echo "!ExecutablePath!"
)
)
)
Call :RemoveDuplicateEntry "!TmpFile!" "!LogPathExe!"
Del "!TmpFile!"
> "!Hashes!" (
#for /f "delims=" %%a in ('Type "!LogPathExe!"') do (
#for /f "skip=1 delims=" %%H in ('CertUtil -hashfile "%%~a" SHA256 ^| findstr /i /v "CertUtil"') do set "H=%%H"
echo %%a=!H: =!
>> "!Hash2Check_VirusTotal!" echo https://www.virustotal.com/old-browsers/file/!H: =!
)
)
)
cls
Echo(
Echo( Did you want to check the executable on Virustotal ? Just Type "Y" Or any key to Quit !
Set /p "Check="
If /I [!check!] EQU [Y] (
#for /f "delims=" %%a in ('Type "!Hash2Check_VirusTotal!"') do ( Start "Chek SHA256 on VIRUSTOTAL" %%a & Timeout /T 10 /nobreak>nul)
) else (
If Exist "!Hashes!" Start "" "!Hashes!" & Exit
)
Exit
::----------------------------------------------------
:RemoveDuplicateEntry <InputFile> <OutPutFile>
Powershell ^
$Contents=Get-Content '%1'; ^
$LowerContents=$Contents.ToLower(^); ^
$LowerContents ^| select -unique ^| Out-File '%2'
Exit /b
::----------------------------------------------------

Errorlevel not working when using date command in batch file

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

How to delete this kind of file using a reserved name?

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.