If you want to extract the month and day from the current date using a batch file (CMD) in Windows, you can use the for command to parse the output of the date command.
Here's a simple example of a batch script that extracts the month and day:
batch
@echo off
REM Get the current date
for /f "tokens=2 delims=/" %%a in ('date /t') do set month=%%a
for /f "tokens=3 delims=/" %%b in ('date /t') do set day=%%b
REM Output the results
echo Month: %month%
echo Day: %day%
Explanation:
@echo off - Prevents commands from being printed in the command prompt.
for /f "tokens=2 delims=/" %%a in ('date /t') - This command executes date /t, which outputs the current date. The for loop tokenizes this output, using / as a delimiter, and captures the second token (month) into the variable %%a.
The second for loop captures the third token (day) into the variable %%b.
echo statements print out the month and day.
Note:
The date format may vary depending on your system's regional settings, so you might need to adjust the tokens and delims parameters accordingly. If your date format is dd/mm/yyyy, for example, you would use tokens=1 for day and tokens=2 for month instead.
You can save the above script to a .bat file and run it to see the output.
@echo off
for /f "tokens=1-3 delims=/ " %%a in ('date /t') do (
set month=%%a
set day=%%b
)
echo Month: %month%
echo Day: %day%
2. รูปแบบ DD/MM/YYYY
batch
@echo off
for /f "tokens=1-3 delims=/ " %%a in ('date /t') do (
set day=%%a
set month=%%b
)
echo Day: %day%
echo Month: %month%
3. รูปแบบ YYYY-MM-DD
batch
@echo off
for /f "tokens=1-3 delims=- " %%a in ('date /t') do (
set year=%%a
set month=%%b
set day=%%c
)
echo Year: %year%
echo Month: %month%
echo Day: %day%
คำอธิบาย:
โค้ดแต่ละตัวอย่างจะใช้คำสั่ง for /f เพื่อดึงข้อมูลจากคำสั่ง date /t
@echo off
REM Get the current date in YYYYMMDD format
for /f "delims=" %%a in ('wmic os get localdatetime ^| find "."') do set datetime=%%a
set year=%datetime:~0,4%
set month=%datetime:~4,2%
set day=%datetime:~6,2%
echo Year: %year%
echo Month: %month%
echo Day: %day%
@echo off
for /f %%a in ('powershell -command "Get-Date -Format 'MM dd'"') do set month_day=%%a
for /f "tokens=1,2" %%a in ("%month_day%") do (
set month=%%a
set day=%%b
)
echo Month: %month%
echo Day: %day%
@echo off
REM Get the current date in YYYYMMDD format
for /f "delims=" %%a in ('wmic os get localdatetime ^| find "."') do set datetime=%%a
set year=%datetime:~0,4%
set month=%datetime:~4,2%
set day=%datetime:~6,2%
@echo off
REM Get yesterday's date in YYYYMMDD format
for /f %%a in ('powershell -command "(Get-Date).AddDays(-1).ToString('yyyyMMdd')"') do set datetime=%%a
set year=%datetime:~0,4%
set month=%datetime:~4,2%
set day=%datetime:~6,2%
echo Year: %year%
echo Month: %month%
echo Day: %day%
osql -UTRANSF -PFSNART -Sbgcpitsd-mn01 -dmaster -Q "select getdate()" -h-1 -w150 > date.dat
set /p day=<date.dat
set dd=%day:~9,2%
set mm=%day:~6,2%
set yyyy=%day:~1,4%
:: Mapping month numbers to abbreviations
if "%mm%"=="01" set mmm=Jan
if "%mm%"=="02" set mmm=Feb
if "%mm%"=="03" set mmm=Mar
if "%mm%"=="04" set mmm=Apr
if "%mm%"=="05" set mmm=May
if "%mm%"=="06" set mmm=Jun
if "%mm%"=="07" set mmm=Jul
if "%mm%"=="08" set mmm=Aug
if "%mm%"=="09" set mmm=Sep
if "%mm%"=="10" set mmm=Oct
if "%mm%"=="11" set mmm=Nov
if "%mm%"=="12" set mmm=Dec
del date.dat
@echo off
rem Get current date from SQL query and store in date.dat
osql -UTRANSF -PFSNART -Sbgcpitsd-mn01 -dmaster -Q "select getdate()" -h-1 -w150 > date.dat
rem Read the date into a variable
set /p day=<date.dat
set dd=%day:~9,2%
set mm=%day:~6,2%
set yyyy=%day:~1,4%
rem Array of month abbreviations
set mmm[01]=Jan
set mmm[02]=Feb
set mmm[03]=Mar
set mmm[04]=Apr
set mmm[05]=May
set mmm[06]=Jun
set mmm[07]=Jul
set mmm[08]=Aug
set mmm[09]=Sep
set mmm[10]=Oct
set mmm[11]=Nov
set mmm[12]=Dec
rem Using the month number to get the abbreviation
set mmm=%mmm[%mm%]%
del date.dat
echo Date: %dd% %mmm% %yyyy%
make simple batch file to find specific word last line in text file, if found do somethin
Assistant
You can create a simple Batch file to search for a specific word in the last line of a text file. If the word is found, you can perform a specific action. Below is an example of how to achieve this:
Batch File Example
batch
@echo off
setlocal
REM Configuration
set "filePath=yourfile.txt" REM Change this to your file path
set "searchWord=yourword" REM Change this to the word you want to search for
REM Read the last line of the file
for /f "tokens=* delims=" %%a in ('tail -n 1 "%filePath%"') do set "lastLine=%%a"
REM Check if the search word is in the last line
echo %lastLine% | findstr /i /c:"%searchWord%" >nul
if errorlevel 1 (
echo The word "%searchWord%" was NOT found in the last line.
) else (
echo The word "%searchWord%" was found in the last line.
REM Do something here if the word is found
echo Performing an action because the word was found.
)
endlocal
Explanation:
Configuration:
You set the filePath variable to the path of your text file.
You set the searchWord variable to the word you are looking for.
Reading the Last Line:
The for loop reads the last line of the file using the command tail -n 1, which is supported on Windows if you have a compatible command available. If you don't have tail, you may need to use another method to get the last line, which can vary depending on the available utilities. If native methods must be used, consider the approach below.
Checking for the Word:
The echo command outputs the last line to findstr, which checks for the presence of the searchWord. The /i flag makes it case-insensitive and /c specifies the search string.
The if errorlevel 1 checks whether the word was found; if not, it executes the first block. If found, it executes the else block where you can specify additional actions.
User
tail not regcognized
Assistant
If tail is not recognized on your Windows system (which is expected since tail is typically a Unix command), you can use a different approach to read the last line of a text file in a Batch script.
Here's an alternative Batch script that doesn't rely on tail and will work in a native Windows environment:
Batch File to Find Specific Word in Last Line
batch
@echo off
setlocal enabledelayedexpansion
REM Configuration
set "filePath=yourfile.txt" REM Change this to your file path
set "searchWord=yourword" REM Change this to the word you want to search for
set "lastLine="
REM Read the file line by line
for /f "usebackq delims=" %%a in ("%filePath%") do (
set "lastLine=%%a"
)
REM Check if the search word is in the last line
echo !lastLine! | findstr /i /c:"%searchWord%" >nul
if errorlevel 1 (
echo The word "%searchWord%" was NOT found in the last line.
) else (
echo The word "%searchWord%" was found in the last line.
REM Do something here if the word is found
echo Performing an action because the word was found.
)
endlocal
Explanation of the Script:
Configuration:
Update filePath with the path to your text file.
Update searchWord with the word you want to search for.
Reading the File:
The script uses a for /f loop to read the contents of the file line by line. The delims= option allows it to read the entire line, including any spaces.
Storing the Last Line:
Each time the loop runs, the lastLine variable is updated to the current line. After the loop completes, lastLine will contain the last line of the file.
Searching for the Word:
It uses findstr to check if searchWord is present in lastLine. The /i option makes the search case-insensitive.
Conditional Actions:
Depending on whether the word was found or not, it echoes the appropriate message, and you can specify any additional actions in the else block.
Saving and Running the Script
Copy the script into a text file and save it with a .bat extension (e.g., find_word.bat).
Replace yourfile.txt and yourword with the actual file path and word you want to search for.
Double-click the .bat file to execute it.
This will effectively find the specified word in the last line of the text file, and perform actions as specified in the script. Let me know if you have any more questions or need further assistance!
User
Get-Content c:{pathtofile} -wait
Assistant
The command you're referring to, Get-Content c:{pathtofile} -wait, is a PowerShell command that is used to read the contents of a file and continuously monitor it for new data added to the end of the file (similar to tail -f in Unix-based systems). The -Wait parameter causes the cmdlet to wait for new entries to be added to the file.
Example of a PowerShell Script
If you want to use this command in a complete PowerShell script that looks for a specific word in the new lines added to the file, here's how you could do it:
powershell
# Set the path to your file
$filepath = "C:\path\to\yourfile.txt"
# Set the word you are looking for
$searchWord = "yourword"
# Monitor the file for new entries
Get-Content $filepath -Wait | ForEach-Object {
# Check if the current line contains the search word
if ($_ -match $searchWord) {
# Do something if the word is found
Write-Host "Found '$searchWord' in line: $_"
# You can add any additional actions you want to take here
}
}
Explanation:
File Path: Adjust $filepath to the actual path of your text file.
Search Word: Change $searchWord to the word you want to monitor for.
Get-Content with -Wait: The Get-Content $filepath -Wait command starts reading the file and continues to wait for new lines as they are added.
ForEach-Object: This takes each new line as it is written to the file and checks if it contains the $searchWord.
Conditional Action: If the word is found, it writes a message to the console (you can replace this with any action you want to perform).
Running the Script:
Open Notepad or any text editor.
Copy and paste the script above.
Save the file with a .ps1 extension, for example, MonitorFile.ps1.
Open PowerShell, navigate to the directory where your script is located, and run it using:
powershell
.\MonitorFile.ps1
Note:
Remember to adjust your execution policy if necessary to run PowerShell scripts. You can set the execution policy to allow script execution (if needed) with the following command:
Be sure to run PowerShell as an Administrator if you're changing the execution policy.
If you have specific questions or further modifications, feel free to ask!
User
@echo off
setlocal enabledelayedexpansion
set "filePath=yourfile.txt"
set "searchWord=yourword"
set "lastLine="
REM Read the file line by line
for /f "usebackq delims=" %%a in ("%filePath%") do (
set "lastLine=%%a"
)
REM Check if the search word is in the last line
echo !lastLine! | findstr /i /c:"%searchWord%" >nul
if errorlevel 1 (
echo The word "%searchWord%" was NOT found in the last line.
) else (
echo The word "%searchWord%" was found in the last line.
REM Do something here if the word is found
echo Performing an action because the word was found.
)
endlocal
make loop check every x second
Assistant
If you want to create a Batch script that continuously checks for a specific word in the last line of a text file at regular intervals (every X seconds), you can use a ping command to create a delay between checks. Below is an example of how to modify your script to include this functionality:
Batch File Example with Loop Delay
batch
@echo off
setlocal enabledelayedexpansion
set "filePath=yourfile.txt"
set "searchWord=yourword"
set "delay=5" REM Delay in seconds
:loop
set "lastLine="
REM Read the file line by line
for /f "usebackq delims=" %%a in ("%filePath%") do (
set "lastLine=%%a"
)
REM Check if the search word is in the last line
echo !lastLine! | findstr /i /c:"%searchWord%" >nul
if errorlevel 1 (
echo The word "%searchWord%" was NOT found in the last line.
) else (
echo The word "%searchWord%" was found in the last line.
REM Do something here if the word is found
echo Performing an action because the word was found.
)
REM Wait for specified delay
timeout /t %delay% /nobreak >nul
REM Loop back to the start
goto loop
endlocal
Key Changes and Explanation:
Delay Variable: The set "delay=5" line sets the delay for the loop (in seconds). You can change 5 to any other number to adjust how long you want to wait between checks.
Loop Label: The :loop label is defined to mark the start of the loop.
Timeout Command: The timeout /t %delay% /nobreak >nul command pauses the execution for the specified number of seconds. The >nul suppresses the output message.
Goto Loop: The goto loop command makes the script go back to the :loop label to repeat the process.
How to Use:
Save the modified script with a .bat extension (e.g., MonitorFile.bat).
Replace yourfile.txt and yourword with the appropriate file path and word you want to search for.
Run the script by double-clicking it or executing it from the Command Prompt.
This script will now keep checking the last line of the specified file every X seconds, as specified by the delay variable. Let me know if you need any more adjustments or additional features!
User
ok again
make simple script to check specific file name in folder, if found do something and delete, and wait x second goto loop
Assistant
Sure! Below is a simple Batch script that checks for a specific file name in a specified directory. If the file is found, it performs a defined action (you can customize this) and then deletes the file. The script will wait for a specified number of seconds before looping again.
Batch Script Example
batch
@echo off
setlocal enabledelayedexpansion
REM Configuration
set "folderPath=C:\path\to\your\folder" REM Change this to your folder path
set "fileName=yourfile.txt" REM Change this to the file name you want to check
set "delay=5" REM Delay in seconds
:loop
REM Check for the specific file in the folder
if exist "%folderPath%\%fileName%" (
echo File "%fileName%" found in "%folderPath%".
REM Do something here if the file is found
echo Performing an action with the file...
REM Delete the found file
del "%folderPath%\%fileName%"
echo File "%fileName%" has been deleted.
) else (
echo File "%fileName%" not found.
)
REM Wait for specified delay
timeout /t %delay% /nobreak >nul
REM Loop back to the start
goto loop
endlocal
Explanation:
Configuration:
folderPath: Set this variable to the directory where you want to check for the file.
fileName: Set this to the name of the file you want to find and manage.
delay: Set the delay for how long the script waits before the next check in seconds.
Checking for the File:
The if exist command checks if the specified file exists in the folder.
Actions if File Found:
If the file is found, it echoes a message and allows you to add any desired actions (e.g., processing the file).
The script then deletes the file using the del command.
User
make it simple and short code
Assistant
Sure! Here’s a shorter and simpler version of the Batch script that checks for a specific file in a folder, performs an action if found, deletes the file, and waits for a specified duration before repeating the check.
Simplified Batch Script
batch
@echo off
set "folderPath=C:\path\to\your\folder" REM Change this to your folder path
set "fileName=yourfile.txt" REM Change this to the file name you want to check
set "delay=5" REM Delay in seconds
:loop
if exist "%folderPath%\%fileName%" (
echo Found "%fileName%", performing action...
del "%folderPath%\%fileName%"
echo Deleted "%fileName%".
) else (
echo "%fileName%" not found.
)
timeout /t %delay% /nobreak >nul
goto loop
Key Features:
Configuration:
folderPath: Path to the folder where the file will be checked.
fileName: Name of the file to search for.
delay: Duration (in seconds) to wait before rechecking.
File Check:
Uses a single if exist statement to check for the presence of the file.
Actions:
If the file is found, it prints a message, deletes the file, and indicates that the deletion was successful.
If the file is not found, it notifies that the file is missing.
Delay:
Uses timeout to wait for the specified number of seconds, suppressing output with >nul.
Looping:
Uses goto loop to continually check for the file.
How to Use:
Save the script to a .bat file (e.g., MonitorFolder.bat).
Adjust the folderPath and fileName variables as needed.
Run the script.
This streamlined version performs the same tasks effectively while maintaining simplicity. If you need any further adjustments, feel free to ask!
User
if i no need loop in bat but make task scheduler
Assistant
If you want to run a Batch script using Task Scheduler without having it loop indefinitely, you can simplify your script to perform the desired action just once each time it runs. Below is how you can achieve that.
Simplified Batch Script
Here's a simple Batch script that checks for a specific file in a specified folder and deletes it if found, without looping:
batch
@echo off
set "folderPath=C:\path\to\your\folder" REM Change this to your folder path
set "fileName=yourfile.txt" REM Change this to the file name you want to check
if exist "%folderPath%\%fileName%" (
echo Found "%fileName%", performing action...
del "%folderPath%\%fileName%"
echo Deleted "%fileName%".
) else (
echo "%fileName%" not found.
)
Steps to Schedule the Script Using Task Scheduler
Create the Batch Script:
Open a text editor (like Notepad).
Copy and paste the script above.
Save it with a .bat extension (e.g., CheckAndDeleteFile.bat).
Open Task Scheduler:
Press Win + R, type taskschd.msc, and hit Enter to open Task Scheduler.
Create a New Task:
In Task Scheduler, click on "Create Basic Task" from the right pane.
Give your task a name and description, then click "Next."
Trigger:
Choose how frequently you want the task to run (e.g., Daily, Weekly, One time). Click "Next."
Set the specific trigger details (like start date and time), then click "Next."
Action:
Choose "Start a program" and click "Next."
In the "Program/script" field, click "Browse" and select the Batch file you created (CheckAndDeleteFile.bat).
Click "Next."
Finish:
Review your settings and click "Finish" to create the task.
Adjusting Task Settings (Optional):
Click on the newly created task in the Task Scheduler Library.
You can adjust settings such as running the task whether the user is logged on or not, running with highest privileges, etc., in the task properties.
Summary
Now, whenever the scheduled time arrives, Task Scheduler will run your Batch script, which checks for the specified file in the folder, deletes it if found, and notifies you via the console. The script is not set to loop, so it will only execute once each time it is triggered by the scheduler.
If you have any further questions or need more assistance, feel free to ask!
@echo off
set "folderPath=C:\path\to\your\folder" REM เปลี่ยนเป็นที่อยู่ไฟล์ของคุณ
set "fileName=yourfile.txt" REM เปลี่ยนเป็นชื่อไฟล์ที่คุณต้องการตรวจสอบ
if exist "%folderPath%\%fileName%" (
echo Found "%fileName%", performing action...
del "%folderPath%\%fileName%"
echo Deleted "%fileName%".
) else (
echo "%fileName%" not found.
)
To run a Batch script or any program in the background without opening a command prompt window, you can use a couple of methods. Unfortunately, the Windows Task Scheduler itself doesn't have a built-in option to run tasks hidden, but you can create a shortcut to run your script hidden. Here are two ways to do it:
Method 1: Use a VBScript Wrapper
You can create a VBScript file that calls your Batch script and runs it in the background (silently).
Create Your Batch Script:
First, ensure you have your Batch script ready (e.g. CheckAndDeleteFile.bat).
Create a VBScript:
Open Notepad and paste the following code, modifying the path to your Batch file:
vbscript
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "C:\path\to\your\CheckAndDeleteFile.bat", 0, False
Replace C:\path\to\your\CheckAndDeleteFile.bat with the actual path to your Batch script.
The 0 in the .Run method indicates that the script should run hidden.
False means that the script does not wait for the program to finish.
Save the VBScript:
Save this file with a .vbs extension, for example RunBatchHidden.vbs.
Schedule the VBScript in Task Scheduler:
Now, go to Task Scheduler and schedule the VBScript instead of the Batch file:
Follow the same steps as before but in the "Action" step, browse and select your VBScript (RunBatchHidden.vbs).
Method 2: Use start /min
If you want a simpler method without VBScript, you can modify your Batch script to start another Batch script in a minimized state. However, this still shows a command window, albeit minimized.
Modify your Batch Script:
You can use the start /min command to run your existing Batch script or command in a minimized state.
@echo off
set "folderPath=C:\path\to\your\folder" REM เปลี่ยนไปที่ที่อยู่ไฟล์ของคุณ
set "fileName=yourfile.txt" REM เปลี่ยนเป็นชื่อไฟล์ที่คุณต้องการตรวจสอบ
if exist "%folderPath%\%fileName%" (
echo Found "%fileName%", performing action...
del "%folderPath%\%fileName%"
echo Deleted "%fileName%".
) else (
echo "%fileName%" not found.
)
ในแท็บทั่วไป (General), ให้เลือก "Run whether user is logged on or not" และให้ตรวจสอบเลือก "Run with highest privileges" เพื่อให้แน่ใจว่าสคริปต์จะทำงานอย่างถูกต้อง
ทำให้แน่ใจว่าไม่ได้เลือก "Run only when user is logged on" เพื่อป้องกันไม่ให้เปิดหน้าต่างการสั่งงาน
การเลือก "Run whether user is logged on or not" และ "Run with highest privileges" จะทำให้ Task Scheduler รันโปรแกรมในพื้นหลังได้ โดยที่ไม่จำเป็นต้องแสดงหน้าต่าง Command Prompt
If tail is not available, you can use this alternative script to achieve the same behavior without it:
batch
@echo off
setlocal enabledelayedexpansion
set "filePath=yourfile.txt"
set "searchWord=yourword"
set "lastLine="
REM Read the file line by line
for /f "usebackq delims=" %%a in ("%filePath%") do (
set "lastLine=%%a"
)
REM Check if the search word is in the last line
echo !lastLine! | findstr /i /c:"%searchWord%" >nul
if errorlevel 1 (
echo The word "%searchWord%" was NOT found in the last line.
) else (
echo The word "%searchWord%" was found in the last line.
REM Do something here if the word is found
echo Performing an action because the word was found.
)
endlocal
In this alternative method:
The for /f loop reads the file line by line, and the lastLine variable is updated with the current line each iteration. Thus, after the loop, lastLine will contain the last line of the file.
Saving and Running the Script
Copy the desired script into a text file and save it with a .bat extension (e.g., find_word.bat).
Replace yourfile.txt and yourword with the appropriate file path and search word.
Double-click the .bat file to execute it.
If you have any further questions or need additional modifications, feel free to ask!
Delay:
The timeout command causes the script to wait for the specified number of seconds before looping back to check for the file again.
Looping:
The goto loop command sends the script back to the beginning of the loop for continuous checking.
How to Use:
Copy the script into a text file and save it with a .bat extension (e.g., MonitorFolder.bat).
Replace C:\path\to\your\folder and yourfile.txt with the actual path and filename you want to monitor.
Run the script by double-clicking the .bat file or executing it from the Command Prompt.
This script will keep checking for the specified file every X seconds, and perform the actions defined in the script if the file is found. If you have any questions or need further modifications, feel free to ask!
@echo off
set "folderPath=C:\path\to\your\folder" REM Change this to your folder path
set "fileName=yourfile.txt" REM Change this to the file name you want to check
start /min cmd /c "if exist "%folderPath%\%fileName%" (
echo Found "%fileName%", performing action...
del "%folderPath%\%fileName%"
echo Deleted "%fileName%".
) else (
echo "%fileName%" not found.
)"
Schedule the Original Batch Script:
In Task Scheduler, you can schedule the modified Batch script that contains the start /min command. This will minimize the command prompt when it runs.
Summary
VBScript: Use it to run your Batch script completely hidden.
Batch with start /min: Run your Batch script in a minimized state; it will still appear on the taskbar but will not take up screen space.
Choose the first method if you want the program to run completely in the background without showing a window. Let me know if you need further assistance!