Windows CMD windows

  • make default window bigger: right click menu on title bar, Defaults > Layout; Screen Buffer size 300×100

basic operation

determine the file itself

@echo Full path and filename: %~f0
@echo Drive: %~d0
@echo Path: %~p0
@echo Drive and path: %~dp0
@echo Filename without extension: %~n0
@echo Filename with    extension: %~nx0
@echo Extension: %~x0
@echo Filename as given on command line: %0
@echo Filename as given on command line minus quotes: %~0
@REM Build from parts
@SET drv=%~d0
@SET pth=%~p0
@SET fpath=%~dp0
@SET fname=%~n0
@SET ext=%~x0
@echo Simply Constructed name: %fpath%%fname%%ext%
@echo Fully  Constructed name: %drv%%pth%%fname%%ext%

call python file with same name

@echo off
call python

call custom python to run python file with passing parameter (Basic version)

set CustPython=D:\Pipeline\App_Win\Python27x64\
%CustPython%python.exe %1
import os,sys
input_count = len(sys.argv)
print('Inputs Count: {0}'.format(input_count))
if input_count>1:
    print('Passing File Path: {0}'.format(sys.argv[1]))

call custom python to run python file with passing parameter (Advanced version)

:: dont type out cmds in cmd window
@echo off
set CustPython=R:\Pipeline\App_Win\Python27x64\

:: Check for Python Installation
python --version 2>NUL
if errorlevel 1 goto NoPython

::====== hasPython ======
call python.exe %1 && goto done
goto console

::====== noPython ======
IF EXIST %CustPython% (
  echo %CustPython%
  call %CustPython%python.exe %1 && goto done
  goto console
) ELSE (
  echo Error^: Python not detected  
import os,sys
input_count = len(sys.argv)
print('Inputs Count: {0}'.format(input_count))
if input_count>1:
    print('Passing File Path: {0}'.format(sys.argv[1]))
    sys.exit(0) # 0: success, 1-127: bad error
    print('Error: No File Passing to Python')

copy file and directory

copy d:\file1.txt g:\dir1\file1.txt
xcopy d:\download g:\dn /s /e

REM "copy without asking, replace by default
copy /y d:\file1.txt g:\dir1\file1.txt

edit file and directory attribute

attrib +r +a +s +h secureFile.txt
  • EQU, NEQ, substring, combine string
    @echo off
    REM YourPythonFileName_w.bat will launch without console
    REM YourPythonFileName.bat will launch with console
    set file=%~n0
    if "%file:~-2%" equ "_w" (
      start pythonw %~dp0%file:~0,
      goto done
    call python
  • the > use as output direction
  • 1>, and 2> means if the cmd has 2 output vales, and map each output to separate place
    • stream 1 is the standard input/output stream, 2 is the standard error stream
  • 2> nul, means mute the 2nd output value. only catch 1st output result
  • both call and start or direct app.exe can start a process, normally no difference
  • but if you want to start another batch file, then
    • CALL will start it in the same window and the called batch has access to the same variable context.
    • START will create a new cmd.exe for the called batch and without /b it will open a new window. As it's a new context, variables can't be shared.
      • Starting a new process with CALL, is very similar to running START /wait, in both cases the calling script will (usually) pause until the second script has completed.


  • create a email with content python version (the main code block)
    # rough support code for reference
    config['appPath']['email'] = [r'C:\Program Files\Microsoft Office\Office*\OUTLOOK.EXE']
    # main code
    app = self.getOptionPath(config['appPath'], 'email') # the outlook app path
    address_list = ['']
    subject = 'Daily Feedback'
    text_list = ['line 1', 'line 2']
    cmd = '"{0}" /c ipm.note /m "{1}&subject={2}&body={3}"'.format(app, ';'.join(address_list), subject, '\n'.join(text_list))
    if os.path.isfile(app):
    # support function for reference
        def getOptionPath(self, dict, name, all=0):
            # updated: 2019.01.09
            if name not in dict.keys():
                print('Dict has no key: {0}'.format(name))
            option_list = []
            if not isinstance(dict[name], (list,tuple)):
                option_list = [ dict[name] ]
                option_list = dict[name]
            if all == 0:
                found = None
                for option in option_list:
                    if '*' in option:
                        # wildchar search
                        import glob
                        sub_option_list = glob.glob(option)
                        if len(sub_option_list) > 0:
                            sorted_option_list = sorted(sub_option_list)
                            print('Scaning options:\n'+'\n'.join(sorted_option_list))
                            found = sorted_option_list[-1]
                        if os.path.exists(option):
                            found = option
                if found is not None:
                    found = found.replace('\\','/')
                print('found: {0}'.format(found))
                return found
                all_option = []
                for option in option_list:
                    if '*' in option:
                        # wildchar search
                        import glob
                        sub_option_list = glob.glob(option)
                        all_option.extend(sorted(sub_option_list, reverse=1))
                        if os.path.exists(option):
                standard_path_option = []
                for each_path in all_option:
                    standard_path = each_path.replace('\\','/')
                    if standard_path not in standard_path_option:
                return standard_path_option
  • outlook attach file (/c imp.note need or not need?)
    outlook.exe /c ipm.note /a "FileAttachPathName" /m ""
  • export out all system environment variable
    set > filename.txt
  • display all or a environment variable value
    set path
    echo %PATH%
    reg query HKEY_CURRENT_USER\Environment /v path
    reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v path
  • cust system var setup
    • Method 1: in run > SystemPropertiesAdvanced : environment
      Computer → Properties → Advanced System Settings → Advanced (tab) → Environment Variables
      // For user variable use
      path = %PATH%;D:/yourCustomPath
      path = D:/yourCustomPath
      path = C:/OtherPath;C:/AnotherOtherPath;D:/yourCustomPath
      // For system variable use
      path = C:/OtherPath;C:/AnotherOtherPath;D:/yourCustomPath
    • Method 2: in command window
      REM set variable for current session environment (means not working after you close this cmd)
      set z_sys=D:/z_sys
      REM set permanent variable for user environment
      setx z_sys D:/z_sys
      REM set permanent variable for system environment with admin rights
      setx /M z_sys D:/z_sys
    • Method 3.1: into register editor by cmd
      REM set permanent variable for user environment
      reg add HKEY_CURRENT_USER\Environment /v z_sys /d "D:/z_sys" /f
      REM set permanent variable for system environment
      reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment /v z_sys /d "D:/z_sys" /f
    • Method 3.2: into register editor by python with Extra Precision update instead of dump system environment value into user environment value
      # because the path will give both user path and system path, 
      # here is more detail on update only user path content without having system path repeated in user path
      import sys, subprocess
      userPathValue=subprocess.check_output("reg query HKCU\Environment /v path") # get original user path value
      userPath = userPathValue.split('REG_SZ')[-1].strip() # get clean value of the user path
      myExtraPath = "D:/"
      os.system('reg add HKCU\Environment /v path /d "'+ userPath + ';' + myExtraPath +'" /f')
    • Method 4: insert register entry by reg file
      Windows Registry Editor Version 5.00
  • get cpu core
    wmic cpu get NumberOfCores
  • open explorer and select a item in path
    explorer /select, D:\zTmp\myFileOrFolder
  • force delete a file
    del /q /f "\FilePath\file.ext"
  • rename file
    rename A.ext B.ext

CMD quick actions

  • clean run cmd list
    reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU" /va /f >nul 2>nul
  • cleanup recent file listing
    del %appdata%\microsoft\windows\recent\automaticdestinations\*
    del %appdata%\Microsoft\Windows\Recent\*

Batch file

  • add
    Windows Registry Editor Version 5.00 
    REG ADD HKCR\Control Panel\Desktop /v Wallpaper /t REG_SZ /d "%WINDIR%\Web\Wallpaper\aqua1024.jpg" /f
  • remove
  • empty

Windows specific command

  • list all the service
    net start


    sc query type= service
  • start telnet server
    net start telnet
  • list all port
    netstat -a
REM "format NTFS drive to FAT32 drive"
format /FS:FAT32 /Q X:
management panel
services.msc services panel
compmgmt.msc computer manager
devmgmt.msc device manager
fonts fonts folder
control control panel
control userpasswords2 user manager
control date/time date and time
control desktop display property
control color appearance theme
control panel control somefile.cpl,<optional arguments>
access.cpl Accessibility controls Keyboard(1), Sound(2), Display(3), Mouse(4), General(5)
appwiz.cpl Add/Remove Programs
desk.cpl Display properties Themes(5), Desktop(0), Screen Saver(1), Appearance (2), Settings(3)
hdwwiz.cpl Add hardware
inetcpl.cpl Configure Internet Explorer and Internet properties General(0), Security(1), Privacy(2), Content(3), Connections(4), Programs(5), Advanced(6)
intl.cpl Regional settings Regional Options(1), Languages(2), Advanced(3)
joy.cpl Game controllers
main.cpl Mouse properties and settings Buttons(0), Pointers(1), Pointer Options(2), Wheel(3), Hardware(4)
main.cpl,@1 Keyboard properties Speed(0), Hardware (1)
mmsys.cpl Sounds and Audio Volume(0), Sounds(1), Audio(2), Voice(3), Hardware(4)
ncpa.cpl Network properties
nusrmgr.cpl User accounts
powercfg.cpl Power configuration Power Schemes, Advanced, Hibernate, UPS (Tabs not indexed)
sysdm.cpl System properties General(0), Computer Name(1), Hardware(2), Advanced(3), System Restore(4), Automatic Updates(5), Remote (6)
telephon.cpl Phone and modem options Dialing Rules(0), Modems(1), Advanced(2)
timedate.cpl Date and time properties Date & Time(0), Time Zone(1), Internet Time (no index)


set default sound device nircmd.exe setdefaultsounddevice “Speakers_TheNameInPanel”
close folder windows nircmd.exe win close class “CabinetWClass”
close empty cmd windows nircmd.exe win close title “C:\Windows\system32\cmd.exe”
off monitor nircmd.exe monitor off
off computer nircmd.exe exitwin poweroff force
pop dialog nircmd.exe trayballoon “Hello” “This is a test…” “shell32.dll,22” 15000
windows control

MS sysinternal suite

  • techwiki/dos.txt
  • Last modified: 2022/05/04 07:06
  • by ying