\\ Amazon パソコン・周辺機器 クーポンをチェックしよう!! //

【Ultimate Guide】List of Commands Usable in Batch Files and How to Utilize Them

Batch files are essential tools for automation and task efficiency in Windows environments. They simplify daily operations and allow repetitive tasks to be executed instantly, making them highly attractive for users seeking to enhance their productivity.

In this article, we will cover a comprehensive range of topics from the basics of batch files, a list of available commands, to practical applications. By reading this, even beginners will be able to create basic batch files and apply advanced command usage quickly. Maximize the power of batch files to improve your daily workflow efficiently.

Basics of Batch Files

What is a Batch File?

A batch file is a script that executes a series of Windows commands in bulk. It automates routine tasks, thereby increasing work efficiency.

How to Create a Basic Batch File

For those who want to learn in detail about creating batch files, please refer to our article “Beginner’s Guide: How to Create Batch Files and Important Tips for Use 【2024 Latest】”. This guide provides a step-by-step explanation of creating batch files and important precautions in an easy-to-understand manner.

How to Execute a Batch File

To execute a batch file, you can run it with administrative privileges by right-clicking and selecting “Run as administrator” or use shortcuts for convenient execution methods. For more details, please refer to the linked article above.

List of Commands Usable in Batch Files

Below is a comprehensive list of commands that can be used in batch files:

CommandDescription
ARPDisplays or modifies the mapping between IP and MAC addresses
ASSOCDisplays or modifies file extension associations
ATTRIBDisplays or changes file and directory attributes
bcdbootCreates or repairs boot configuration data
cdDisplays or changes the current directory
chkdskChecks the disk status and repairs errors
chkntfsDisplays or modifies the automatic disk check settings
clipCopies command output to the clipboard
clsClears the screen
cmdkeyManages stored user names and passwords
colorChanges the console text and background colors
compCompares files
compactDisplays or alters the compression settings of files and directories
copyCopies files
dateDisplays or sets the date
defragPerforms disk defragmentation
delDeletes files
dirDisplays directory contents
diskpartManages disk partitions
dispdiagCollects display diagnostic information
echoDisplays messages or toggles command echoing
endlocalEnds localization of environment variables
exitExits the command prompt
fcCompares files and displays differences
findSearches for a string in files
findstrSearches for strings using advanced patterns
forExecutes a loop of commands
forfilesExecutes a command on a file or set of files
formatFormats disks
ftpPerforms FTP operations
ftypeDisplays or modifies file types associated with extensions
getmacDisplays MAC addresses
gotoJumps to a labeled line in the batch file
gpresultDisplays applied group policies
gpupdateUpdates group policies
hostnameDisplays the computer name
icaclsDisplays or modifies access control lists for files and directories
ifPerforms conditional processing
ipconfigDisplays network configuration
ipconfig /allDisplays detailed network configuration
ipconfig /displaydnsDisplays DNS resolver cache
ipconfig /flushdnsFlushes the DNS resolver cache
ipconfig /registerdnsRegisters DNS names
ipconfig /releaseReleases the IP address
ipconfig /renewRenews the IP address
irftpStarts infrared file transfer
labelDisplays or sets a volume label
logoffLogs off the current user
md / mkdirCreates directories
mklinkCreates symbolic or hard links
mmcStarts Microsoft Management Console
modeConfigures system devices
moreDisplays output one screen at a time
moveMoves files
msgSends messages to users
msiexecManages Windows Installer operations
msinfo32Displays system information
mstscStarts Remote Desktop Connection
nbtstatDisplays NetBIOS over TCP/IP statistics
netshConfigures network settings
netstatDisplays network connections
nfsadminManages NFS services
nlbmgrStarts Network Load Balancing Manager
nslookupQueries DNS servers
pathDisplays or sets command search path
pausePauses the batch file execution
perfmonStarts Performance Monitor
pingChecks network connectivity
pnputilManages Plug and Play drivers
printPrints text files
prnjobsManages printer jobs
prnmngrManages printers
prnportManages printer ports
prnqctlControls printer queues
promptChanges the command prompt display
pushdSaves the current directory and changes to a new one
qappsrv / query process / query session / query user / quserDisplays process, session, and user information
rd / rmdirRemoves directories
reg / reg add / reg compare / reg delete / reg export / reginiManages registry settings
remAdds comments in the batch file
renRenames files
replaceReplaces files
robocopyRobust file and directory copy
rpcinfo / rpcpingDisplays or tests RPC service connections
rundll32Executes functions from DLLs
scManages services
schtasks / schtasks / change / create / delete / end / query / runManages scheduled tasks
select disk / select partition / select vdiskSelects disks, partitions, or virtual disks (used with diskpart)
setDisplays or sets environment variables
sfcScans and repairs system files
shutdownShuts down or restarts the system
sortSorts input
startStarts programs or commands in a new window
systeminfoDisplays detailed system information
taskkillTerminates tasks by process ID or image name
tasklistDisplays a list of currently running processes
telnetInitiates Telnet sessions
timeDisplays or sets the system time
timeoutWaits for a specified time period
titleSets the title for the command prompt window
tlntadmnManages Telnet services
treeGraphically displays directory structure
tzutilDisplays or sets the time zone
volDisplays the disk volume label and serial number
whereLocates and displays files in the path
whoamiDisplays the current user name
wmicDisplays WMI information
xcopyCopies files and directories, including subdirectories

Practical Examples of Batch Files

Example 1: Collecting System Information and Saving Logs

This example demonstrates how to create a batch file that automatically collects system information and saves it to a log file by combining multiple commands.

Code Example:

@echo off
rem Batch file to collect system information and save to a log file

echo Collecting system information...
systeminfo > systeminfo.log

echo Retrieving network settings...
ipconfig /all >> systeminfo.log

echo Listing installed programs...
wmic product get name,version >> systeminfo.log

echo Collection complete. Please check systeminfo.log.
pause

Explanation of Each Line:

  • @echo off: Hides the command inputs.
  • rem: Adds a comment to describe the code.
  • echo: Displays messages to the user.
  • systeminfo > systeminfo.log: Retrieves system information and overwrites systeminfo.log.
  • ipconfig /all >> systeminfo.log: Retrieves network settings and appends to systeminfo.log.
  • wmic product get name,version >> systeminfo.log: Lists installed programs and appends to systeminfo.log.
  • pause: Pauses execution and waits for user input.

Execution Result:

When executed, this batch file creates a systeminfo.log file in the same folder, containing system information, network settings, and a list of installed programs.

Example 2: Automating Regular Backups

This example shows how to create a batch file that backs up a specified folder to another location automatically.

Code Example:

@echo off
rem Batch file to perform regular backups

set SOURCE=C:\Users\YourName\Documents
set DEST=D:\Backup\Documents_%DATE:~0,4%%DATE:~5,2%%DATE:~8,2%

echo Starting backup...
xcopy "%SOURCE%" "%DEST%" /E /H /C /I

echo Backup complete. Please check %DEST%.
pause

Explanation of Each Line:

  • set SOURCE=...: Sets the source folder for the backup.
  • set DEST=...: Sets the destination folder, including the date in YYYYMMDD format.
  • xcopy: Copies files and directories with specific options:
  • /E: Copies all subdirectories, including empty ones.
  • /H: Copies hidden and system files.
  • /C: Continues copying even if errors occur.
  • /I: Assumes the destination is a directory if it does not exist.

Execution Result:

Running this batch file creates a folder named D:\Backup\Documents_YYYYMMDD and copies all contents from C:\Users\YourName\Documents to it.

Troubleshooting

Error 1: Batch File Does Not Execute

Issue:

Double-clicking the batch file does nothing, or the window appears briefly and closes immediately.

Solutions:

  1. Add pause Command:
    Add pause at the end of the batch file to prevent the window from closing immediately.
   @echo off
   echo Hello, World!
   pause
  1. Check File Extension:
    Ensure the file has a .bat extension, not .bat.txt.

Error 2: Command Not Found

Expected Behavior:

Running the batch file results in an error like 'command' is not recognized as an internal or external command, operable program or batch file.

Solutions:

  1. Verify Command Spelling:
    Check for typos in the command names.
  2. Check PATH Environment Variable:
    Ensure the necessary commands are included in the PATH environment variable.
  3. Use Full Path:
    Specify the full path of the command.
   @echo off
   "C:\Windows\System32\ipconfig.exe"
   pause

Debugging Methods

Steps:

  1. Enable Echo:
    Remove or comment out @echo off to display executed commands.
  2. Redirect Error Output to Log:
    Capture errors by redirecting output.
   @echo off
   command > output.log 2> error.log
  1. Step Execution:
    Insert pause between commands to verify each step.

Best Practices and Precautions

Tips for Creating Efficient Batch Files

  1. Use Comments:
    Utilize rem or :: to add comments explaining the code.
  2. Use Variables:
    Define variables with the set command to enhance reusability.
  3. Implement Error Handling:
    Use if statements and error levels to manage errors.
  4. Modularize:
    Separate common functionalities into different batch files and call them using the call command.

Specific Example:

@echo off
rem Script to backup user folders

set SOURCE=%USERPROFILE%
set DEST=D:\Backup\%USERNAME%_%DATE:~0,4%%DATE:~5,2%%DATE:~8,2%

if not exist "%DEST%" (
    mkdir "%DEST%"
)

xcopy "%SOURCE%" "%DEST%" /E /H /C /I
if %ERRORLEVEL% NEQ 0 (
    echo Backup failed.
) else (
    echo Backup completed successfully.
)
pause

Security Precautions

  1. Use Trusted Commands Only:
    Avoid running unknown commands or scripts.
  2. Handle Administrative Privileges Carefully:
    Execute with administrative rights only when necessary to prevent misuse.
  3. Avoid Hardcoding Passwords:
    Do not embed sensitive information like passwords directly in scripts.

Conclusion

In this article, we covered practical examples of batch files, troubleshooting common issues, and best practices for creating efficient and secure batch scripts. By leveraging batch files, you can streamline daily tasks and make effective use of your time.

As a next step, consider automating more complex tasks or combining batch files with other scripting languages to further enhance your automation capabilities.

Related Information

  • Beginner’s Guide: How to Create Batch Files and Important Tips for Use 【2024 Latest】
  • FAQ (Frequently Asked Questions)
  • Q1: Why can’t I run the batch file by double-clicking?
    • A1: Ensure the file has a .bat extension and not .bat.txt. Also, check if security software is blocking the execution.
  • Q2: My batch file shows garbled Japanese characters. What should I do?
    • A2: Save the batch file with ANSI encoding. Some editors default to UTF-8, which may cause encoding issues.
  • Q3: How can I run commands that require administrative privileges automatically?
    • A3: Create a shortcut for the batch file, go to its properties, and set it to “Run as administrator”. Alternatively, use Task Scheduler to run the batch file with elevated privileges.

References and Related Links

Tamaglo

Thank you for reading until the end!