techwiki:dos

Differences

This shows you the differences between two versions of the page.


Previous revision
techwiki:dos [2024/01/11 12:58] (current) – [PowerShell] ying
Line 1: Line 1:
 +====== Windows CMD windows ======
  
 +  * make default window bigger: right click menu on title bar, Defaults > Layout; Screen Buffer size 300x100
 +
 +====== basic operation ======
 +
 +determine the file itself <code dos>
 +
 +@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
 +@SETLOCAL
 +@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%
 +@ENDLOCAL
 +pause
 +</code>
 +
 +**add other exe like python into path of cmd**
 +  * note: put added path of python in front of %path% works, while behind it not work
 +  * code <code dos>
 +SET PATH=D:\App\Python;D:\App_Dev\PortableGit\bin;%PATH%
 +</code>
 +
 +**call python file with same name**<code dos>
 +@echo off
 +call python %~dp0%~n0.py
 +pause
 +</code>
 +
 +**call custom python to run python file with passing parameter (Basic version)**<code dos SameNameAsPyFile.bat>
 +set CustPython=D:\Pipeline\App_Win\Python27x64\
 +%CustPython%python.exe %~dp0%~n0.py %1
 +pause
 +</code>
 +
 +<code python SameNameAsPyFile.py>
 +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]))
 +</code>
 +
 +**call custom python to run python file with passing parameter (Advanced version)**<code dos SameNameAsPyFileAdvanced.bat>
 +:: 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 %~dp0%~n0.py %1 && goto done
 +goto console
 +
 +::====== noPython ======
 +:NoPython
 +IF EXIST %CustPython% (
 +  echo %CustPython%
 +  call %CustPython%python.exe %~dp0%~n0.py %1 && goto done
 +  goto console
 +) ELSE (
 +  echo Error^: Python not detected  
 +)
 +
 +:console
 +pause
 +:done
 +</code>
 +
 +<code python SameNameAsPyFileAdvanced.py>
 +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
 +else:
 +    print('Error: No File Passing to Python')
 +    sys.exit(1)
 +</code>
 +
 +copy file and directory
 +<code dos>
 +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
 +</code>
 +
 +edit file and directory attribute
 +<code dos>
 +attrib +r +a +s +h secureFile.txt
 +</code>
 +
 +===== String and Logic Operation =====
 +
 +  * EQU, NEQ, substring, combine string <code dos>
 +@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,-2%.py
 +  goto done
 +)
 +call python %~dp0%~n0.py
 +pause
 +:done
 +</code>
 +
 +===== cmd output direction =====
 +
 +  * 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
 +
 +
 +===== start a process =====
 +
 +  * 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.
 +
 +
 +**Outlook**
 +
 +  * create a email with content python version (the main code block) <code python>
 +# 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 = ['test@test.com']
 +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):
 +    print(cmd)
 +    subprocess.Popen(cmd)
 +
 +# 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))
 +            return
 +        option_list = []
 +        if not isinstance(dict[name], (list,tuple)):
 +            option_list = [ dict[name] ]
 +        else:
 +            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]
 +                        break
 +                else:
 +                    if os.path.exists(option):
 +                        found = option
 +                        break
 +            if found is not None:
 +                found = found.replace('\\','/')
 +            print('found: {0}'.format(found))
 +            return found
 +        else:
 +            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))
 +                else:
 +                    if os.path.exists(option):
 +                        all_option.append(option)
 +            standard_path_option = []
 +            for each_path in all_option:
 +                standard_path = each_path.replace('\\','/')
 +                if standard_path not in standard_path_option:
 +                    standard_path_option.append(standard_path)
 +            print(standard_path_option)
 +            return standard_path_option
 +</code>
 +  * outlook attach file (/c imp.note need or not need?) <code dos>outlook.exe /c ipm.note /a "FileAttachPathName" /m "email@addresses.com&cc=&subject=&body="</code>
 +    * ref: https://www.slipstick.com/outlook/how-to-use-outlooks-command-line-switches/
 +===== system operation =====
 +
 +  * assign a path with driver letter: Subst
 +    * ref: https://technet.microsoft.com/en-us/library/bb491006.aspx
 +
 +  * export out all system environment variable <code dos>set > filename.txt</code>
 +  * display all or a environment variable value <code dos>set
 +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
 +</code>
 +
 +  * cust system var setup
 +    * Method 1: in run > SystemPropertiesAdvanced : environment<code>
 +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
 +</code>
 +    * Method 2: in command window <code dos>
 +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
 +</code>
 +    * Method 3.1: into register editor by cmd <code>
 +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
 +</code>
 +    * Method 3.2: into register editor by python with Extra Precision update instead of dump system environment value into user environment value <code python>
 +# 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')
 +</code>
 +    * Method 4: insert register entry by reg file <code>
 +Windows Registry Editor Version 5.00
 +
 +[HKEY_CURRENT_USER\Environment]
 +"Path"="%PATH%;c:\\bin"
 +</code>
 +
 +  * get cpu core <code>
 +wmic cpu get NumberOfCores
 +</code>
 +
 +===== explorer operation =====
 +
 +  * open explorer and select a item in path <code>
 +explorer /select, D:\zTmp\myFileOrFolder
 +</code>
 +
 +===== file operation =====
 +
 +  * force delete a file <code>
 +del /q /f "\FilePath\file.ext"
 +</code>
 +  * rename file <code>rename A.ext B.ext</code>
 +====== CMD quick actions ======
 +
 +  * clean run cmd list \\ <code>
 +reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU" /va /f >nul 2>nul
 +</code>
 +  * cleanup recent file listing \\ <code>
 +del %appdata%\microsoft\windows\recent\automaticdestinations\*
 +del %appdata%\Microsoft\Windows\Recent\*
 +</code>
 +
 +====== Batch file ======
 +===== Batch for registery edit =====
 +  * add \\ <code>
 +regedit 
 +add: 
 +Windows Registry Editor Version 5.00 
 +[HKEY_CURRENT_USER\SomeKey]
 +"SomeStringValue"="Hello" 
 +
 +e.g
 +REG ADD HKCR\Control Panel\Desktop /v Wallpaper /t REG_SZ /d "%WINDIR%\Web\Wallpaper\aqua1024.jpg" /f
 +</code>
 +  * remove \\ <code>
 +[-HKEY_CURRENT_USER\SomeKey]  
 +</code>
 +  * empty \\ <code>
 +[HKEY_CURRENT_USER\SomeKey]
 +"SomeStringValue"=-
 +</code>
 +
 +====== Windows specific command ======
 +
 +  * list all the service <code dos>net start</code> or <code dos>sc query type= service</code>
 +  * start telnet server <code dos>net start telnet</code>
 +
 +  * list all port <code>netstat -a</code>
 +===== Dos disk related operation =====
 +<code dos>
 +REM "format NTFS drive to FAT32 drive"
 +format /FS:FAT32 /Q X:
 +
 +</code>
 +
 +===== control panels and admin tools =====
 +
 +  * windows component window can be open with cmds like explorer.exe,control.exe,rundll32.exe, like open network connection window can be
 +    * code (canonical name, GUID, module dll)<code>
 +explorer.exe shell:ConnectionsFolder
 +explorer.exe shell:::{992CFFA0-F557-101A-88EC-00DD010CCC48}
 +control.exe netconnections
 +ncpa.cpl
 +control ncpa.cpl
 +rundll32.exe shell32.dll,Control_RunDLL ncpa.cpl
 +
 +control.exe sysdm.cpl,,3
 +control /name Microsoft.NetworkAndSharingCenter /page Advanced
 +control /name Microsoft.InternetOptions /page 4
 +explorer shell:::{ED834ED6-4B5A-4bfe-8F11-A626DCB6A921} -Microsoft.Personalization\pageWallpaper
 +
 +# folder option
 +control /name Microsoft.FolderOptions
 +control folders
 +rundll32.exe shell32.dll,Options_RunDLL 0
 +# folder option - view
 +rundll32.exe shell32.dll,Options_RunDLL 7
 +</code>
 +    * ref: 
 +      * https://www.lifewire.com/command-line-commands-for-control-panel-applets-2626060
 +      * https://docs.microsoft.com/en-us/windows/win32/shell/controlpanel-canonical-names
 +      * https://www.tenforums.com/tutorials/86339-list-commands-open-control-panel-items-windows-10-a.html
 +      * https://coderwall.com/p/3awvka/a-list-of-run-commands-for-windows-7
 +
 +^ 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)|
 +
 +
 +===== Windows 3rd party command-line utility =====
 +
 +** NirCmd **
 +
 +^ download | http://www.nirsoft.net/utils/nircmd.html |
 +^ 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 | http://nircmd.nirsoft.net/win.html |
 +
 +** MS sysinternal suite **
 +
 +  * http://technet.microsoft.com/en-us/sysinternals/bb545027
 +
 +
 +===== PowerShell =====
 +
 +  * enable script run on powershell
 +    * run powershell as admin, then <code>set-executionpolicy remotesigned</code>
 +
 +  * add ssh <code>
 +# Install the OpenSSH Client
 +Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
 +
 +# Install the OpenSSH Server
 +Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
 +</code>
 +    * after install ssh, go Run services, and set ssh server to startup automatic, then start ssh server
 +    * you need put vim on server machine to be able to edit text file:
 +      * https://www.vim.org/download.php