i have one task scheduler with 2 .bat file on action.
List .bat file on action tab
when task scheduler running how to i know which one .bat is running ?
this is xml file task scheduler:
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2020-07-21T08:40:20.4842672</Date>
<Author>WIN-9DQ9EVI3R22\Administrator</Author>
<URI>\RESTORE</URI>
</RegistrationInfo>
<Triggers>
<CalendarTrigger>
<Repetition>
<Interval>PT5M</Interval>
<StopAtDurationEnd>false</StopAtDurationEnd>
</Repetition>
<StartBoundary>2020-07-21T00:00:00</StartBoundary>
<Enabled>true</Enabled>
<ScheduleByDay>
<DaysInterval>1</DaysInterval>
</ScheduleByDay>
</CalendarTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>S-1-5-21-316211975-241055689-3246940587-500</UserId>
<LogonType>Password</LogonType>
<RunLevel>LeastPrivilege</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>"D:\Batch File\LS_RESTORE_221.bat"</Command>
</Exec>
<Exec>
<Command>"D:\Batch File\LS_RESTORE_MAINDB.bat"</Command>
</Exec>
</Actions>
</Task>
see at the xml file i have 2 .bat on action tag
this is .bat file script
sqlcmd -Q "exec SP_LS_RESTORE" -S WIN-9DQ9EVI3R22 -d dbSaaS_HOST_221 -o "D:\Batch File\LS_Restore_out_221.txt"
You can give a try for this batch file :
#echo off
Color 0B & Title Showing No Microsoft Scheduled Tasks List by Hackoo 2020
Set "TmpFile=%~n0_Abs_cmdline.txt"
Set "LogFile=%~n0_cmdline.txt
If Exist "%TmpFile%" Del "%TmpFile%"
If Exist "%LogFile%" Del "%LogFile%"
Set ProcessNames="cmd.exe" "wscript.exe" "cscript.exe"
SetLocal EnableDelayedExpansion
for %%A in (%ProcessNames%) Do (
Call :GetCommandLine %%A ProcessCmd
If defined ProcessCmd (
echo !ProcessCmd!>>"%TmpFile%"
)
)
If Exist "%TmpFile%" Call :Extract "%TmpFile%" "%LogFile%"
If Exist "%LogFile%" Start "" "%LogFile%"
echo(
echo( ****************************************************************************************************
echo( No Microsoft Scheduled Tasks List
echo( ****************************************************************************************************
Set "EXT=BAT"
#For /F "tokens=2,9 delims=," %%a in (
'SCHTASKS /Query /NH /FO CSV /V ^|find /I /V "Microsoft" ^|find /I /V "ADOBE" ^|findstr /I /C:"%EXT%"'
) do (
REM Set TaskName=%%~a
Set TaskPath=%%~b
REM Call :Trim_Dequote !TaskName! TaskName
Call :Trim_Dequote !TaskPath! TaskPath
REM echo "!TaskName!"
echo( "!TaskPath!"
)
Pause & exit
::-----------------------------------------------------------------------------------
:Trim_Dequote <Var> <NewVar>
Set "VbsFile=%Tmp%\%~n0.vbs"
(
echo Wscript.echo Trim_Dequote("%~1"^)
echo Function Trim_Dequote(S^)
echo If Left(S, 1^) = """" And Right(S, 1^) = """" Then Trim_Dequote = Trim(Mid(S, 2, Len(S^) - 2^)^) Else Trim_Dequote = Trim(S^)
echo End Function
)>"%VbsFile%"
for /f "delims=" %%a in ('Cscript //nologo "%VbsFile%"') do (
set "%2=%%a"
)
Del "%VbsFile%" /F >nul 2>&1
exit /b
::---------------------------------------------------------------------------------------------------------------
:GetCommandLine <ProcessName> <ProcessCmd>
Set "ProcessCmd="
for /f "tokens=2 delims==" %%P in (
'2^>nul wmic process where caption^="%~1" get commandline /format:list ^| findstr /I "%~1" ^| find /I /V "%~nx0"'
) do (
if not defined %2 Set "%2=%%P"
)
Exit /b
::---------------------------------------------------------------------------------------------------------------
:Extract <InputData> <OutPutData>
(
echo Data = WScript.StdIn.ReadAll
echo Data = Extract(Data,"(^?^!.*(\x22\w\W^)^).*(\.ps1^|\.vbs^|\.vbe^|\.js^|\.jse^|\.cmd^|\.bat^|\.wsf^|\.exe^)(^?^!.*(\x22\w\W^)^)"^)
echo WScript.StdOut.WriteLine Data
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
)>"%tmp%\%~n0.vbs"
cscript /nologo "%tmp%\%~n0.vbs" < "%~1" > "%~2"
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
exit /b
::---------------------------------------------------------------------------------------------------------------
EDIT on 23/08/2020 #16:45 :
This is a Hybrid code Batch and Powershell that help us to show All No Microsoft Scheduled Tasks.
Show_No-Microsoft_Tasks.bat
<# : Batch portion
#rem # The previous line does nothing in Batch, but begins a multiline comment block
#rem # in PowerShell. This allows a single script to be executed by both interpreters.
#echo off
Title Get Schedule Tasks with a Hybrid code Batch and Powershell Script by Hackoo 2020
echo(
rem # This a Powershell command executes the hybrid portion at the bottom of this script
rem #for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0}|out-string)"') do echo %%I
>"%~dpn0.txt" (
#for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0}|out-string)"') do echo %%I
)
REM TimeOut /T 3 /NoBreak>nul
If Exist "%~dpn0.txt" Start "" "%~dpn0.txt" & exit /b
rem # End multi-line PowerShell comment block. Begin PowerShell scripting.
: end Batch / begin PowerShell hybrid code #>
Function getTasks($path) {
$out = #()
# Get root tasks
$schedule.GetFolder($path).GetTasks(0) | % {
$xml = [xml]$_.xml
$out += New-Object psobject -Property #{
"Name" = $_.Name
"Path" = $_.Path
"LastRunTime" = $_.LastRunTime
"NextRunTime" = $_.NextRunTime
"Actions" = ($xml.Task.Actions.Exec | % { "$($_.Command) $($_.Arguments)" }) -join "`n"
}
}
# Get tasks from subfolders
$schedule.GetFolder($path).GetFolders(0) | % {
$out += getTasks($_.Path)
}
#Output
$out
}
$tasks = #()
$schedule = New-Object -ComObject "Schedule.Service"
$schedule.Connect()
# Start inventory
$tasks += getTasks("\")
# Close com
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($schedule) | Out-Null
Remove-Variable schedule
# To show All No Microsoft Scheduled Tasks
$tasks | ? { $_.Path -notmatch "Micro*" }
Read-Host 'Type any key to continue'
$tasks | ? { $_.Path -notmatch "Micro*" } | Out-GridView
Read-Host 'Type any key to continue'
<#
# Output all tasks
#$tasks | Out-GridView
#Read-Host 'Type any key to continue'
# To show only tasks with those extensions in their TaskPath
#$tasks | ? { $_.Actions -match "(\.vbs|\.vbe|\.cmd|\.bat|\.hta)" } | Out-GridView
#Read-Host 'Type any key to continue'
#>
Related
I'm trying to go through a .csv file I've copied in a .txt, and find any line that has any of these characters \ / : * ? " ' < >.
In this code I use find to output all line containing "/", but how can I look for every line with one of the special characters above?
#echo off
setlocal
for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
mkdir Output
copy "%%~I" Output\csvCopy.csv
)
for /f "tokens=2,* delims=;" %%a in (Output\csvCopy.csv) do ( echo %%b >> Output\debug.txt )
find /N "/" Output\debug.txt > Output\finalDebug.txt
start "" Output\finalDebug.txt
pause
#REM delete folder output
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 = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*"
$f.ShowHelp = $true
$f.Multiselect = $false
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }
How to write a Batch file to go to the directory mentioned in a variable inside for loop.
I have the below query which allows me to select a file through the file select dialog and I have placed the directory of the file in variable path1.
I need to go to this directory and then again create a folder there with the user input name.
I am writing the below code but echo !mypath! is showing the directory where the batch file is present.
<# : chooser.bat
:: launches a File
#echo off
for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
echo You chose %%~dpI >> E:\Rajan\test.txt
set "path1=%%~dpI"
setlocal EnableDelayedExpansion
echo !path1! >> E:\Rajan\test2.txt
cd /D "!path1!"
set /p name =Enter your name
set mypath=%cd%
echo !mypath! >> E:\Rajan\test3.txt
md "%name%"
endlocal
)
goto :EOF
: #>
Add-Type -AssemblyName System.Windows.Forms
$f = new-object Windows.Forms.OpenFileDialog
$f.InitialDirectory = pwd
$f.Filter = "Text Files (*.dmp)|*.dmp"
$f.ShowHelp = $true
$f.Multiselect = $false
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }
I thought I put this on the previous question.
<# : chooser.bat
:: launches a File
#echo off
SET "THE_FILE="
for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
echo You chose %%~I
SET "THE_FILE=%%~I"
)
CD /D "%THE_FILE%\..\"
set /p "name=Enter your name: "
set "mypath=%cd%"
echo %mypath% >>"E:\Rajan\test3.txt"
IF NOT EXIST ".\%name%" (md "%name%")
goto :EOF
: #>
Add-Type -AssemblyName System.Windows.Forms
$f = new-object Windows.Forms.OpenFileDialog
$f.InitialDirectory = pwd
$f.Filter = "Text Files (*.dmp)|*.dmp"
$f.ShowHelp = $true
$f.Multiselect = $false
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }
Here's my answer again, this time using powershell, instead of jscript, to invoke the dialog box.
#Echo Off
SetLocal EnableExtensions
For /F Delims^=^ EOL^= %%G In ('^"
"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile ^
"(New-Object -COM 'Shell.Application').BrowseForFolder(0,'Select your directory.',1,0).Self.Path"
^"') Do MD "%%G\%UserName%"
As you can clearly see, the command using the output from the for-loop is exactly as I provided in my previous answer, and shows my comment, to be correct.
Im trying to make a script that the user need to fill 3 spaces in the same line.
Is it possibile?
For example filling a date: 25/02/2019 in this way: day here / month here / year here
Not line by line.
The normal way is that:
set /p "dd=Type the Day: "
set /p "mm=Type the Month: %dd% / "
set /p "aa=Type The Year: %dd% / %mm% / "
And the result will be: 22/05/2019
But i want put these 3 set /p in one single line, filling only this single line.
I tried this way:
set dd=%%a
set mm=%%b
set aa=%%c
set /p "test= "!dd! !mm! !aa!
echo %%a / %%b / %%c
pause
Also tried:
set /p "dd=Type the day: " / &set /p "mm=Type the month " &set /p "aa=Type the year "
But unfortunatelly didn't worked. The second way worked line by line.
Edit 1:
Follow my final script to change the Windows date by batch command:
#echo off
setlocal enableextensions
setlocal EnableDelayedExpansion
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
call :lab%errorlevel%
:lab 1
cls
for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"
for /F %%a in ('copy /Z "%~F0" NUL') do set "CR=%%a"
set /P "=Digite a data: / / !CR!Digite a data: " < nul
call :GetDigits 2 3 Day=
set /P "=.%BS% / " < nul
call :GetDigits 2 1 Mon=
set /P "=.%BS% / " < nul
call :GetDigits 4 2 Year=
echo/
echo/
net stop w32time >nul 2>nul
sc config w32time start= disabled >nul 2>nul
date %Day%-%Mon%-%Year% <nul && (
echo Data modificada: %Day%/%Mon%/%Year%
timeout /nobreak /t 2 >nul 2>nul
goto begin
) || (
cls & echo Erro ao mudar a data.
echo( &echo( &echo(
pause
goto begin
)
:GetDigits HowMany FirstLimit Result=
setlocal EnableDelayedExpansion
set "digits=123456789"
set "%3="
choice /C "0!digits:~0,%2!" /N > nul
set /A digit=%errorlevel%-1
set /P "=%digit%" < nul
set "%3=!%3!%digit%"
for /L %%i in (2,1,%1) do (
choice /C "0%digits%" /N > nul
set /A digit=!errorlevel!-1
set /P "=!digit!" < nul
set "%3=!%3!!digit!"
)
for %%a in (!%3!) do endlocal & set "%3=%%a"
exit /B
:lab2
sc config w32time start= demand >nul
net start w32time >nul 2>nul
cls & w32tm /resync >nul 2>&1
echo Data atual retornada.
timeout /nobreak /t 2 >nul 2>nul
cls & goto begin
No comments... ;)
#echo off
setlocal EnableDelayedExpansion
for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"
for /F %%a in ('copy /Z "%~F0" NUL') do set "CR=%%a"
set /P "=Enter the date: DD / MM / YYYY!CR!Enter the date: " < nul
call :GetDigits 2 3 Day=
set /P "=.%BS% / " < nul
call :GetDigits 2 1 Mon=
set /P "=.%BS% / " < nul
call :GetDigits 4 2 Year=
echo/
echo/
echo Result: %Day%/%Mon%/%Year%
goto :EOF
:GetDigits HowMany FirstLimit Result=
setlocal EnableDelayedExpansion
set "digits=123456789"
set "%3="
choice /C "0!digits:~0,%2!" /N > nul
set /A digit=%errorlevel%-1
set /P "=%digit%" < nul
set "%3=!%3!%digit%"
for /L %%i in (2,1,%1) do (
choice /C "0%digits%" /N > nul
set /A digit=!errorlevel!-1
set /P "=!digit!" < nul
set "%3=!%3!!digit!"
)
for %%a in (!%3!) do endlocal & set "%3=%%a"
exit /B
This is the closest to what you want. It requires the choice command.
There's still a blinking curser that is mildly annoying but you can solve that with third party commands if you wish.
#echo off
choice /c "1234567890" /m "__/__/__" /n
set x1=%errorlevel%
if errorlevel 10 set x1=0
cls
choice /c "1234567890" /m "%x1%_/__/__" /n
set x2=%errorlevel%
if errorlevel 10 set x2=0
cls
choice /c "1234567890" /m "%x1%%x2%/__/__" /n
set x3=%errorlevel%
if errorlevel 10 set x3=0
cls
choice /c "1234567890" /m "%x1%%x2%/%x3%_/__" /n
set x4=%errorlevel%
if errorlevel 10 set x4=0
cls
choice /c "1234567890" /m "%x1%%x2%/%x3%%x4%/__" /n
set x5=%errorlevel%
if errorlevel 10 set x5=0
cls
choice /c "1234567890" /m "%x1%%x2%/%x3%%x4%/%x5%_" /n
set x6=%errorlevel%
if errorlevel 10 set x6=0
cls
echo Date - %x1%%x2%/%x3%%x4%/%x5%%x6%
pause>nul
If the system is a supported Windows platform, PowerShell can be called from a .bat file script to present a GUI calendar for date selection. Place the .ps1 script in the same directory as the .bat script. Adapted from https://learn.microsoft.com/en-us/powershell/scripting/samples/creating-a-graphical-date-picker?view=powershell-6
=== guical.bat
set "THEDATE="
for /f "delims=" %%d in ('powershell -NoLogo -NoProfile -File "%~dp0guical.ps1"') do (
set "THEDATE=%%~d"
)
if "%THEDATE%" == "" (
echo No date selected.
) else (
echo Selected date is %THEDATE%
)
=== guical.ps1
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object Windows.Forms.Form -Property #{
StartPosition = [Windows.Forms.FormStartPosition]::CenterScreen
Size = New-Object Drawing.Size 233, 270
Text = 'Select a Date'
Topmost = $true
}
$calendar = New-Object Windows.Forms.MonthCalendar -Property #{
ShowTodayCircle = $false
MaxSelectionCount = 1
}
$form.Controls.Add($calendar)
$OKButton = New-Object Windows.Forms.Button -Property #{
Location = New-Object Drawing.Point 38, 200
Size = New-Object Drawing.Size 75, 23
Text = 'OK'
DialogResult = [Windows.Forms.DialogResult]::OK
}
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object Windows.Forms.Button -Property #{
Location = New-Object Drawing.Point 113, 200
Size = New-Object Drawing.Size 75, 23
Text = 'Cancel'
DialogResult = [Windows.Forms.DialogResult]::Cancel
}
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$result = $form.ShowDialog()
if ($result -eq [Windows.Forms.DialogResult]::OK) {
$date = $calendar.SelectionStart
Write-Host "$($date.ToString('MM\/dd\/yyyy'))"
}
You could also use powershell directly from a for loop in your batch-file, if it suits your purpose better:
Something like this may be adequate; the end user is prompted to enter the date in a specific format, and continues only when PowerShell recognises the input as a valid date:
#Echo Off
Set "Input="
For /F "Tokens=*" %%A In ('PowerShell -NoP^
"$d=$Null;While(1){Try{$d=[DateTime](Read-Host 'Date [dd/MM/yyyy]')"^
";Break}Catch{}};$d.ToString('dd/MM/yyyy')" 2^>Nul')Do Set "Input=%%A"
Set Input 2>Nul&Pause
Hello I'm trying to figure out how to have my results show in MB so its more readable instead of bytes. This script is used for monitoring a common folder in a list of servers.
Thank you for any help provided. I searched around on google for quite awhile but couldn't figure this out on my own.
ECHO DATE: %DATE% > filecount.TXT
ECHO TIME: %TIME% >> filecount.TXT
ECHO USER: %USERNAME% >> filecount.TXT
ECHO COMPUTER: %COMPUTERNAME% >> filecount.TXT
ECHO. >> filecount.TXT
ECHO. >> filecount.TXT
ECHO. >> filecount.TXT
FOR /F "tokens=1" %%i in (servers.txt) DO (
ECHO %%i ::: >> filecount.TXT
ECHO Counting %%i
dir \\%%i\c$\folder1\folder2 | findstr "File(s)" >> filecount.TXT
ECHO. >> filecount.TXT
ECHO. >> filecount.TXT
)
:::::::::::::::::::::::: END SCRIPT :::::::::::::::::::::::::
You can conveniently and efficiently use ROBOCOPY to get cumulative file counts and file sizes. It will automatically convert large values to kilobytes, megabytes, or gigabytes, (or possibly terabytes?).
I put the code to get the file count and file size in its own subroutine.
I also simplified the code by putting the main block of code in parentheses and redirecting only once - it is easier to write, and it is more efficient (faster).
I also added code to translate t, g, m, k, and blank into TB, GB, MB, KB, and B. The code would be simpler without the translation.
I'm pretty sure the code would have to change if your language is not English.
#echo off
setlocal
:: Initialize unit translation
for /f "eol== delims==" %%V in ('set unit_ 2^>nul') do set "%%V="
for %%A in ("t=TB" "g=GB" "m=MB" "k=KB") do set "unit_%%~A"
> filecount.TXT (
echo DATE: %DATE%
echo TIME: %TIME%
echo USER: %USERNAME%
echo COMPUTER: %COMPUTERNAME%
echo(
echo(
echo(
for /f "tokens=1" %%S in (servers.txt) do (
echo %%S :::
echo Counting %%S
call :printSize "\\%%S\c$\folder1\folder2"
echo(
echo(
)
)
exit /b
:printSize %1
setlocal
for /f "tokens=1,3,4" %%A in (
'robocopy %1 %1 /l /is /nfl /ndl /njh'
) do (
setlocal enableDelayedExpansion
if %%A == Files (
set "files= %%B"
) else if %%A == Bytes (
set "bytes= %%B"
set "unit=!unit_%%C!"
if not defined unit set "unit=B"
)
)
echo %files:~-16% File(s) %bytes:~-8% %unit%
exit /b
Here's a batch function that'll convert an integer into a human readable B / KB / MB / GB convention. It uses a bit mask one bit to the right of the most significant bit to check whether the final value should be rounded up. Put this at the bottom of your script below the final exit /b or goto :EOF:
:humansize <return_var> <int>
setlocal enabledelayedexpansion
set "unit=B"
set /a "mask = 512, roundup = 0, size = %~2"
for %%I in (KB MB GB) do (
if !size! geq 1024 (
set "unit=%%I"
set /a "roundup = size & mask, size >>= 10"
)
)
if %roundup% gtr 0 set /a "size += 1"
endlocal & set "%~1=%size% %unit%" & exit /b
Example usage:
call :humansize human 1536
rem // %human% now contains "2 KB"
call :humansize human 1535
rem // %human% now contains "1 KB"
Be advised that batch math is limited to 32-bit signed integers (2GB).
The SET command cannot do floating point math, so this is technically an estimation. Also you are limited to 32 bit Integers. So the largest byte size you can do math on is 2147483647
#echo off
ECHO DATE: %DATE% > filecount.TXT
ECHO TIME: %TIME% >> filecount.TXT
ECHO USER: %USERNAME% >> filecount.TXT
ECHO COMPUTER: %COMPUTERNAME% >> filecount.TXT
ECHO. >> filecount.TXT
ECHO. >> filecount.TXT
ECHO. >> filecount.TXT
FOR /F "tokens=1" %%i in (servers.txt) DO (
ECHO %%i ::: >> filecount.TXT
ECHO Counting %%i
FOR /F "tokens=1-4 delims= " %%G IN ('dir /-C \\%%i\c$\folder1\folder2 ^| findstr "File(s)"') DO (
set size=%%I
set bytes=%%J
setlocal enabledelayedexpansion
IF !size! GEQ 1048576 (
set /a size/=1048576
set bytes=MB
)
echo %%G %%H !SIZE! !bytes! >> filecount.TXT
endlocal
)
ECHO. >> filecount.TXT
ECHO. >> filecount.TXT
)
pause
:::::::::::::::::::::::: END SCRIPT :::::::::::::::::::::::::
Batch Script Get Total Sum by Size and Count of Files within a Folder
Attached is a batch script method that will get you the KB, MB, and GB along with all the other detail you needed from your script. It'll all go to the log file and be appended accordingly while still iterating through the file list of servers getting the sum and counts of the files within the directory.
Batch Script
Set the LogFile and ServerList variables up top. Set the directory to get the file detail from within the FOR loop still as an argument passed with the call command passing that as an argument tp the dynamic PowerShell script build routine that does the calculations, etc.
#ECHO ON
SET LogFile=filecount.TXT
SET ServerList=Servers.txt
ECHO.........................................>> "%LogFile%"
ECHO DATE: %DATE% >> "%LogFile%"
ECHO TIME: %TIME% >> "%LogFile%"
ECHO USER: %USERNAME% >> "%LogFile%"
ECHO COMPUTER: %COMPUTERNAME% >> "%LogFile%"
ECHO. >> "%LogFile%"
FOR /F "TOKENS=1" %%i IN (%ServerList%) DO (
ECHO ~~~Counting %%~i~~~ >> "%LogFile%"
CALL :PowerShellBuild "\\%%~i\c$\folder1\folder2"
)
ECHO.........................................>> "%LogFile%"
EXIT
GOTO EOF
:::::::::::::::::::::::: END OF SCRIPT STILL :::::::::::::::::::::::::
:PowerShellBuild
SET TmpPSScript=%Temp%\~tmpFileCalc.ps1
IF EXIST "%TmpPSScript%" DEL /Q /F "%TmpPSScript%"
ECHO $Folder = "%~1" >>"%TmpPSScript%"
ECHO $Files = Get-ChildItem $folder>>"%TmpPSScript%"
ECHO $KBTotal = ($files ^| Measure-Object -Sum Length).Sum / 1kb >>"%TmpPSScript%"
ECHO $MBTotal = ($files ^| Measure-Object -Sum Length).Sum / 1mb >>"%TmpPSScript%"
ECHO $GBTotal = ($files ^| Measure-Object -Sum Length).Sum / 1gb >>"%TmpPSScript%"
ECHO $Count = ($files ^| Measure-Object).count >>"%TmpPSScript%"
ECHO $KBTotal = [math]::Round($KBTotal, 2) >>"%TmpPSScript%"
ECHO $MBTotal = [math]::Round($MBTotal, 2) >>"%TmpPSScript%"
ECHO $GBTotal = [math]::Round($GBTotal, 2) >>"%TmpPSScript%"
ECHO ECHO "Count: $Count" ^| Out-File -encoding ascii -append "%LogFile%" >>"%TmpPSScript%"
ECHO ECHO "KB: $KBTotal" ^| Out-File -encoding ascii -append "%LogFile%" >>"%TmpPSScript%"
ECHO ECHO "MB: $MBTotal" ^| Out-File -encoding ascii -append "%LogFile%" >>"%TmpPSScript%"
ECHO ECHO "GB: $GBTotal" ^| Out-File -encoding ascii -append "%LogFile%" >>"%TmpPSScript%"
:PowerShellExec
SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0
CD /D "%PowerShellDir%"
Powershell -ExecutionPolicy Bypass -Command "& '%TmpPSScript%'"
GOTO EOF
My Test Example Script
Result
........................................
DATE: Sat 03/11/2017
TIME: 16:52:32.48
USER: User
COMPUTER: FBIPC
~~~Counting Clutter~~~
Count: 15
KB: 2490.48
MB: 2.43
GB: 0
~~~Counting Photowork~~~
Count: 7
KB: 372.88
MB: 0.36
GB: 0
........................................
Native PowerShell
Test the syntax on your system(s) with the native PowerShell to confirm it works at this level from the PowerShell ISE app but it works for my with Windows 10 with PowerShell 5.0 and Windows 7 with PowerShell 4.0
$LogFile = "C:\Users\User\Desktop\Scripts\logfile.log"
$Folder = "C:\Users\User\Desktop\Scripts"
$Files = Get-ChildItem $folder
$KBTotal = ($files | Measure-Object -Sum Length).Sum / 1kb
$MBTotal = ($files | Measure-Object -Sum Length).Sum / 1mb
$GBTotal = ($files | Measure-Object -Sum Length).Sum / 1gb
$Count = ($files | Measure-Object).count
$KBTotal = [math]::Round($KBTotal, 2)
$MBTotal = [math]::Round($MBTotal, 2)
$GBTotal = [math]::Round($GBTotal, 2)
ECHO "Count: $Count" | Out-File -encoding ascii -append $Logfile
ECHO "KB: $KBTotal" | Out-File -encoding ascii -append $Logfile
ECHO "MB: $MBTotal" | Out-File -encoding ascii -append $Logfile
ECHO "GB: $GBTotal" | Out-File -encoding ascii -append $Logfile
Further Resources
Call
Measure Object
PowerTip: Use PowerShell to Round Numbers
Out-File
Is there way to echo text after a set command? I have tried, but nothing seems to work. Here is my code:
#echo off
Echo Enter a website:
Set /p op="Https:\\" ".com"
:: The ".com" would be displayed behind the users input.
if %op%==%op% goto Show
:Show
cls
Echo Website: Http:\\%op%.com
pause
exit
How would I get the .com to be displayed after the input? I would preferably like to have the ".com" frozen in one spot, no matter how big the users input is.
I took the solution from this answer and slightly modified it in order to fulfill this request.
#echo off
setlocal EnableDelayedExpansion
for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"
for /F %%a in ('copy /Z "%~F0" NUL') do set "CR=%%a"
set "op="
set /P "=Https:\\.com!BS!!BS!!BS!!BS!" < NUL
:nextKey
set "key="
for /F "delims=" %%K in ('xcopy /W "%~F0" "%~F0" 2^>NUL') do if not defined key set "key=%%K" & set "key=!key:~-1!"
if "!key!" equ "!CR!" goto endInput
if "!key!" neq "!BS!" (
set "op=%op%%key%"
set /P "=.!BS!%key%.com!BS!!BS!!BS!!BS!" < NUL
) else if defined op (
set "op=%op:~0,-1%"
set /P "=.!BS!!BS!.com !BS!!BS!!BS!!BS!!BS!" < NUL
)
goto nextKey
:endInput
echo/
echo/
echo Website: Http:\\%op%.com
EDIT: New method added (requested in a comment)
#echo off
setlocal EnableDelayedExpansion
set /A spaces=10, backSpaces=spaces+4
set "spcs="
for /L %%i in (1,1,%spaces%) do set "spcs=!spcs! "
set "back="
for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"
for /L %%i in (1,1,%backSpaces%) do set "back=!back!!BS!"
set /P "op=Https:\\%spcs%.com!back!"
echo/
echo Website: Http:\\%op%.com
Per #Marged's comments, I suspect this is impossible (or at least extremely difficult) by batch file.
Here's a PowerShell solution should that be of use:
function Get-UserInput {
param (
[parameter(mandatory = $false)]
[string]$pre='Enter text:'
,
[parameter(mandatory = $false)]
[string]$post='_'
)
process {
[string]$text=''
while ($key.Key -ne 'Enter') {
write-host "`r$pre$text$post " -NoNewline #trailing space to hide deleted chars
#replace the above with the 3 below if you want user input to be a different colour to the defaults
#write-host "`r$pre" -NoNewline
#write-host $text -NoNewline -ForegroundColor Cyan
#write-host "$post " -NoNewline #trailing space to hide deleted chars
$key = [Console]::ReadKey($true)
switch ($key.Key)
{
'Backspace' { $text = $text.substring(0,($text.length-1)) }
default { $text = $text + $key.KeyChar }
}
}
write-host "" #undo no new line
write-output "$pre$text$post"
}
}
clear-host
$input = Get-UserInput -pre 'https://' -post '.com'
"User entered: '$input'"