0% found this document useful (0 votes)
1K views

Windows CMD Command Syntax

Windows CMD Command Syntax SS64.Com(1)

Uploaded by

awais
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Windows CMD Command Syntax

Windows CMD Command Syntax SS64.Com(1)

Uploaded by

awais
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 161

Windows CMD Command Syntax | SS64.

com

(  SS64  ) CMD Links


Search

Windows CMD Shell Command Line Syntax


Parameters Command Line Arguments %1 %~f1
RUN commands Start | Run commands.
MMC Snap-ins Admin commands.
Shell: folder Shortcuts to key folders.
ProfileFolders Location of User profile folders (XP / W7 / W10).
Env. Variables Create/read environment variables.
Redirection Spooling output to a file, piping input.
AND/OR Logic Conditional Execution (If-Then-Else)
Loops Loops and Subroutines.
functions How to package blocks of code.
Macros Embed blocks of code in a variable.

Services      List of Windows 7 (SP1) Services.


Evaluating expressions
Using brackets to Group and expand expressions.
Delayed Expansion Variables within loops.
Escape chars, delimiters and quotes
SET /A Environment variable arithmetic.
VarSubstring Extract part of a variable (substring).
VarSearch Search & replace part of a variable.
RANDOM Random Numbers.
Wildcards Match multiple files.
Batch Files
Run a script How to run a script.
Elevate Run with elevated permissions (As Admin).
DateMath Add or subtract days from any date.
DeQuote Remove quotes from a string.
DelOlder Delete files more than n days old.
GenChr.cmd Generate an ASCII/Unicode character.
GetDate.cmd Get todays date (any region, any OS.)
GetTime.cmd Get the time now.
GetGMT.cmd Time adjusted to Greenwich Mean Time.
StampMe.cmd Rename a file with the date/time.
tdiff.cmd Time difference in Hours/Minutes.
Which.cmd Display full path to any command.
xlong.cmd Find filenames that exceed the 256 char pathname limit.
Reference/How to
Autoexec Run commands at startup.
Slow Browsing Speed up network browsing.
Desktop Heap Memory configuration.
Long Filenames NTFS filename issues.
Display DPI Monitor size settings.
CMD Shell Working in the Windows CMD shell.
CMD Internal Commands that are Internal to the CMD shell.
File Shares Organising shared files.
Keyboard CMD Keyboard shortcuts.
NoDrives Hide mapped drives from Windows Explorer.
Printing Printer connections and print drivers.
Recovery The Recovery Console.
Reg Tweaks Registry tweaks and settings.
BuiltIn Groups Built-In Users and Security Groups.
Groups Local Domain groups, Global and Universal groups.
64Bit Detect 64 bit vs 32 bit Windows.
Windows Key Shortcut keys

Related:

Microsoft.com - Command-line Reference


Recommended books and Websites

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax.html[8/24/2017 10:32:39 AM]


SS64 | Command line reference

(  SS64  ) Search

Command line reference – Database and OS scripting.

Bash macOS CMD PowerShell

Access VB Script Oracle SQL Server

ASCII Convert MB/GB Forum Passwords

About/contact - Last update: August 23rd
Copyright © SS64.com 1999-2017, some rights reserved.

https://ss64.com/[8/24/2017 10:32:42 AM]


An A-Z Index of the Windows CMD command line | SS64.com

(  SS64  ) Links Syntax


Search

An A-Z Index of the Windows CMD command line


ADDUSERS Add or list users to/from a CSV file
ADmodcmd Active Directory Bulk Modify
ARP Address Resolution Protocol
ASSOC Change file extension associations•
ASSOCIAT One step file association
AT Schedule a command to run at a specific time
ATTRIB Change file attributes
b
BCDBOOT Create or repair a system partition
BCDEDIT Manage Boot Configuration Data
BITSADMIN Background Intelligent Transfer Service
BROWSTAT Get domain, browser and PDC info
c
CACLS Change file permissions
CALL Call one batch program from another•
CERTREQ Request certificate from a certification authority
CERTUTIL Utility for certification authority (CA) files and services
CD Change Directory - move to a specific Folder•
CHANGE Change Terminal Server Session properties
CHKDSK Check Disk - check and repair disk problems
CHKNTFS Check the NTFS file system
CHOICE Accept keyboard input to a batch file
CIPHER Encrypt or Decrypt files/folders
CleanMgr Automated cleanup of Temp files, recycle bin
CLIP Copy STDIN to the Windows clipboard
CLS Clear the screen•
CMD Start a new CMD shell
CMDKEY Manage stored usernames/passwords
COLOR Change colors of the CMD window•
COMP Compare the contents of two files or sets of files
COMPACT Compress files or folders on an NTFS partition
COMPRESS Compress one or more files
CONVERT Convert a FAT drive to NTFS
COPY Copy one or more files to another location•
Coreinfo Show the mapping between logical & physical processors
CSCcmd Client-side caching (Offline Files)
CSVDE Import or Export Active Directory data
d
DATE Display or set the date•
DEFRAG Defragment hard drive
DEL Delete one or more files•
DELPROF Delete user profiles
DELTREE Delete a folder and all subfolders
DevCon Device Manager Command Line Utility
DIR Display a list of files and folders•
DIRQUOTA File Server Resource Manager Disk quotas
DIRUSE Display disk usage
DISKPART Disk Administration
DISKSHADOW Volume Shadow Copy Service
DISKUSE Show the space used in folders
DOSKEY Edit command line, recall commands, and create macros
DriverQuery Display installed device drivers
DSACLs Active Directory ACLs
DSAdd Add items to active directory (user group computer)
DSGet View items in active directory (user group computer)
DSQuery Search for items in active directory (user group computer)
DSMod Modify items in active directory (user group computer)
DSMove Move an Active directory Object
DSRM Remove items from Active Directory
Dsmgmt Directory Service Management
e
ECHO Display message on screen•
ENDLOCAL End localisation of environment changes in a batch file•
ERASE Delete one or more files•
EVENTCREATE Add a message to the Windows event log
EXIT Quit the current script/routine and set an errorlevel•
EXPAND Uncompress CAB files
EXPLORER Open Windows Explorer
EXTRACT Uncompress CAB files
f
FC Compare two files
FIND Search for a text string in a file
FINDSTR Search for strings in files
FLTMC Manage MiniFilter drivers
FOR /F Loop command: against a set of files•
FOR /F Loop command: against the results of another command•
FOR Loop command: all options Files, Directory, List•
FORFILES Batch process multiple files
FORMAT Format a disk
FREEDISK Check free disk space
FSUTIL File and Volume utilities
FTP File Transfer Protocol
FTYPE File extension file type associations•
g

https://ss64.com/nt/[8/24/2017 10:32:43 AM]


An A-Z Index of the Windows CMD command line | SS64.com

GETMAC Display the Media Access Control (MAC) address


GOTO Direct a batch program to jump to a labelled line•
GPRESULT Display Resultant Set of Policy information
GPUPDATE Update Group Policy settings
h
HELP Online Help
HOSTNAME Display the host name of the computer
i
iCACLS Change file and folder permissions
IEXPRESS Create a self extracting ZIP file archive
IF Conditionally perform a command•
IFMEMBER Is the current user a member of a group
IPCONFIG Configure IP
INUSE Replace files that are in use by the OS
l
LABEL Edit a disk label
LODCTR Load PerfMon performance counters
LOGMAN Manage Performance Monitor logs
LOGOFF Log a user off
LOGTIME Log the date and time in a file
m
MAKECAB Create .CAB files
MAPISEND Send email from the command line
MBSAcli Baseline Security Analyzer
MEM Display memory usage
MD Create new folders•
MKLINK Create a symbolic link (linkd) •
MODE Configure a system device COM/LPT/CON
MORE Display output, one screen at a time
MOUNTVOL Manage a volume mount point
MOVE Move files from one folder to another•
MOVEUSER Move a user from one domain to another
MSG Send a message
MSIEXEC Microsoft Windows Installer
MSINFO32 System Information
MSTSC Terminal Server Connection (Remote Desktop Protocol)
n
NET Manage network resources
NETDOM Domain Manager
NETSH Configure Network Interfaces, Windows Firewall & Remote access
NBTSTAT Display networking statistics (NetBIOS over TCP/IP)
NETSTAT Display networking statistics (TCP/IP)
NLSINFO Display locale information (reskit).
NLTEST Network Location Test (AD)
NOW Display the current Date and Time
NSLOOKUP Name server lookup
NTBACKUP Backup folders to tape
NTDSUtil Active Directory Domain Services management
NTRIGHTS Edit user account rights
NVSPBIND Modify network bindings
o
OPENFILES Query or display open files
p
PATH Display or set a search path for executable files•
PATHPING Trace route plus network latency and packet loss
PAUSE Suspend processing of a batch file and display a message•
PERMS Show permissions for a user
PERFMON Performance Monitor
PING Test a network connection
POPD Return to a previous directory saved by PUSHD•
PORTQRY Display the status of ports and services
POWERCFG Configure power settings
PRINT Print a text file
PRINTBRM Print queue Backup/Recovery
PRNCNFG Configure or rename a printer
PRNMNGR Add, delete, list printers and printer connections
ProcDump Monitor an application for CPU spikes
PROMPT Change the command prompt•
PsExec Execute process remotely
PsFile Show files opened remotely
PsGetSid Display the SID of a computer or a user
PsInfo List information about a system
PsKill Kill processes by name or process ID
PsList List detailed information about processes
PsLoggedOn Who's logged on (locally or via resource sharing)
PsLogList Event log records
PsPasswd Change account password
PsPing Measure network performance
PsService View and control services
PsShutdown Shutdown or reboot a computer
PsSuspend Suspend processes
PUSHD Save and then change the current directory•
q
QGREP Search file(s) for lines that match a given pattern
Query Process / QPROCESS Display processes
Query Session / QWinsta Display all sessions (TS/Remote Desktop)
Query TermServer /QAppSrv List all servers (TS/Remote Desktop)
Query User / QUSER Display user sessions (TS/Remote Desktop)
r
RASDIAL Manage RAS connections
RASPHONE Manage RAS connections
RECOVER Recover a damaged file from a defective disk
REG Registry: Read, Set, Export, Delete keys and values

https://ss64.com/nt/[8/24/2017 10:32:43 AM]


An A-Z Index of the Windows CMD command line | SS64.com

REGEDIT Import or export registry settings


REGSVR32 Register or unregister a DLL
REGINI Change Registry Permissions
REM Record comments (remarks) in a batch file•
REN Rename a file or files•
REPLACE Replace or update one file with another
Reset Session Delete a Remote Desktop Session
RD Delete folder(s)•
RMTSHARE Share a folder or a printer
ROBOCOPY Robust File and Folder Copy
ROUTE Manipulate network routing tables
RUN Start | RUN commands
RUNAS Execute a program under a different user account
RUNDLL32 Run a DLL command (add/remove print connections)
s
SC Service Control
SCHTASKS Schedule a command to run at a specific time
SET Display, set, or remove session environment variables•
SETLOCAL Control the visibility of environment variables•
SetSPN Edit Service Principal Names
SETX Set environment variables
SFC System File Checker
SHARE List or edit a file share or print share
ShellRunAs Run a command under a different user account
SHIFT Shift the position of batch file parameters•
SHORTCUT Create a windows shortcut (.LNK file)
SHUTDOWN Shutdown the computer
SIGCHECK Display file version no. VirusTotal status & timestamp
SLEEP Wait for x seconds
SLMGR Software Licensing Management (Vista/2008)
SORT Sort input
START Start a program, command or batch file•
STRINGS Search for ANSI and UNICODE strings in binary files
SUBINACL Edit file and folder Permissions, Ownership and Domain
SUBST Associate a path with a drive letter
SYSMON Monitor and log system activity to the Windows event log
SYSTEMINFO List system configuration
t
TAKEOWN Take ownership of a file
TASKLIST List running applications and services
TASKKILL End a running process
TELNET Communicate with another host using the TELNET protocol
TIME Display or set the system time•
TIMEOUT Delay processing of a batch file
TITLE Set the window title for a CMD.EXE session•
TLIST Task list with full path
TOUCH Change file timestamps
TRACERT Trace route to a remote host
TREE Graphical display of folder structure
TSDISCON Disconnect a Remote Desktop Session
TSKILL End a running process
TSSHUTDN Remotely shut down or reboot a terminal server
TYPE Display the contents of a text file•
TypePerf Write performance data to a log file
TZUTIL Time Zone Utility
v
VER Display version information•
VERIFY Verify that files have been saved•
VMConnect Connect to a Hyper-V Virtual Machine
VOL Display a disk label•
w
W32TM Time Service
WAITFOR Wait for or send a signal
WBADMIN Windows Backup Admin
WECUTIL Windows Event Collector Utility
WEVTUTIL Clear event logs, enable/disable/query logs
WHERE Locate and display files in a directory tree
WHOAMI Output the current UserName and domain
WINDIFF Compare the contents of two files or sets of files
WINRM Windows Remote Management
WINRS Windows Remote Shell
WMIC WMI Commands
WPEUTIL Run WinPE commands
WPR Windows Performance Recorder
WUAUCLT Windows Update
x
XCACLS Change file and folder permissions
XCOPY Copy files and folders
:: Comment / Remark•

Commands marked • are Internal commands only available within the CMD shell.
All other commands (not marked with •) are external commands.
External commands may be used under the CMD shell, PowerShell, or directly from START-RUN.

See also: a categorized list of Windows CMD commands


Microsoft Help pages: 2003 Server, 2008 Server, Windows 7/Server 2012 / Technology
Discussion forum
Links to other sites, books etc...

https://ss64.com/nt/[8/24/2017 10:32:43 AM]


An A-Z Index of the Windows CMD command line | SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/[8/24/2017 10:32:43 AM]


Windows Resource Kits, Books and Websites - SS64.com

(  SS64  ) CMD

Websites, Resource Kits, Books and Utilities


Windows 7/2008 Command Reference - Microsoft
Windows 2008/R2 Commands Help file - Microsoft
Old New Thing - Raymond Chen, Microsoft
Microsoft Security Response Center (MSRC) - Microsoft)
Security Bulletins 2017 - Microsoft Security TechCenter
Microsoft Update Catalog - Search for specific updates by KB#

Rob van der Woude.com - Batch files, VBS


CommandLine - Batch File examples and Utilities.
Timo Salmi - Useful script tricks and tips.

Resource Kits + updates


Many resource kit tools and utilities will run successfully on multiple versions of Windows. However Active Directory and
NTFS have changed significantly over the years so I recommend you only use the tools supported for your platform.

Windows 7 Resource Kit


By Mitch Tulloch, Tony Northrup & Jerry Honeycutt
1,700 pages, Deploy, Manage, Maintain and Troubleshoot. Example VBS and PowerShell scripts, sample chapter
(PDF.)

Windows 10 Remote Server Administration Tools (RSAT) KBase


Windows 2008/2012 Remote Server Administration Tools (RSAT) Built-in feature
WIndows 8.1 Remote Server Administration Tools (RSAT) KBase
Windows 8 Remote Server Administration Tools (RSAT) KBase
Windows 7 Remote Server Administration Tools (RSAT) KBase
RSAT includes Active Directory Domain Services Tools, elements of the RSAT package can be enabled under
Control Panel | Programs and Features | Windows features.

Windows Server 2008 Resource Kit - April 2008


By Microsoft Corp
4,000 pages + DVD with more than 200 essential tools and scripts.

Deployment tools
Windows 10 - ISO download
N edition = No Media Player or IE DRM or Camera.
KN edition = Korean

Windows Assessment and Deployment Kit (Windows ADK) - Customize Windows 10 images for large-scale
deployment.
Microsoft Deployment Toolkit (MDT) 2013 Update 2 [news] - Automate desktop and server OS deployments.

Other Windows Toolkits:


Sysinternals Suite - Download the Sysinternals utilities.

https://ss64.com/links/windows.html[8/24/2017 10:32:44 AM]


Windows Resource Kits, Books and Websites - SS64.com

ADModify - A GUI tool to facilitate making bulk user attribute modifications.

Windows 7 /8 / 2008 / 2012 Assessment and Deployment Kit (ADK)


Windows 7 /8.1/ 2008 R2 /2012 Assessment and Deployment Kit (ADK update)

Microsoft Application Compatibility Toolkit - Evaluate and mitigate application compatibility issues for Vista and
Windows 7. Includes the Compatibility Administrator which can be used to set UAC exceptions (Application fix.)

Account Lockout Status (LockoutStatus.exe) - Display lockout information for a particular user account (Aug
2012).

Account Lockout and Management Tools - Includes LockoutStatus, plus tools to troubleshoot account lockouts,
and display password ages(Aug 2012).

Microsoft Baseline Security Analyzer - Scan local and remote systems for missing security updates.

SMB1 How to disable it - Windows 7 up to Windows Server 2016

Elevation PowerToys for Windows Vista + Elevation blog

File Checksum Integrity Verifier (FCIV) - Compute and verify cryptographic hash values for files.

Policy Analyzer from Aaron Margosis - Compare sets of Group Policy Objects (GPOs). Highlight redundant
settings or internal inconsistencies.

Group Policy Management Console SP1 & Group Policy Object Settings spreadsheet 2003/2008/2008R2/Win7

Local Administrator Password Solution (LAPS) - Manage local account passwords of domain joined computers
(howto)

Remote Desktop Connection Manager - RDP to multiple machines.

Windows Help - Install Windows 7/8 Help, fix for 'Help not supported' errors.

WMI Diagnosis Utility - Diagnose and repair problems with the WMI service.

Recommended Books.

Batchography: The Art of Batch Files Programming


by Elias Bachaalany
Discover the lost art of Batch file programming, start with the basics of manipulating numbers, strings and
variables and move on to looping operations, recursion, debugging and troubleshooting of your scripts. The final
chapter has a number of batch file recipes: parsing .ini files, creating interactive menus and more. Highly
recommended.

SysInternals Administrator's Reference


by Mark E. Russinovich
Guidance and inside insights for the Windows Sysinternals tools. Guided by Sysinternals creator Mark
Russinovich and Windows expert Aaron Margosis

https://ss64.com/links/windows.html[8/24/2017 10:32:44 AM]


Windows Resource Kits, Books and Websites - SS64.com

Windows 7 and Vista Guide to Scripting, Automation, and Command Line Tools
By Brian Knittel
A complete guide covering VBScript, traditional batch files, and PowerShell.

Windows Internals, Part 1 and Part2


by Mark E. Russinovich, David A. Solomon and Alex Ionescu
Insider perspectives and hands-on experiments to demonstrate how Windows operates.

Windows 10: The Missing Manual


by David Pogue
An enjoyable but still very detailed read with lot's of good tips and keyboard shortcuts.

Mark Minasi's Mastering Windows Server 2012 R2


by Mark Minasi.
Comprehensive and understandable guide. Improve the performance and manageability of your network.
minasi.com

Windows NT Shell Scripting


by Tim Hill.
First published in 1998 so no mention of VBS or Powershell, despite this it's still a solid introduction to writing
batch files under Windows. Sample chapter.

Also see - Recommended VBScript Books

Utilities - Command line


SysInternals - Microsoft System utilities.
Joeware.net - Admin, AD and Exchange tools.
Nirsoft Utilities and NirCMD freeware Command-Line Tool.

Console 2 - Windows console emulator for CMD and/or PowerShell (review)


ConEmu-Maximus5 - Windows console emulator for CMD and/or PowerShell (review)
CommandLine.co.uk - Useful tools (free Win32 utilities - mostly console)
CryptoPrevent - A Group Policy to block executables from specific paths.
Cygwin - Linux-like environment for Windows, tutorial: 1, 2, 3
FastCopy - An alternative to RoboCopy.
Frank P. Westlake Batch Scripts + mirror of older console utilities.
Gow - Lightweight UNIX utilities compiled as native win32 binaries.
HoboCopy - open-source backup tool (can copy open files)
Jason Hood - Utilities including Search & Replace, Date/Time, ANSI escape recognition for CMD.
Npocmaka - Batch scripts, zipjs.bat + others

https://ss64.com/links/windows.html[8/24/2017 10:32:44 AM]


Windows Resource Kits, Books and Websites - SS64.com

PDFtk - Command-line tool for processing PDFs


Petter Nordahl-Hagen - Offline Windows Password & Registry Editor
pretentiousname - Utilities by Leo Davidson
Repl.bat - FInd and Replace text, JScript/Batch script
FindRepl.bat - FInd and Replace text, JScript/Batch script
SetRes - Set screen resolution (Ian Sharpe)
Bill Stewart - Batch script and Windows admin tools (TrueLast LogonTime)
SetACL - Utility to manage permissions, auditing and ownership (free)
System Tools - Dump Event Log, Registry or Security info
unxutils - Port of unix utilities to run under the CMD shell

Package Managers
Chocolatey - Package manager for Windows
Ninite - Automate software installations and updates.

Utilities - GUI
Agent Ransack - File Search (search all file types)
AIMP3 - Fully featured free music player.
Autohotkey - Automate keystrokes, mouse clicks.
AutoIT - GUI scripting
CamStudio - Record screen and audio activity on your computer.
Clonezilla - Partition and disk imaging/cloning program
CPU-Z - gather information on system devices

Dban - Darik's Boot and Nuke, a boot CD that securely wipes hard disks.
Event Sentry - Event log monitoring

FTP - Cyberduck - FTP client


FTP - FileZilla - FTP client (safe download only via Ninite)
FTP - WinSCP - Free SFTP, SCP and FTP client for Windows

Find And Replace Text - Grep-like utility by Lionello Lunesu (Sourceforge link removed)
Flash uninstall - To allow a full 'clean' reinstall
FlashBlock - Content-filtering extension for Firefox
FileZilla - A cross-platform FTP, FTPS and SFTP client
foobar2000 - freeware audio player
Ghost Solution Suite - Disk / Partition Imaging
Inkscape - Vector Graphics (Illustrator)
imgburn.com - Free CD/DVD/Blu-ray burner
isoRecorder - Burn iso image to bootable CD
Krita - Open Source photo/graphics editor.
Lansweeper - Network Monitoring
Lost NT password
MakeMSI - Build Windows Installer files.
MalwareBytes - Anti Malware, detect and remove worms, Trojans, rootkits, etc.
Metapad - Simple notepad replacement
Notepad++ - Notepad replacement (n.b. the syntax highlighting for parentheses in CMD/BAT files is faulty.)
nLite - pre-installation Windows configuration
Photoshop Elements - Basic photo editing and organisation.
Trinity Rescue Kit - Recovery and repair of Windows machines
Netikus - Password, Ping, FTP, event log alerts.
Panda AntiVirus Free
PhotoRec - Data recovery software - hard disk, CD-ROM & Memory Cards
PuTTY - Free Telnet/SSH Client
Rapid Environment Editor - Edit environment variables
Servers Alive - Network monitoring
SoftPerfect - Search, Scan for open file shares and other utils.
Speccy - System information, hardware and software (serial numbers etc).
Sumatra - PDF viewer

https://ss64.com/links/windows.html[8/24/2017 10:32:44 AM]


Windows Resource Kits, Books and Websites - SS64.com

SyncBack - GUI Backup and synchronize files


SyncToy - Synchronize files and folders
TeamViewer - Screen sharing/Remote control (Mac/PC/Linux)
Textadept - cross-platform text editor.
TightVNC - Remote control
TribbleSoft - Easy Robocopy (GUI)
UnDelete - Condusiv/Diskeeper
USB install for Windows 7 - Copy iso images to a bootable USB stick
WinMerge - open source WinDiff
VirtualBox - Open Source virtualisation for Windows, Linux, Macintosh, and Solaris.
VirtualDub - Process/Edit .AVI files
Virtual PC - Virtualisation for Windows
VLC Media Player - Free versatile media player
VMWare - Free
VueScan - Scanner Software
WiNToBootic - Make bootable USB Flash or Hard Disk
WSUS Offline Update - Microsoft Windows/Office updates from a USB stick.
Wink - Capture screenshots/video, add help text
WsusOffline - Apply Windows Update patches without an internet connection.
Zero Assumption Recovery - data recovery

Find more utilities, or add you own over in the forum

Related

Usenet - news: alt.msdos.batch.nt


DosTips forum
The Scripting Guys Forum - a mix of VBScript, Batch and PowerShell.
SS64 - Windows CMD discussion Forum

MS Support Q no's
913086 »

Search Microsoft Knowledge base


Blue Screen »

“We have prided ourselves on always being the cheapest guy on the block. We have always told our people we're the high volume, low
price guy in the software business" - Steve Ballmer (Partnering for Success)

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/links/windows.html[8/24/2017 10:32:44 AM]


Parameters / Arguments - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Command Line arguments (Parameters)


A command line argument (or parameter) is any value passed into a batch script:
C:> MyScript.cmd January 1234 "Some value"

Arguments can also be passed to a subroutine with CALL:


CALL :my_sub 2468

You can get the value of any argument using a % followed by it's numerical position on the command line. The first item
passed is always %1 the second item is always %2 and so on

%* in a batch script refers to all the arguments (e.g. %1 %2 %3 %4 %5 ...%255)


only arguments %1 to %9 can be referenced by number.

Parameter Extensions
When an argument is used to supply a filename then the following extended syntax can be applied:

we are using the variable %1 (but this works for any parameter)

%~f1 Expand %1 to a Fully qualified path name - C:\utils\MyFile.txt

%~d1 Expand %1 to a Drive letter only - C:

%~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which will be interpreted as an escape
character by some commands.

%~n1Expand %1 to a file Name without file extension C:\utils\MyFile or if only a path is present (with no trailing
backslash\) - the last folder in that path.

%~x1 Expand %1 to a file eXtension only - .txt

%~s1 Change the meaning of f, n, s and x to reference the Short 8.3 name (if it exists.)

%~1   Expand %1 removing any surrounding quotes (")

%~a1 Display the file attributes of %1

%~t1 Display the date/time of %1

%~z1 Display the file size of %1

%~$PATH:1 Search the PATH environment variable and expand %1 to the fully qualified name of the first match
found.

The modifiers above can be combined:

%~dp1 Expand %1 to a drive letter and path only

%~sp1 Expand %1 to a path shortened to 8.3 characters

%~nx2 Expand %2 to a file name and extension only

These parameter/ argument variables are always denoted with a single leading %
This is unlike regular variables which have both leading and trailing %'s such as %variable% , or FOR command variables
which use a single leading % on the command line or a double leading %% when used in a batch file.

https://ss64.com/nt/syntax-args.html[8/24/2017 10:32:54 AM]


Parameters / Arguments - Windows CMD - SS64.com

Parameter expansion will treat a Full Stop within a directory name as a file extension, so for a name like "Sample 2.6.4 " the
output of %~n1 will be truncated to "Sample 2.6 " to return the whole folder name use %1 or %~nx1

If the output of DIR, or a filename with no drive letter/path is expanded to display a Full pathname %~f1 the command shell will
assume; often incorrectly; that the file resides in the current directory. The CMD shell does not read file descriptors, or work
with filesystem objects the way that PowerShell does, it is processing a simple list of text strings.

When writing batch scripts it's a good idea to store the values in a named variable SET _LogFile=%~dp1 , the rest of the script
can then refer to the easy-to-read variable name %_LogFile% This will also make life easier if you later need to change around
the order of the parameters.

Tokenization
Tokenization of the command line arguments is not always done by the cmd.exe shell. Most often the tokenization
is done by the newly formed processes' runtime, at the OS level, Windows passes a command line untokenized as
a single string to the new process. You can read more about the low-level details of the batch language/cmd
escaping from the excellent answers by jeb and dbenham on this StackOverflow question.

Passing by Reference
In addition to passing numeric or string values on the command line, it is also possible to pass a variable name
and then use the variable to transfer data between scripts or subroutines. Passing by reference is a slightly more
advanced technique but can be particularly useful when the string contains characters that are CMD delimiters or
quotes.

Links relative to the Batch Script


You can get the pathname of the batch script itself with %0, parameter extensions can be applied to this so %~dp0
will return the Drive and Path to the batch script e.g. W:\scripts\ and %~f0 will return the full pathname
W:\scripts\mybatch.cmd

You can refer to other files in the same folder as the batch script by using this syntax:
CALL %0\..\SecondBatch.cmd

This can even be used in a subroutine, Echo %0 will give the call label but, echo "%~nx0" will give you the filename
of the batch script.

When the %0 variable is expanded, the result is enclosed in quotation marks.

Use %~a1 to display the Extended Attributes of a file.


FOR's %%~aI recognizes 9 NTFS file attributes. The expansion of a file attribute produces a series of 9 dashes,
with each recognized attribute replacing a dash with a letter. A file with no recognized attributes or with none set
will expand to 9 dashes like this: ---------
Attribute Expansion
FILE_ATTRIBUTE_DIRECTORY d--------
FILE_ATTRIBUTE_READONLY -r-------
FILE_ATTRIBUTE_ARCHIVE --a------
FILE_ATTRIBUTE_HIDDEN ---h-----
FILE_ATTRIBUTE_SYSTEM ----s----
FILE_ATTRIBUTE_COMPRESSED -----c---
FILE_ATTRIBUTE_OFFLINE ------o--
FILE_ATTRIBUTE_TEMPORARY -------t-
FILE_ATTRIBUTE_REPARSE_POINT --------l
FILE_ATTRIBUTE_NORMAL ---------

Other NTFS attributes not recognised by %%~aI can be read using FSUTIL usn command:
FILE_ATTRIBUTE_ENCRYPTED
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
FILE_ATTRIBUTE_SPARSE_FILE

Example: Expansion of a file with the Hidden and System attributes:

https://ss64.com/nt/syntax-args.html[8/24/2017 10:32:54 AM]


Parameters / Arguments - Windows CMD - SS64.com

---hs----

Maximum line length


The maximum length of any command line (or variable) within CMD is 8191 characters.

Terminology: Command-line Argument or Parameter?


In mathematical terms a parameter is "a numerical or other measurable factor" so typically a number.

In programming terminology:
A parameter represents a value that the procedure expects you to pass when you call it.
An argument represents the actual value that you pass to a procedure.

In practice the phrases argument and parameter tend to be used interchangeably, CMD batch files do not perform
any type checking.

FOR parameters
The FOR command creates parameter variables which are identified with a letter rather than a number (e.g. %%G ).
The Parameter Expansions described above can also be applied to these.
To avoid confusion between the two sets of letters, avoid using the letters (a, d, f, n, p, s, t, x, z) as FOR
parameters or just choose a FOR parameter letter that is UPPER case.
So for example in a reference like %%~fG the %%G is the FOR parameter, and the ~f is the Parameter Expansion.

Examples:

Pass parameters from one batch to another:


MyBatch.cmd SMITH 100

Or as part of a CALL :
CALL MyBatch.cmd SMITH 100

Get the file size of C:\demo\sample.xlsx using the %~z parameter extension:
@Echo off
For %%G in ("C:\demo\sample.xlsx") do set _var=%%~zG
Echo File size is %_var%

Passing values from one part of a script to another:


:: Using CALL to jump to a subroutine
CALL :s_staff SMITH 100
:: Calling a subroutine from a FOR command
FOR /F %%G IN ('DIR /b *.*') DO call :s_subroutine %%G

“A gift is pure when it is given from the heart to the right person at the right time and at the right place, and when we expect nothing in
return” ~ The Bhagavad Gita

Related:

CALL - Call one batch program from another.


CMD - Start a new DOS shell (cmd.exe)
IF - Test that required inputs are in place (not NULL)
FOR - Conditionally perform a command several times.
SETLOCAL - Control the visibility of environment variables
SHIFT - Shift the position of replaceable parameters in a batch file.
How Command Line Parameters are Parsed by David Deley
Bug when using ~s to display short file/folder names
StackOverflow - How does the Windows Command Interpreter (CMD.EXE) parse scripts?
Equivalent bash command (Linux): dirname - Convert a full pathname to just a path.

https://ss64.com/nt/syntax-args.html[8/24/2017 10:32:54 AM]


Parameters / Arguments - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-args.html[8/24/2017 10:32:54 AM]


Start | Run Commands for Windows - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Windows Start | Run commands


Description Run Command
utilman
Accessibility Options or
control access.cpl

Add Hardware Wizard hdwwiz

Add/Remove Programs appwiz.cpl


(Add New Programs) control appwiz.cpl,,1
(Add Remove Windows Components) control appwiz.cpl,,2
(Set Program Access & Defaults ) control appwiz.cpl,,3

Administrative Tools control admintools

Advanced User Accounts Control Panel netplwiz

Authorization Manager azman.msc

Automatic Update control wuaucpl.cpl

Backup and Restore Utility sdclt

Bluetooth Transfer Wizard fsquirt

Calculator calc

Certificate Manager certmgr.msc

Character Map charmap

Check Disk Utility chkdsk

Clear Type (tune or turn off) cttune

Color Management colorcpl.exe

Command Prompt cmd

dcomcnfg
Component Services or
comexp.msc

CompMgmtLauncher.exe
Computer Management or
compmgmt.msc

Control Panel control

Credential (passwords) Backup and Restore Wizard credwiz

Data Execution Prevention SystemPropertiesDataExecutionPrevention

Date and Time Properties timedate.cpl

hdwwiz
Device Manager or
devmgmt.msc

Device Pairing Wizard DevicePairingWizard

https://ss64.com/nt/run.html[8/24/2017 10:33:04 AM]


Start | Run Commands for Windows - Windows CMD - SS64.com

Digitizer Calibration Tool (Tablets/Touch screens) tabcal

Direct X Control Panel (if installed) directx.cpl

Direct X Troubleshooter dxdiag

Disk Cleanup Utility cleanmgr

dfrgui
Disk Defragmenter
defrag

Disk Management diskmgmt.msc

Disk Partition Manager diskpart

Display Color Calibration dccw

Display DPI / Text size dpiscaling

Display Properties (Themes, Desktop, Screensaver) control desktop

Display Properties (Resolution, Orientation) desk.cpl

Display Properties (Color & Appearance) control color

Documents (open 'My Documents' folder) documents

Downloads (open 'Downloads' folder) downloads

Driver Verifier Utility verifier

DVD Player dvdplay

Edit Environment Variables rundll32.exe sysdm.cpl,EditEnvironmentVariables

Encrypting File System Wizard (EFS) rekeywiz

Event Viewer eventvwr.msc

File Signature Verification Tool (Device drivers) sigverif

Files and Settings Transfer Tool %systemroot%\system32\migwiz\migwiz.exe

Firewall Control Panel firewall.cpl

Folders Properties control folders

Fonts list control fonts

Font preview fontview arial.ttf

Game Controllers joy.cpl

Local Group Policy Editor gpedit.msc

Internet Properties inetcpl.cpl

IP Configuration ipconfig

iSCSI Initiator configuration iscsicpl

Keyboard Properties control keyboard

Language Pack Installer lpksetup

Local Security Policy secpol.msc

Local Users and Groups lusrmgr.msc

Log out logoff

https://ss64.com/nt/run.html[8/24/2017 10:33:04 AM]


Start | Run Commands for Windows - Windows CMD - SS64.com

Microsoft Malicious Software Removal Tool mrt

Microsoft Management Console mmc

Access (Microsoft Office) msaccess

Excel (Microsoft Office) Excel

Powerpoint (Microsoft Office) powerpnt

Word (Microsoft Office) winword

Microsoft Paint mspaint

Microsoft Support Diagnostic Tool msdt

control mouse
Mouse Properties or
main.cpl

control netconnections
Network Connections or
ncpa.cpl

Projector: netproj
Connect to Network Projector
Switch projector display displayswitch

Notepad notepad

ODBC Data Source Admin


Default ODBC driver: C:\windows\system32\odbcad32.exe
32-bit ODBC driver under 64-bit platform: C:\windows\sysWOW64\odbcad32.exe

ODBC configuration - Install/configure MDAC drivers odbcconf

On Screen Keyboard osk

OOB Getting Started gettingstarted

Password - Create a Windows Password Reset Disk "C:\Windows\system32\rundll32.exe"


(USB) keymgr.dll,PRShowSaveWizardExW

Pen and Touch (Tablet/Pen input configuration) tabletpc.cpl

Performance Monitor perfmon.msc

Phone and Modem Options telephon.cpl

Phone Dialer dialer

Power Configuration powercfg.cpl and powercfg.exe

Presentation Settings PresentationSettings

Problem Steps Recorder psr

Program Access and Computer Defaults - browser / email computerdefaults


/ media
Printers and Faxes control printers

Print Management (.msc) PrintManagement

Printer Migration (backup/restore) printbrmui and printbrm.exe

Printer user interface (List all printui.dll options) printui

https://ss64.com/nt/run.html[8/24/2017 10:33:04 AM]


Start | Run Commands for Windows - Windows CMD - SS64.com

Private Character Editor eudcedit

Regional Settings - Language, Date/Time format,


intl.cpl
keyboard locale.
Registry Editor regedit

Remote Assistance msra

Remote Desktop mstsc

Resource Monitor resmon

Resultant Set of Policy rsop.msc

Scheduled Tasks control schedtasks

Screenshot Snipping Tool snippingtool

Security Center wscui.cpl

Services services.msc

Shared Folder Wizard shrpubw

Shared Folders fsmgmt.msc

Shut Down Windows shutdown

Software Licensing/Activation slui

Sounds and Audio mmsys.cpl

Sound Recorder soundrecorder

Sound Volume sndvol

Syncronization Tool (Offline files) mobsync

System Configuration Utility msconfig

System File Checker Utility (Scan/Purge) sfc

System Information msinfo32

sysdm.cpl SystemProperties
System Properties or
sysdm.cpl DisplaySYSDMCPL

System Properties - Performance SystemPropertiesPerformance

System Properties - Hardware SystemPropertiesHardware

System Properties - Advanced SystemPropertiesAdvanced

System Repair - Create a System Repair Disc recdisc

System Restore rstrui

Task Manager taskmgr

Task Scheduler taskschd.msc

Telnet Client telnet

Trusted Platform Module Initialization Wizard tpmInit

control userpasswords2
User Accounts (Autologon)

https://ss64.com/nt/run.html[8/24/2017 10:33:04 AM]


Start | Run Commands for Windows - Windows CMD - SS64.com

User Account Control (UAC) Settings UserAccountControlSettings

C:\Windows\System32\rundll32.exe
User Profiles - Edit/Change type
sysdm.cpl,EditUserProfiles

Windows Disc Image Burning Tool isoburn C:\movies\madmax.iso

Windows Explorer explorer

Windows Features optionalfeatures

Windows Firewall firewall.cpl


Windows Firewall with Advanced Security wf.msc

Windows Image Acquisition (scanner) wiaacmgr

Windows Magnifier magnify

Windows Management Infrastructure wmimgmt.msc

Windows Memory Diagnostic Scheduler mdsched

Windows Mobility Center (Mobile PCs only) mblctr

Windows PowerShell powershell

Windows PowerShell ISE powershell_ise

Windows Security Action Center wscui.cpl

Windows Script Host(VBScript) wscript NAME_OF_SCRIPT.VBS

Windows System Security Tool. Encrypt the SAM


database. syskey
(boot password.)
Windows Update wuapp

Windows Update Standalone Installer wusa

Windows Version (About Windows) winver

WordPad write

Unless indicated otherwise, all the commands above work in all versions of Windows from Vista upwards.
Most of these utilities can be found in %systemroot%\System32\

“The Macintosh uses an experimental pointing device called a 'mouse.' There is no evidence that people want to use these things” ~ John
Dvorak

Related

MMC Snap-ins - Admin commands


Shell: folder - Shortcuts to key folders.
ProfileFolders - Location of user profile folders.
EXPLORER - Open Windows Explorer
Windows Key - Shortcuts

https://ss64.com/nt/run.html[8/24/2017 10:33:04 AM]


Start | Run Commands for Windows - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/run.html[8/24/2017 10:33:04 AM]


MMC Admin command lines - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

MMC Snap-ins
System Administrator command line shortcuts to popular Microsoft Management Consoles (MMCs).

Admin Snap-in Command Category


Quality of Service Control Management ACSsnap.msc Network
ADSI Edit ADSIedit.msc AD Configuration
Authorization manager AZman.msc Security
Certificates Management - Local machine Certlm.msc Security
Certificates Management - Current user Certmgr.msc Security
Certification Authority Management Certsrv.msc Security
Certificate Templates Certtmpl.msc Security
Failover cluster Manager Cluadmin.exe Disc, File
Component Services Comexp.msc

Computer Management Compmgmt.msc

Device Manager Devmgmt.msc Hardware


Notifications/Start menu/policy DevModeRunAsUserConfig.msc

Disk Defragmenter Defrag.exe (formerly Dfrg.msc) Disc, File


Distributed File Service Mgmt DFSmgmt.msc Disc, File
Disk Manager DiskMgmt.msc Disc, File
DNS Manager DNSmgmt.msc Network
AD Domains and Trusts Domain.msc AD Configuration
AD Users and Computers DSA.msc Security
AD Sites and Services DSsite.msc AD Configuration
Embedded Lockdown Manager EmbeddedLockdown.msc Security
Event Viewer Eventvwr.msc

Shared Folders open files FSmgmt.msc Disc, File


File Server Resource manager FSRM.msc Disc, File
Local Group Policy Editor GPedit.msc Policy
Group Policy Management GPmc.msc Policy
Group Policy Management Editor GPme.msc Policy
Group Policy Starter GPO Editor GPTedit.msc Policy
Local Users and Groups Manager LUsrMgr.msc Security
Teminal Services RDP MSTSC Remote Access
Teminal Services RDP to Console MSTSC /v:[server] /console Remote Access

https://ss64.com/nt/syntax-mmc.html[8/24/2017 10:33:14 AM]


MMC Admin command lines - Windows CMD - SS64.com

NAP client configuration NapCLCfg Network


Performance Monitor PerfMon.msc

Print Management PrintManagement.msc Print


Resultant Set of Policy RSOP.msc Policy
Local Security Settings Manager SecPol.msc Policy
Server Roles, Features ServerManager.msc

Services Management Services.msc

SQL Server configuration Manager SQLServerManager11.msc

Storage Mgmt StorageMgmt.msc Disc, File


Telephony Management TAPImgmt.msc Phone/Modem
Task Scheduler TaskSchd.msc

Trusted Platform Module TPM.msc Security


Terminal Server Manager TSadmin.exe Remote Access
Remote Desktop TSmmc.msc Remote Access
Windows Mangement Instrumentation WmiMgmt.msc

Windows Server Backup (Local+Remote) WBadmin.msc Disc, File


Windows Local Backup WLBadmin.msc Disc, File
Windows Firewall WF.msc Remote Access

The commands above can be entered from START > Run, or from the command line.
Availability will vary by OS and by the features installed.

“I don't do anything in order to cause trouble. It just so happens that what I do naturally causes trouble.
 I'm proud to be a troublemaker” ~ Sinead O'Connor

Related:

Run Commands

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-mmc.html[8/24/2017 10:33:14 AM]


Shell folder shortcuts - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Shell: folder shortcuts


Roaming?
Description Shell: folder shortcut Type

Display installed Windows Updates shell:AppUpdatesFolder System folder


Display links provided by your PC manufacturer (if
shell:OEM Links System folder
any)
Open the Computer folder shell:MyComputerFolder System folder
Open the folder holding all user profiles shell:UserProfiles System folder
Open the Fonts folder shell:Fonts System folder
Open the Games folder shell:Games System folder
Open the HomeGroup folder shell:HomeGroupFolder System folder
Open the HomeGroup folder for the currently logged-
shell:HomeGroupCurrentUserFolder System folder
on user (if any)
Open the Network Places folder shell:NetworkPlacesFolder System folder
Open the Printers folder shell:PrintersFolder System folder
Open the Public Application Data folder shell:Common AppData System folder
Open the Public Desktop shell:Common Desktop System folder
Open the Public Documents folder shell:Common Documents System folder
Open the Public Downloads folder shell:CommonDownloads System folder
Open the Public Game Explorer folder shell:PublicGameTasks System folder
Open the Public ringtones folder. shell:CommonRingtones System folder
Open the Public Start Menu folder shell:Common Start Menu System folder
Open the Public Start Menu Programs folder shell:Common Programs System folder
Open the Public Startup folder shell:Common Startup System folder
Open the Public Templates folder shell:Common Templates System folder
Open the Recycle Bin shell:RecycleBinFolder System folder
Open the Users\Public folder (Shared files) shell:Public System folder
Open the Windows installation folder (usually
shell:Windows System folder
\Windows)
Open the Windows Resources folder (themes are shell:ResourceDir System folder
stored here)
Open the Windows System folder shell:System System folder
Open the Windows System folder for 32-bit files on
64-bit Windows, shell:Systemx86 System folder
Or \Windows\System32 on 32-bit Windows
Access shortcuts pinned to the Start menu or Taskbar shell:User Pinned User folder Y

https://ss64.com/nt/shell.html[8/24/2017 10:33:23 AM]


Shell folder shortcuts - Windows CMD - SS64.com

Display the user's Ringtones folder shell:Ringtones User folder


Display further user tiles shell:Roaming Tiles User folder Y
Display your user tiles (the images you can use for
shell:UserTiles User folder
your account)
Open the Client Side Cache Offline Files folder, if
shell:CSCFolder User folder
supported
Open the folder where files are stored before being
shell:CD Burning User folder
burned to disc
Open the Public user tiles folder shell:PublicUserTiles User folder
Open the Quick Launch folder (disabled by default) shell:Quick Launch User folder Y
Open the Saved Games folder shell:SavedGames User folder Y
Open the saved searches folder shell:Searches User folder Y
Open the user‘s \Music\Playlists folder shell:Playlists User folder Y
Open the user‘s Application Data folder shell:AppData User folder Y
Open the user‘s Application Data folder (same as
shell:Local AppData User folder
% LOCALAPPDATA%)

Open the user‘s certificates folder shell:SystemCertificates User folder Y


Open the user‘s Credentials folder shell:CredentialManager User folder Y
Open the user‘s desktop folder shell:Desktop User folder Y
Open the user‘s Documents folder shell:Personal User folder Y
Open the user‘s downloads folder shell:Downloads User folder Y
Open the user‘s encryption keys folder shell:Cryptokeys User folder Y
Open the user‘s Game Explorer folder shell:GameTasks User folder
Open the user‘s History folder shell:History User folder
Open the user‘s Links folder shell:Links User folder Y
Open the user‘s Network Places folder shell:NetHood User folder Y
Open the user‘s printer shortcuts folder shell:PrintHood User folder Y
Open the user‘s profile folder (same as
shell:Profile User folder Y
% USERPROFILE%)

Open the user‘s Send To folder shell:SendTo User folder Y


Open the user‘s Start Menu folder shell:Start Menu User folder Y
Open the user‘s Start Menu Programs folder shell:Programs User folder Y
Open the user‘s Startup folder shell:Startup User folder Y
Open the user‘s Templates folder shell:Templates User folder Y
Open the user‘s Windows Contacts folder shell:Contacts User folder Y
Open the user‘s Recent Documents folder shell:Recent User folder Y
Opens the user‘s AppData\Roaming\Microsoft\Protect
shell:DpAPIKeys User folder Y
folder
Display 32-bit programs stored on 64-bit Windows, Internet

https://ss64.com/nt/shell.html[8/24/2017 10:33:23 AM]


Shell folder shortcuts - Windows CMD - SS64.com

shell:ProgramFilesX86
or the \Program Files folder on 32-bit Windows Explorer
Internet
Display the Control Panel shell:ControlPanelFolder
Explorer
Open the user‘s Start Menu\Administrative Tools Internet
shell:Administrative Tools Y
folder (if any) Explorer
shell:Immersive Application Internet
Display Metro App shortcuts (Windows 8) Shortcuts Explorer
shell:Common Administrative Internet
Open All Users Start Menu\Administrative Tools folder
Tools Explorer
Internet
Launches Internet Explorer Applets and applications shell:InternetFolder
Explorer
Open the Common Files for 32-bit programs stored on
64-bit Windows, Internet
shell:ProgramFilesCommonX86
Or the Program Files\Common Files folder on 32-bit Explorer
Windows
Open the Control Panel "Install a program from the shell:AddNewProgramsFolder
Internet
network" applet Explorer
Open the Control Panel "Uninstall or change a Internet
shell:ChangeRemoveProgramsFolder
program" applet Explorer
Internet
Open the default Sidebar Gadgets folder shell:Default Gadgets
Explorer
Internet
Open the hidden ImplicitAppShortcuts folder shell:ImplicitAppShortcuts Y
Explorer
Internet
Open the Internet Explorer Cookies folder shell:Cookies Y
Explorer
Internet
Open the Internet Explorer Favorites folder shell:Favorites Y
Explorer
Internet
Open the list of Network Connections shell:ConnectionsFolder
Explorer
Open the Program Files folder (same as Internet
shell:ProgramFiles
% PROGRAMFILES%) Explorer
Internet
Open the Program Files\Common Files folder shell:ProgramFilesCommon
Explorer
Internet
Open the Temporary Internet Files folder shell:Cache
Explorer
Internet
Open the user folder of downloaded Sidebar Gadgets shell:Gadgets
Explorer
Internet
Open the Windows Search tool shell:SearchHomeFolder
Explorer
Display public libraries, if any shell:PublicLibraries Library
Display your Music library shell:MusicLibrary Library
Display your Pictures library shell:PicturesLibrary Library
Display your Videos library shell:VideosLibrary Library
Open the Documents library shell:DocumentsLibrary Library

https://ss64.com/nt/shell.html[8/24/2017 10:33:23 AM]


Shell folder shortcuts - Windows CMD - SS64.com

Open the Libraries folder shell:Libraries Library


Open the Windows Photo Gallery Original Images
shell:Original Images Multimedia
folder, if installed
Open the Public Music folder shell:CommonMusic Multimedia
Open the Public Pictures folder shell:CommonPictures Multimedia
Open the Public Video folder shell:CommonVideo Multimedia
Open the Sample Music folder shell:SampleMusic Multimedia
Open the Sample Pictures folder shell:SamplePictures Multimedia
Open the Sample Videos folder shell:SampleVideos Multimedia
Open the user‘s Music folder shell:My Music Multimedia Y
Open the user‘s Pictures folder shell:My Pictures Multimedia Y
Open the user‘s Pictures\Slide Shows folder (if
shell:PhotoAlbums Multimedia Y
present)
Open the user‘s Videos folder shell:My Video Multimedia Y
Windows Sync
Display Sync Centre shell:SyncCenterFolder
Centre
Windows Sync
Display Sync Centre Conflicts shell:ConflictFolder
Centre
Windows Sync
Display Sync Centre Results shell:SyncResultsFolder
Centre
Windows Sync
Open the Sync Centre Setup options shell:SyncSetupFolder
Centre

Unless indicated otherwise, all the shortcuts above work in all versions of Windows from Vista upwards.

Shell folder shortcuts can be used directly in the Windows Explorer Address bar:  shell:Desktop

Or in the Start Menu Start | Run | shell:Desktop

Or from the command line:


C:\> explorer shell:desktop
C:\> start shell:desktop

The START command does also accept Shell shortcuts with spaces but they have to be quoted like so:
C:\> start "" "shell:my music "

“You go away for a long time and return a different person - you never come all the way back” ~ Paul Theroux

Related

EXPLORER - Open Windows Explorer


ProfileFolders - Location of user profile folders.
Env. Variables - List of environment variables.
RUN commands Start | Run commands.

https://ss64.com/nt/shell.html[8/24/2017 10:33:23 AM]


Shell folder shortcuts - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/shell.html[8/24/2017 10:33:23 AM]


User Shell Folders - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

User Shell Folders - Profile, Start Menu folder...


In Windows 7/2008 the main User Profile folder ( %USERPROFILE% ) has moved from C:\Documents and Settings\ to C:\Users\
and many profile folders have also changed name or location:
Windows XP/2003 Windows 7/2008
%USERPROFILE%\Application Data %USERPROFILE%\AppData\Roaming
%USERPROFILE%\Cookies %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Cookies
%USERPROFILE%\History %USERPROFILE%\AppData\Local\Microsoft\Windows\History
%USERPROFILE%\Local Settings %USERPROFILE%\AppData\Local
%USERPROFILE%\My Documents %USERPROFILE%\Documents
%USERPROFILE%\NetHood %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Network Shortcuts
%USERPROFILE%\PrintHood %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Printer Shortcuts
%USERPROFILE%\Recent %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Recent
%USERPROFILE%\SendTo %USERPROFILE%\AppData\Roaming\Microsoft\Windows\SendTo
%USERPROFILE%\Start Menu %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu
%USERPROFILE%\Templates %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Templates
%USERPROFILE%\Temporary Internet Files %USERPROFILE%\AppData\Local\Microsoft\Windows\Temporary Internet Files
Windows XP/2003 Windows 10/2012 R2
%USERPROFILE%\Application Data %USERPROFILE%\AppData\Roaming
%USERPROFILE%\Cookies %USERPROFILE%\AppData\Local\Microsoft\Windows\INetCookies
%USERPROFILE%\History %USERPROFILE%\AppData\Local\Microsoft\Windows\History
%USERPROFILE%\Local Settings %USERPROFILE%\AppData\Local
%USERPROFILE%\My Documents %USERPROFILE%\Documents
%USERPROFILE%\NetHood %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Network Shortcuts
%USERPROFILE%\PrintHood %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Printer Shortcuts
%USERPROFILE%\Recent %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Recent Items
%USERPROFILE%\SendTo %USERPROFILE%\AppData\Roaming\Microsoft\Windows\SendTo
%USERPROFILE%\Start Menu %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu
%USERPROFILE%\Templates %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Templates
%USERPROFILE%\Temporary Internet Files %USERPROFILE%\AppData\Local\Microsoft\Windows\INetCache

The values above can be found in the registry (as REG_EXPAND_SZ values)
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

The following HKCU registry subkeys are common to Windows XP/2003/7/2008 :


AppData, Cache, Cookies, Desktop, Favorites, History, LocalAppData, My Pictures, NetHood, Personal, PrintHood,
Programs, Recent, SendTo, Start Menu, Startup, Templates.

By default these all resolve to subfolders below %USERPROFILE% but they can be redirected to other locations.
The registry locations are always the same, but the files and folders may be in different places.

To provide backwards compatibility, in Windows 7 and above the old locations under C:\Documents and Settings contain
junction points (hidden, protected operating system files) which point to the new user-accessible folders.

'All Users' Shell Folders


The folders for All Users settings have also moved:
Windows XP/2003 Windows 7/2008
%ALLUSERSPROFILE%\Application Data %ProgramData%
%ALLUSERSPROFILE%\Desktop %PUBLIC%\Desktop
%ALLUSERSPROFILE%\Documents %PUBLIC%\Documents
%ALLUSERSPROFILE%\Start Menu\Programs %ProgramData%\Microsoft\Windows\Start Menu\Programs
%ALLUSERSPROFILE%\Start menu %ProgramData%\Microsoft\Windows\Start Menu
%ALLUSERSPROFILE%\Start Menu\Programs\Startup %ProgramData%\Microsoft\Windows\Start
Menu\Programs\Startup
%ALLUSERSPROFILE%\Templates %ProgramData%\Microsoft\Windows\Templates
Windows XP/2003 Windows 10/2012 R2
%ALLUSERSPROFILE%\Application Data %ProgramData%
%ALLUSERSPROFILE%\Desktop %PUBLIC%\Public Desktop
%ALLUSERSPROFILE%\Documents %PUBLIC%\Public Documents
%ALLUSERSPROFILE%\Start Menu\Programs %ProgramData%\Microsoft\Windows\Start Menu\Programs *
%ALLUSERSPROFILE%\Start menu %ProgramData%\Microsoft\Windows\Start Menu *
%ALLUSERSPROFILE%\Start Menu\Programs\Startup %ProgramData%\Microsoft\Windows\Start
Menu\Programs\Startup *
%ALLUSERSPROFILE%\Templates %ProgramData%\Microsoft\Windows\Templates

https://ss64.com/nt/syntax-folders.html[8/24/2017 10:33:33 AM]


User Shell Folders - Windows CMD - SS64.com

* In Windows 10 the Start Menu items are held in a database that is stored under
C:\Users\accountname\AppData\Local\TileDataLayer this is proprietary, non user editable and limited to 500
shortcuts. It is also used for Cortana Search. The entire database can be copied between accounts - all or nothing.

The values above can be found in the registry (as REG_EXPAND_SZ values)
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
The entries in this subkey can appear in both the Shell Folders subkey and the User Shell Folders and in both
HKLM and HKCU. The entries that appear in User Shell Folders take precedence over those in Shell Folders.
The entries that appear in HKCU take precedence over those in HKLM

The following HKLM registry subkeys are common to Windows XP/2003/7/2008 :


Common AppData, Common Desktop, Common Documents, Common Programs, Common Start Menu, Common Startup,
Common templates

Folder Redirection
Although it is possible to redirect any of these folders with Group Policy, not all options are fully supported,
for example redirecting IE favorites/cookies will result in very slow performance.

Examples

Find the location of the Start Menu folder:


For /f "tokens=3*" %%G in ('REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell
Folders" /v "Start Menu" ^|Find "REG_"') do Call Set _startmenu=%%H

Echo %_startmenu%

PowerShell function to open the Start menu:


function Open-StartMenu {
$drive = dir env:SystemDrive
$w7path = $drive.value + "\ProgramData\Microsoft\Windows\Start Menu"
$xppath = $drive.value + "\Documents and Settings\All Users\Start Menu"
if (test-path $w7path)
 {explorer $w7path}
elseif (test-path $xppath) {explorer $xppath}
}

“There are no shortcuts to any place worth going” - Beverly Sills

Related:

Shell: folder - Shortcuts to key folders.


Windows Environment Variables
RoamingProfile.vbs - Cleardown files to improve logon and logoff times.
Managing Roaming User Data Deployment Guide - TechNet (html and .doc)
Q886549 - User Shell Folders

https://ss64.com/nt/syntax-folders.html[8/24/2017 10:33:33 AM]


User Shell Folders - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-folders.html[8/24/2017 10:33:33 AM]


Windows Environment Variables - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Windows Environment Variables


Environment variables are mainly used within batch files, they can be created, modified and deleted for a session using the
SET command. To make permanent changes, use SETX

Variables can be displayed using either SET or ECHO.

Variables have a percent sign on both sides: %ThisIsAVariable%


The variable name can include spaces, punctuation and mixed case: %_Another Ex.ample%
(This is unlike Parameter variables which only have one % sign and are always one character long: %A )

A variable name may include any of the following characters:


A-Z, a-z, 0-9, # $ ' ( ) * + , - . ? @ [ ] _ ` { } ~

Array variables
Unlike PowerShell, which fully supports arrays, there is no built in support for array variables within the CMD shell.
However with some effort you can replicate this functionality using a series of separate variables, named to
represent the array:
Set elem[1]=First element
Set elem[2]=Second one
Set elem[3]=The third one

To perform array indexing operations with these, use EnableDelayedExpansion and a reference like
!elem[%var%]!
this is explained fully in this StackOverflow Q/A.

Standard (built-in) Environment Variables


Volatile
Default value in Windows 7/10/2008 (assuming the system drive is C:
Variable (Read-
)
Only)
ALLUSERSPROFILE   C:\ProgramData
APPDATA   C:\Users\{username}\AppData\Roaming
CD Y The current directory (string).

ClientName Y Terminal servers only - the ComputerName of a remote host.

The current Command Processor Extensions version number. (NT = "1",


CMDEXTVERSION Y
Win2000+ = "2".)
CMDCMDLINE Y The original command line that invoked the Command Processor.
CommonProgramFiles   C:\Program Files\Common Files
COMMONPROGRAMFILES(x86)   C:\Program Files (x86)\Common Files
COMPUTERNAME   {computername}
C:\Windows\System32\cmd.exe or if running a 32 bit WOW -
COMSPEC  
C:\Windows\SysWOW64\cmd.exe
DATE Y The current date using same region specific format as DATE.

The current ERRORLEVEL value, automatically set when a program


ERRORLEVEL Y
exits.

FPS_BROWSER_APP_PROFILE_STRING
Internet Explorer

https://ss64.com/nt/syntax-variables.html[8/24/2017 10:33:42 AM]


Windows Environment Variables - Windows CMD - SS64.com

Default
FPS_BROWSER_USER_PROFILE_STRING  
These are undocumented variables for the Edge browser in Windows
10.
Y
HighestNumaNodeNumber The highest NUMA node number on this computer.
(hidden)
HOMEDRIVE Y C:
HOMEPATH Y \Users\{username}
LOCALAPPDATA   C:\Users\{username}\AppData\Local
LOGONSERVER   \\{domain_logon_server}
NUMBER_OF_PROCESSORS Y The Number of processors running on the machine.

OS Y Operating system on the user's workstation.

User
C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem;{plus
PATH and
program paths}
System
.COM; .EXE; .BAT; .CMD; .VBS; .VBE; .JS ; .WSF; .WSH; .MSC
PATHEXT
The syntax is like the PATH variable - semicolon separators.
AMD64/IA64/x86 This doesn't tell you the architecture of the processor
PROCESSOR_ARCHITECTURE Y but only of the current process, so it returns "x86" for a 32 bit WOW
process running on 64 bit Windows. See detecting OS 32/64 bit
PROCESSOR_ARCHITEW6432   = %ProgramFiles% (only available on 64 bit systems)

PROCESSOR_IDENTIFIER Y Processor ID of the user's workstation.

PROCESSOR_LEVEL Y Processor level of the user's workstation.

PROCESSOR_REVISION Y Processor version of the user's workstation.


ProgramW6432   = %PROCESSOR_ARCHITECTURE% (only available on 64 bit systems)
ProgramData   C:\ProgramData
ProgramFiles   C:\Program Files or C:\Program Files (x86)

ProgramFiles(x86) 1   C:\Program Files (x86)

Code for current command prompt format,usually $P$G


PROMPT  
C:>

PSModulePath   %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\
Public   C:\Users\Public
RANDOM Y A random integer number, anything from 0 to 32,767 (inclusive).
Terminal servers only - for a terminal server session, SessionName is a
%SessionName%   combination of the connection name, followed by #SessionNumber. For
a console session, SessionName returns "Console".
SYSTEMDRIVE   C:
By default, Windows is installed to C:\Windows but there's no guarantee
of that, Windows can be installed to a different folder, or a different drive
letter.
SYSTEMROOT  
systemroot is a read-only system variable that will resolve to the correct
location.
NT 4.0, Windows 2000 and Windows NT 3.1 default to C:\WINNT

https://ss64.com/nt/syntax-variables.html[8/24/2017 10:33:42 AM]


Windows Environment Variables - Windows CMD - SS64.com

User C:\Users\{Username}\AppData\Local\Temp
TEMP and TMP
Variable Under XP this was \{username}\Local Settings\Temp
TIME Y The current time using same format as TIME.

Y
Set if a user is a logged on to a domain and returns the fully qualified
UserDnsDomain User
DNS domain that the currently logged on user's account belongs to.
Variable
USERDOMAIN   {userdomain}
The user domain for RDS or standard roaming profile paths. Windows
USERDOMAIN_roamingprofile  
8/10/2012 (or Windows 7/2008 with Q2664408)
USERNAME   {username}
%SystemDrive%\Users\{username}
USERPROFILE  
This is equivalent to the $HOME environment variable in Unix/Linux

%WinDir% pre-dates Windows NT and seems to be superseded by


%SystemRoot%
WINDIR   Set by default as windir=%SystemRoot%
%windir% is a regular variable and can be changed, which makes it less
robust than %systemroot%

1 Only on 64 bit systems, is used to store 32 bit programs.

Unless stated otherwise, all the variables above are System variables

Environment variables are stored in the registry:

User Variables: HKEY_CURRENT_USER\Environment


System Variables: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

By default, files stored under Local Settings do not roam with a roaming profile.

Dynamic environment variables are read-only and are computed each time the variable is expanded. When all variables are
listed with SET, these will not appear in the list. Do not attempt to directly SET a dynamic variable. 

Undocumented Dynamic variables (read only)


%__APPDIR__%   The directory path to the current application .exe, terminated with a trailing backslash. (Global) -
discuss
%__CD__%   The current directory, terminated with a trailing backslash. (Global)
%=C:%   The current directory of the C: drive.
%=D:%   The current directory of the D: drive if drive D: has been accessed in the current CMD session.
%DPATH%   Related to the (deprecated) DPATH command.
%=ExitCode%   The most recent exit code returned by an external command, such as CMD /C EXIT n, converted to
hex.
%=ExitCodeAscii%   The most recent exit code returned by an external command, as ASCII. (Values 0-32 do not
display because those map to ASCII control codes.)
%FIRMWARE_TYPE% The boot type of the system: Legacy ,UEFI,Not implemented ,Unknown Windows 8/2012.
%KEYS%   Related to the (deprecated) KEYS command.
More detail on these undocumented variables can be found in this stackoverflow answer from Dave Benham.

Undocumented Dynamic variables (read/write)


%__COMPAT_LAYER%   Set the ExecutionLevel to either RunAsInvoker (asInvoker), RunAsHighest (highestAvailable) or
RunAsAdmin (requireAdministrator) for more see elevation and Q286705 / Application Compatibility Toolkit for other
Compatibility Layers (colours,themes etc).

https://ss64.com/nt/syntax-variables.html[8/24/2017 10:33:42 AM]


Windows Environment Variables - Windows CMD - SS64.com

Pass variables between batch scripts


There are several ways to pass values between batch files, or between a batch file and the command line, see the
CALL and SETLOCAL pages for full details.

A child process by default inherits a copy of all environment variables from its parent, this makes environment
variables unsuitable for storing secret information such as API keys or user passwords, especially in rare
occasions like crashes where a crash log will often include the full OS environment at the time of the crash.
PowerShell/Get-Credential is a more secure approach.

“Men may be convinced, but they cannot be pleased against their will. But though taste is obstinate, it is very variable, and time often
prevails when arguments have failed” ~ Samuel Johnson

Related:

PowerShell - Working with Environment variables


User Shell Folders - Standard folder locations.
Detecting 32 vs 64 bit Windows
CALL - Evaluate environment variables
SET - View environment variables, set local variables
SETX - Set environment variables
Q100843 - The four types of environment variable
Q286705 - Set compatibility variables
Q242557 - Registry Settings for Folder Redirection
StackOverflow - Storing a Newline in a variable
Managing Roaming User Data Deployment Guide - Microsoft.com (Word Doc)

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-variables.html[8/24/2017 10:33:42 AM]


Command Redirection, Pipes - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Redirection
command > filename Redirect command output to a file
command >> filename APPEND into a file
command < filename Type a text file and pass the text to command
commandA | commandB Pipe the output from commandA into commandB
commandA & commandB Run commandA and then run commandB
commandA && commandB Run commandA, if it succeeds then run commandB
commandA || commandB Run commandA, if it fails then run commandB
commandA && commandB || commandC
If commandA succeeds run commandB, if it fails commandC

Success and failure are based on the Exit Code of the command.
In most cases the Exit Code is the same as the ErrorLevel
Numeric handles:
STDIN = 0 Keyboard input
STDOUT = 1 Text output
STDERR = 2 Error text output
UNDEFINED = 3-9
command 2> filename Redirect any error message into a file
command 2>> filename Append any error message into a file
(command)2> filename Redirect any CMD.exe error into a file
command > file 2>&1 Redirect errors and output to one file
command > fileA 2> fileB Redirect output and errors to separate files
command 2>&1 >filename This will fail!
Redirect to NUL (hide errors)
command 2> nul Redirect error messages to NUL
command >nul 2>&1 Redirect error and output to NUL
command >filename 2> nul Redirect output to file but suppress error
(command)>filename 2> nul Redirect output to file but suppress CMD.exe errors

Any long filenames must be surrounded in "double quotes".


A CMD error is an error raised by the command processor itself rather than the program/command.

Redirection with > or 2> will overwrite any existing file.

You can also redirect to a printer with > PRN or >LPT1

Multiple commands on one line


In a batch file the default behaviour is to read and expand variables one line at a time, if you use & to run multiple
commands on a single line, then any variable changes will not be visible until execution moves to the next line. For
example:

 SET /P _cost="Enter the price: " & ECHO %_cost%

This behaviour can be changed using SETLOCAL EnableDelayedExpansion

Creating a new file


Create empty files using the NUL device:

Type NUL >EmptyFile.txt


or
Copy NUL EmptyFile.txt

To prevent the > and < characters from causing redirection, escape with a caret: ^> or ^<

https://ss64.com/nt/syntax-redirection.html[8/24/2017 10:33:51 AM]


Command Redirection, Pipes - Windows CMD - SS64.com

Redirect multiple lines by bracketing a set of commands:


(
Echo sample text1
Echo sample text2
) > c:\logfile.txt

Exit Codes
If the filename or command is not found then redirection will set an Exit Code of 1

Unicode
The CMD Shell can redirect ASCII/ANSI (the default) or Unicode (UCS-2 le) but not UTF-8.
This can be selected by launching CMD /A or CMD /U

With the default settings a UCS-2 file can be converted by redirecting it (note it's the redirection not the
TYPE/MORE command that makes the encoding change)
TYPE unicode.txt > asciifile.txt

European characters like ABCàéÿ will usually convert correctly, but others like £¥ƒ€ will become random extended
ASCII characters: œ¾Ÿ?

Pipes and CMD.exe


When a command is piped with '| batch_command ' this will instantiate a new CMD.exe instance, in effect running:

C:\Windows\system32\cmd.exe /C /S /D "batch_command"

This has several side effects:


Any newline (CR/LF) characters in the batch_command will be turned into & operators. (see StackOverflow)
If the batch_command includes any caret escape characters ^ they will need to be doubled up so that the escape
survives into the new CMD shell.

Starting a new CMD shell also has a small (likely unnoticable) effect on performance.

For example, this syntax works, but would fail if the second or subsequent (piped) lines were indented with a
space:
@Echo Off
echo abc def |^
find "abc" |^
find "def"> outfile.txt

Multi-line single commands with lots of parameters, can be indented as in this example:

Echo abc def ^


  ghi jkl ^
  mno pqr

When redirecting the output of DIR to a file, you may notice that the output file (if in the same folder) will be listed with a size
of 0 bytes. The command interpreter first creates the empty destination file, then runs the DIR command and finally saves the
redirected text into the file.

The maximum number of consecutive pipes is 2042

Examples:
DIR >MyFileListing.txt
DIR /o:n >"Another list of Files.txt"
DIR C:\ >List_of_C.txt 2>errorlog.txt
DIR C:\ >List_of_C.txt & DIR D:\ >List_of_D.txt

https://ss64.com/nt/syntax-redirection.html[8/24/2017 10:33:51 AM]


Command Redirection, Pipes - Windows CMD - SS64.com

ECHO y| DEL *.txt


ECHO Some text ^<html tag^> more text
COPY nul empty.txt
MEM /C >>MemLog.txt
Date /T >>MemLog.txt
SORT < MyTextFile.txt
SET _output=%_missing% 2>nul
FIND /i "Jones" < names.txt >logfile.txt
(TYPE logfile.txt >> newfile.txt) 2>nul

“Stupidity, outrage, vanity, cruelty, iniquity, bad faith, falsehood,


we fail to see the whole array when it is facing in the same direction as we” ~ Jean Rostand (French Historian)

Related:

conIN$ and conOUT$ behave like stdin and stdout, or 0 and 1 streams but only with internal commands.
CMD Syntax
TYPE - Display the contents of one or more text files
Q245031 - Error when using the | pipe symbol
Successive redirections explained ( 1>&3 ) - Stack Overflow
Equivalent bash command (Linux): Redirection - Spooling output to a file, piping input.

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-redirection.html[8/24/2017 10:33:51 AM]


Conditional Execution AND OR IF - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Conditional Execution
Syntax

if command1 succeeds then execute command2 (IF)

command1 && command2

Execute command1 and then execute command2 (AND)

command1 & command2

Execute command2 only if command1 fails (OR)

command1 || command2

Success is defined as returning an %ERRORLEVEL% = 0

Care must be taken in using this syntax to read and SET variables as by default variables are expanded one line at a time.

Examples

Show a message if a file copy succeeds:


COPY H:\share\TNSnames.ora C:\Oracle\ && ECHO The Copy succeeded

Use parenthesis to test the success of several commands:


(Dir C:\Test1 & Dir C:\Test2) || Echo One or more of the commands failed.

“Conditional cooperation is like adulterated cement which does not bind” ~ Mohandas K. Gandhi

Related:

IF - Conditionally perform a command.


Command redirection

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-conditional.html[8/24/2017 10:34:00 AM]


Loops (batch file) - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Loops and subroutines


There are 2 ways to conditionally process commands in a batch file

IF xxx ELSE yyy - will conditionally perform a command (or a set of commands)

FOR aaa DO xxx - will conditionally perform a command several times (for a set of data, or a set of files)

Either of these can be combined with the CALL command to run a subroutine like this:
@echo off
IF EXIST C:\pagefile.sys CALL :s_page_on_c
IF EXIST D:\pagefile.sys CALL :s_page_on_d
GOTO :eof
:s_page_on_c
echo pagefile found on C: drive
GOTO :eof
:s_page_on_d
echo pagefile found on D: drive

Without the : a second batch file will be called ...


@ECHO off
IF EXIST C:\pagefile.sys CALL Second_Batch.cmd

If the code does not need to return then use the GOTO statement like this:
@ECHO off
IF EXIST C:\pagefile.sys GOTO s_page_on_c
ECHO pagefile not found
GOTO :eof
:s_page_on_c
ECHO pagefile found

To call a second batch file in a separate shell use CMD An important difference between CALL and CMD is the exit behaviour
if an error occurs.
@ECHO off
IF EXIST C:\pagefile.sys CMD /C Second_Batch.cmd

"I knew of one little DO loop that ran for 48 hours, cost $14,000 and did nothing" ~ Richard Keeler

Related:

Syntax: Parameters - Command Line Parameters %1 %~f1


Syntax: Functions - How to package blocks of code

Copyright © SS64.com 1999-2017

https://ss64.com/nt/syntax-loops.html[8/24/2017 10:34:09 AM]


Loops (batch file) - Windows CMD - SS64.com

 
Some rights reserved

https://ss64.com/nt/syntax-loops.html[8/24/2017 10:34:09 AM]


Functions - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Batch file Functions


Packaging up code into a discrete functions, each with a clear purpose is a very common programming technique. Re-using
known, tested code, means you can solve problems very quickly by just bolting together a few functions.

The CMD shell does not have any documented support for functions, but you can fake it by passing arguments/parameters to
a subroutine and you can use SETLOCAL to control the visibility of variables.

A common first attempt at building a function:


:myfunct
SETLOCAL
SET _var1=%1
SET _var2="%_var1%--%_var1%--%_var1%"
SET _result=%_var2%
ENDLOCAL

but there is a problem, the ENDLOCAL command will throw away the _result variable and so the function returns nothing.

:myfunct2
SETLOCAL
SET _var1=%1
SET _var2="%_var1%--%_var1%--%_var1%"
ENDLOCAL
SET _result=%_var2%

This version is getting close, but it still fails to return a value, this time because ENDLOCAL will throw away the _var2 variable

The solution to this is to take advantage of the fact that the CMD shell evaluates variables on a line-by-line basis - so placing
ENDLOCAL on the same line as the SET statement(s) gives the result we want. This technique is known as 'tunneling' and
works for both functions and entire batch scripts:

:myfunct3
SETLOCAL
SET _var1=%1
SET _var2="%_var1%--%_var1%--%_var1%"
ENDLOCAL & SET _result=%_var2%

In examples above there are just 2 local variables (_var1 and _var2) but in practice there could be far more, by turning the
script into a function with SETLOCAL and ENDLOCAL we don’t have to worry if any variable names will clash.

In other words you can do this:


@ECHO OFF
SET _var1=64
SET _var2=123
CALL :myfunct3 Testing
echo _var1 is %_var1%
echo Final result %_result%
goto :eof

:myfunct3
SETLOCAL
SET _var1=%1
SET _var2="%_var1%--%_var1%--%_var1%"
ENDLOCAL & SET _result=%_var2%

When working with functions it can be useful to use Filename Parameter Extensions against the function name, %0 will contain
the call label, %~nx0 the file name, see Rob Hubbards blog for an example. Note that if you have two scripts one calling
another, this will not reveal the location of the 'calling' script.

https://ss64.com/nt/syntax-functions.html[8/24/2017 10:34:19 AM]


Functions - Windows CMD - SS64.com

“Cats are intended to teach us that not everything in nature has a function” ~ Garrison Keillor

Related:

CALL - Call one batch program from another


Macros - Embed blocks of code in a variable.
SETLOCAL - Control the visibility of environment variables
SHIFT - Shift the position of replaceable parameters in a batch file
DosTips - A collection of CMD functions

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-functions.html[8/24/2017 10:34:19 AM]


Batch file macros | cmd - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Batch file macros


A macro allows you to embed blocks of code in a variable. Like calling a subroutine or function this allows reusing the same
block of code multiple times, the difference is that by placing the code in a variable the performance will be much faster.

This is an advanced technique but can be very useful in scripts that include large blocks of code or looping commands where
the performance of other methods is too slow.

A macro which runs exit /b


set _ex=exit /b

You can then exit a subroutine with:


%_ex%

A macro which lists all the .XLS files in a folder:


Set _macro=Dir c:\demo\*.xls

We can now run the Macro like this:


%_macro%

So far so like the DOSKEY command, but to make this more powerfull you will want to pass arguments to the macro, in the
example above you might want to pass the name of the folder to be listed.

Passing arguments to a macro is not particularly easy, the best method (discovered by Jeb) is to place a For /L command
within the macro, set to run 2 steps each time the macro is run:

In the first step the arguments are stored in a variable ( argv )


In the second step the main body of the macro runs and can (optionally) read the variable

The basic structure of the macro definition:


Set _macro=For /l %%n in (1 1 2) do if %%n==2 (Echo Main MACRO goes here.) else setlocal enableDelayedExpansion
^& Set argv=,
%_macro% arg1 arg2
:: The macro will expand to:
:: for /l %%n in (1 1 2) do if %%n==2 (Echo Main MACRO goes here.) else setlocal enableDelayedExpansion & Set
argv=, arg1 arg2
:: which is equivalent to:
:: setlocal enableDelayedExpansion
:: Set argv= arg1 arg2
:: Echo Main MACRO goes here.

Example:
@echo off
cls
setlocal DisableDelayedExpansion
set LF=^

::Above 2 blank lines are required - do not remove


set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
set _macrodemo=for /L %%n in (1 1 2) do if %%n==2 (%\n%
for /F "tokens=1 delims=, " %%G in ("!argv!") do (%\n%
echo _argument1=%%G %\n%
set "_argument1=!%%~G!"%\n%
dir !_argument1!\*.xls%\n%
) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,
set "_testfolder=c:\demo"
%_macrodemo% _testfolder

https://ss64.com/nt/syntax-macros.html[8/24/2017 10:34:28 AM]


Batch file macros | cmd - Windows CMD - SS64.com

In a macro where more than one argument need to be passed, these will become tokens 2,3,4... in the FOR / F command.

A library of macros can be defined by running a single MACROS.CMD batch file, allowing the library macros to be used in
multiple batch files.

Credits: Ed Dyreen, Jeb and Dave Benham, the original dostips forum threads are here and here.

“Macro dictionary definition: 1. Large 2. Long 3. Inclusive” ~ from the Greek 'makros'

Related:

functions - How to package blocks of code.


CALL - Call one batch program/subroutine from another
How the %LF% newline variable hack works - StackOverflow
DOSKEY - Edit command line, recall commands, and create macros

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-macros.html[8/24/2017 10:34:28 AM]


Windows 7 Services - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Windows 7 Services
A list of the default services in Windows 7.

Service
Default Status &
Display Name Service (Registry Key) Process Description
notes

Provides UACl
ActiveX validation for the
Installer AxInstSV svchost.exe / audiosrv.dll installation of ActiveX Manual
(AxInstSV) controls from the
Internet.
Monitors ambient light
sensors to detect Manual, can be
Adaptive
SensrSvc svchost.exe / sensrsvc.dll changes in ambient disabled if no light
Brightness
light and adjust the sensors available)
display brightness.
Processes application
compatibility cache
Application
AeLookupSvc svchost.exe / aelupsvc.dll requests for Manual
Experience
applications as they
are launched
Not Installed.
Application
Optional feature
Host Helper AppHostSvc
(Control Panel add
Service
features)
Manual.
Determines and Disabling this
Application
AppIDSvc svchost.exe / appidsvc.dll verifies the identity of service will prevent
Identity
an application. AppLocker from
being enforced.
Facilitates the running
of interactive
Application applications with
Appinfo svchost.exe /appinfo.dll Manual (Started)
Information additional
administrative
privileges.
Provides support for
Application
3rd party protocol
Layer Gateway ALG alg.exe Manual
plug-ins for Internet
Service
Connection Sharing
Processes
installation, removal,
Application and enumeration
AppMgmt svchost.exe / appmgmts.dll Manual
Management requests for software
deployed through
Group Policy.
Optional feature
ASP.NET State
aspnet_state aspnet_state.exe (Control Panel add
Service
features)

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

Manual.
Transfer files using If disabled, then
idle network applications that
Background
bandwidth, maintain depend on BITS,
Intelligent
BITS svchost.exe / qmgr.dll file transfers through such as Windows
Transfer
network Update, will be
Service
disconnections and unable to
computer restarts. automatically
download files.
Manages firewall and
Base Filtering Automatic
BFE svchost.exe / bfe.dll IPsec policies and
Engine (Started)
user mode filtering.
Provides secure
BitLocker Drive
startup for theOS, as
Encryption BDESVC svchost.exe / bdesvc.dll Manual
well as full volume
Service
encryption.
The WBENGINE
Block Level service is used by
Backup Engine wbengine wbengine.exe Windows Backup to Manual
Service perform backup and
recovery operations.
Manual.
Bluetooth Discovery and If stopped
Support bthserv svchost.exe / bthserv.dll association of remote Bluetooth devices
Service Bluetooth devices. will fail to operate
properly.
Caches network
BranchCache PeerDistSvc peerdistsvc.dll content from peers on Manual
the local subnet.
Copies user
certificates and root
certificates from smart
cards into the current
user's certificate
Certificate store, detects when a
CertPropSvc svchost.exe / certprop.dll Manual
Propagation smart card is inserted
into a smart card
reader, and, if
needed, installs the
smart card Plug and
Play minidriver.
Not Installed.
Optional feature in
Ultimate/Enterprise
Client for NFS NfsClnt
edition (Control
Panel add
features)
Provides key process
isolation to private
LSASS.exe (Local Security keys and associated
CNG Key
KeyIso Authority Subsystem) cryptographic Manual
Isolation
/ keyiso.dll operations as required
by the Common
Criteria.
Provides automatic

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

COM+ Event distribution of events Automatic


EventSystem svchost.exe / comres.dll
System to subscribing COM (Started)
components.
COM+ System
COMSysApp dllhost.exe Manual
Application
Collects the names of
NetBIOS resources
on the network,
creating a list so that it Manual.
can participate as a If disabled you can
master browser or still map drives,
basic browser (one but can't browse
Computer
Browser svchost.exe / browser.dll that takes part in the whole network.
Browser
browser elections).
This has no effect
This maintained list of on TCP/IP or
resources internet browsing
(computers) is
displayed in Network
Neighborhood.
Provides secure
storage and retrieval
LSASS.exe (Local Security
Credential of credentials to
VaultSvc Authority Subsystem) Manual
Manager users, applications
/ vaultsvc.dll
and security service
packages.
Confirm the
signatures of
Windows files, add
and remove Trusted
Cryptographic Automatic
CryptSvc svchost.exe / cryptsvc.dll Root Certification
Services (Started)
Authority certificates,
retrieve root
certificates from
Windows Update.
Automatic
(Started)
Launches COM and
DCOM Server If this service is
DCOM servers in
Process DcomLaunch svchost.exe / oleres.dll stopped, programs
response to object
Launcher using COM or
activation requests.
DCOM will not
function properly.
Desktop
Provides Desktop
Window
Window Manager Automatic
Manager UxSms svchost.exe / dwm.exe
startup and (Started)
Session
maintenance services
Manager
Automatic
(Started)
Registers and If this service is
updates IP addresses stopped, this
DHCP Client Dhcp svchost.exe / dhcpcore.dll
and DNS records for computer will not
this computer. receive dynamic IP
addresses and
DNS updates.
Enables problem

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

detection,
Diagnostic troubleshooting and Automatic
DPS svchost.exe / dps.dll
Policy Service resolution for (Started)
Windows
components.
Diagnostic Policy
Diagnostic Service - diagnostics
WdiServiceHost svchost.exe / wdi.dll Manual (Started)
Service Host that need to run in a
Local Service context.
Diagnostic Policy
Diagnostic Service - diagnostics
WdiSystemHost svchost.exe / wdi.dll Manual
System Host that need to run in a
Local System context.
Provides Disk
Disk
defragsvc svchost.exe / defragsvc.dll Defragmentation Manual
Defragmenter
Capabilities.
Maintains links
between NTFS files
Distributed Link Automatic
TrkWks svchost.exe / trkwks.dll within a computer or
Tracking Client (Started)
across computers in a
network.
Coordinates
transactions that span
Distributed multiple resource
Transaction MSDTC MSDTC.exe managers, such as Manual
Coordinator databases, message
queues, and file
systems.

Resolves and caches


Domain Name
System (DNS)
Automatic
DNS Client Dnscache discache.sys / dnsapi.dll names, and registers
(Started)
the full computer
name for this
computer.

The core file


LSASS.exe (Local Security encryption technology
Encrypting File
EFS Authority Subsystem) used to store Manual
System (EFS)
/ efssvc.dll encrypted files on
NTFS volumes.
Provides network
authentication in such
Extensible scenarios as 802.1x
Authentication EapHost svchost.exe / eapsvc.dll wired and wireless, Manual
Protocol VPN, and Network
Access Protection
(NAP).
Send or receive Manual
faxes, using a local or Optional feature
Fax Fax fxssvc.exe
network fax (Control Panel add
machine/server. features)
Function Function Discovery
Discovery fdPHost svchost.exe / fdPHost.dll (FD) network Manual (Started)

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

Provider Host discovery providers.


Publish this computer
Function and resources
Discovery attached to this Automatic
FDResPub svchost.exe / fdrespub.dll
Resource computer so they can (Started)
Publication be discovered over
the network.
Group Policy Applies Group Policy Automatic
gpsvc svchost.exe / gpapi.dll
Client settings. (Started)
Manual.
Provides X.509
Enforcement
certificate and key
Health Key and technologies that
management services
Certificate hkmsvc svchost.exe / kmsvc.dll use X.509
for the Network
Management certificates will not
Access Protection
function properly
Agent (NAPAgent).
without this service
Makes local computer
changes associated
HomeGroup with configuration and Automatic
HomeGroupListener svchost.exe / ListSvc.dll
Listener maintenance of the (Started)
homegroup-joined
computer.
Performs networking
tasks associated with
HomeGroup
HomeGroupProvider svchost.exe / provsvc.dll configuration and Manual (Started)
Provider
maintenance of
homegroups.
Enables generic input
access to Human
Human
Interface Devices
Interface hidserv svchost.exe / hidserv.dll Manual
(HID), predefined hot
Device Access
buttons on keyboards,
remote controls,etc.
Optional feature
IIS Admin
IISADMIN (Control Panel add
Service
features)
Hosts the Internet Key
Exchange and
Authenticated Internet
Protocol (AuthIP)
IKE and AuthIP modules. These
IPsec Keying IKEEXT svchost.exe / ikeext.dll keying modules are Manual
Modules used for
authentication and
key exchange in
Internet Protocol
security (IPsec).
Index the contents
and properties of files
on local and remote
computers. Optional feature
Indexing
CISVC Cisvc.exe This can become a (Control Panel add
Service
resource hog if set to features)
scan the entire
volume or multiple

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

volumes.
Enables user
notification of user
input for interactive
Interactive
services, which
Services UI0Detect UIODetect.exe Manual
enables access to
Detection
dialogs created by
interactive services
when they appear.
Provides network
address translation,
Internet addressing, name
Connection SharedAccess svchost.exe / ipnathlp.dll resolution and/or Disabled
Sharing (ICS) intrusion prevention
services for a home or
small office network.
Provides tunnel
connectivity using
IPv6 transition
Automatic
IP Helper iphlpsvc svchost.exe / iphlpsvc.dll technologies (6to4,
(Started)
ISATAP, Port Proxy,
and Teredo), and IP-
HTTPS.
IPsec supports
network-level peer
authentication, data
IPsec Policy origin authentication,
PolicyAgent svchost.exe / polstore.dll Manual
Agent data integrity, data
confidentiality
(encryption), and
replay protection.
Coordinates
transactions between
KtmRm for the Distributed
Distributed Transaction
KtmRm svchost.exe / comres.dll Manual
Transaction Coordinator (MSDTC)
Coordinator and the Kernel
Transaction Manager
(KTM).
Creates a Network
Link-Layer
Map, consisting of PC
Topology
lltdsvc svchost.exe / lltdres.dll and device topology - Manual
Discovery
connectivity and
Mapper
metadata.
Optional feature
LPD Service LPDSVC (Control Panel add
features)
Allows Media Center
Media Center
Extenders to locate
Extender Mcx2Svc svchost.exe / ehres.dll Disabled
and connect to the
Service
computer.
Optional feature
Message Message Queuing
MSMQ mqsvc.exe (Control Panel add
Queuing Q2566230
features)
Message Optional feature

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

Message Queuing
Queuing MSMQTriggers mqtgsvc.exe (Control Panel add
Q2294419
Triggers features)
Microsoft .NET
Automatic
Framework Microsoft .NET
clr_optimization_v2.0.50727 mscorsvw.exe (Delayed Start,
NGEN Framework NGEN
Started
v2.0.50727
Optional feature
Microsoft FTP
ftpsvc (Control Panel add
Service
features)
Manages Internet
SCSI (iSCSI)
Microsoft iSCSI
MSiSCSI svchost.exe / iscsidsc.dll sessions from this Manual
Initiator Service
computer to remote
iSCSI target devices.
Manages software-
Microsoft based volume
Software shadow copies taken
swprv svchost.exe / swprv.dll Manual
Shadow Copy by the Volume
Provider Shadow Copy
service.
Enables relative
prioritization of work
Multimedia based on system-
Automatic
Class MMCSS svchost.exe / mmcss.dll wide task priorities.
(Started)
Scheduler This is intended
mainly for multimedia
applications.
Receives activation
requests and passes
them to the Windows
Net.Msmq Optional feature
Process Activation
Listener NetMsmqActivator SMSSvcHost.exe (Control Panel add
Service. net.msmq
Adapter features)
and
msmq.formatname
protocols
Receives activation
requests and passes
Net.Pipe Optional feature
them to the Windows
Listener NetPipeActivator SMSSvcHost.exe (Control Panel add
Process Activation
Adapter features)
Service. net.pipe
protocol
Receives activation
requests over the
Net.Tcp Optional feature
net.tcp protocol and
Listener NetTcpActivator SMSSvcHost.exe (Control Panel add
passes them to the
Adapter features)
Windows Process
Activation Service.
Net.Tcp Port Provides ability to Optional feature
Sharing NetTcpPortSharing SMSSvcHost.exe share TCP ports over (Control Panel add
Service the net.tcp protocol. features)
Network
Authentication:
LSASS.exe (Local Security
Maintains a secure
Authority Subsystem)
channel between this
Netlogon Netlogon Manual

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

/ netlogon.dll computer and the


domain controller for
 
authenticating users
and services.
Collects and manages
health information for
Network client computers on a
Access network. Health policy
napagent svchost.exe / qagentrt.dll Manual
Protection ensures that the client
Agent computer has the
required software and
settings.
Manages objects in
the Network and Dial-
Up Connections
Network
Netman svchost.exe / netman.dll folder, in which you Manual (Started)
Connections
can view both local
area network and
remote connections.
Identifies the
networks to which the
computer has
connected, collects
Network List and stores properties
netprofm svchost.exe / netprofm.dll Manual (Started)
Service for these networks,
and notifies
applications when
these properties
change.
Collects and stores
configuration
Network information for the
Automatic
Location NlaSvc svchost.exe / nlasvc.dll network and notifies
(Started)
Awareness programs when this
information is
modified.
delivers network
Network Store notifications (e.g.
Automatic
Interface nsi svchost.exe / nsisvc.dll interface
(Started)
Service addition/deleting etc)
to user mode clients.
Maintains the Offline
Files cache, responds Automatic
Offline Files CscService svchost.exe / cscsvc.dll
to user logon/logoff (Started)
events
Parental For backward
WPCSvc svchost.exe Manual
Controls compatibility only.
Enables serverless
peer name resolution
Peer Name
over the Internet
Resolution PNRPsvc svchost.exe / pnrpsvc.dll Manual
using the Peer Name
Protocol
Resolution Protocol
(PNRP).
Enables multi-party
Peer
communication using

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

Networking p2psvc svchost.exe / p2psvc.dll Manual


Peer-to-Peer
Grouping
Grouping.
Provides identity
Peer services for the Peer
Networking Name Resolution
p2pimsvc svchost.exe / pnrpsvc.dll Manual
Identity Protocol (PNRP) and
Manager Peer-to-Peer
Grouping services.
Enables remote users
Performance and 64-bit processes
Counter DLL PerfHost perfhost.exe to query performance
Host counters provided by
32-bit DLLs.
Collects performance
data from local or
remote computers
based on
Performance
pla svchost.exe / pla.dll preconfigured Manual
Logs & Alerts
schedule parameters,
then writes the data to
a log or triggers an
alert.
Enables a computer
to recognize and
Automatic
Plug and Play PlugPlay svchost.exe / umpnpmgr.dll adapt to hardware
(Started)
changes with little or
no user input.
Manages the virtual
network bus,
PnP-X IP Bus svchost.exe / discovers network
IPBusEnum Manual
Enumerator IPBusEnum.dll connected devices
and gives them
presence in PnP.
PNRP Machine Publishes a machine
Name name using the Peer
PNRPAutoReg svchost.exe / pnrpauto.dll Manual
Publication Name Resolution
Service Protocol.
Portable
Enforces group policy
Device svchost.exe /
WPDBusEnum for removable mass- Manual
Enumerator wpdbusenum.dll
storage devices.
Service
Manages power policy
Automatic
Power Power svchost.exe / umpo.dll and power policy
(Started)
notification delivery.
Loads files to memory Automatic
Print Spooler Spooler SPOOLSVC.exe
for later printing (Started)
Provides support for
Problem viewing, sending and
Reports and deletion of system-
svchost.exe /
Solutions wercplsupport level problem reports Manual
wercplsupport.dll
Control Panel for the Problem
Support Reports and Solutions
control panel.

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

Provides support for


the Program
Compatibility
Program
Assistant (PCA). PCA
Compatibility
PcaSvc svchost.exe / pcasvc.dll monitors programs Manual
Assistant
installed and run by
Service
the user and detects
known compatibility
problems.
Provides protected
storage for sensitive
data, such as
LSASS.exe (Local Security
Protected passwords, to prevent
ProtectedStorage Authority Subsystem) Manual
Storage access by
/ psbase.dll
unauthorized
services, processes,
or users.
Quality Windows
Audio Video
Quality Experience (qWave)
Windows Audio is a networking
QWAVE svchost.exe / qwave.dll Manual
Video platform for Audio
Experience Video (AV) streaming
applications on IP
home networks.
Creates a connection
Remote to a remote network
Access Auto whenever a program
RasAuto svchost.exe / rasauto.dll Manual
Connection references a remote
Manager DNS or NetBIOS
name or address.
Manages dial-up and
Remote virtual private network
Access (VPN) connections
RasMan svchost.exe / rasmans.dll Manual
Connection from this computer to
Manager the Internet or other
remote networks.
Responsible for all
Remote Desktop
Services and Remote
Remote
Desktop related
Desktop SessionEnv svchost.exe / SessEnv.dll Manual
configuration and
Configuration
session maintenance
activities that require
SYSTEM context.
Remote Allows users to
Desktop TermService svchost.exe / termsrv.dll connect interactively Manual
Services to a remote computer.
Remote
Allows the redirection
Desktop
of
Services UmRdpService svchost.exe/ /umrdp.dll Manual
Printers/Drives/Ports
UserMode Port
for RDP connections
Redirector
The Service Control
Remote Manager for COM
Automatic
Procedure Call RpcSs svchost.exe / oleres.dll and DCOM servers.

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

(Started)
(RPC) Aactivation requests,
garbage collection.
In Windows 2003 and
earlier versions of
Windows, the Remote
Procedure Call (RPC)
Locator service
manages the RPC
Remote name service
Procedure Call RpcLocator Locator.exe database. In Windows Manual
(RPC) Locator Vista and later
versions of Windows,
this service does not
provide any
functionality and is
present for application
compatibility.
Enables remote users
Remote to modify registry
RemoteRegistry svchost.exe / regsvc.dll Manual
Registry settings on this
computer.
Optional feature
RIP Listener iprip isapnp.sys (Control Panel add
features)
Offers routing
services to
Routing and
businesses in local
Remote RemoteAccess svchost.exe / mprdim.dll Disabled
area and wide area
Access
network
environments.
Resolves RPC
RPC Endpoint interfaces identifiers Automatic
RpcEptMapper svchost.exe / RpcEpMap.dll
Mapper to transport (Started)
endpoints.
Manual
Enables starting If this service is
Secondary
seclogon svchost.exe / seclogon.dll processes under stopped, this type
Logon
alternate credentials. of logon access
will be unavailable.
Provides support for
Secure Socket the Secure Socket
Tunneling Tunneling Protocol
SstpSvc svchost.exe / sstpsvc.dll Manual
Protocol (SSTP) to connect to
Service remote computers
using VPN.
The startup of this
service signals other
Security LSASS.exe (Local Security services that the
Automatic
Accounts SamSs Authority Subsystem) Security Accounts
(Started)
Manager / samsrv.dll Manager (SAM) is
ready to accept
requests.
Monitors and reports
security health
settings: Firewall, Automatic

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

Security Center wscsvc svchost.exe / wscsvc.dll antivirus, antispyware, (Delayed Start,


Windows Update, Started)
UAC, and Internet
settings
Supports file, print,
and named-pipe
Automatic
Server LanmanServer svchost.exe / srvsvc.dll sharing over the
(Started)
network for this
computer.
Provides notifications
Shell Hardware Automatic
ShellHWDetection svchost.exe / shsvcs.dll for AutoPlay hardware
Detection (Started)
events.
Optional feature
Simple TCP/IP
simptcp (Control Panel add
Services
features)
Manages access to
Smart Card SCardSvr svchost.exe / SCardSvr.dll smart cards read by Manual
this computer.
Allows the system to
be configured to lock
Smart Card
SCPolicySvc svchost.exe / certprop.dll the user desktop Manual
Removal Policy
upon smart card
removal.
Optional feature
SNMP Service SNMP (Control Panel add
features)
Receives trap
messages generated
by local or remote
Simple Network
Management Protocol
SNMP Trap SNMPTRAP SNMPTRAP.exe (SNMP) agents and Manual
forwards the
messages to SNMP
management
programs running on
this computer.
Enables the
download, installation
Automatic
Software and enforcement of
sppsvc SPPSVC.exe (Delayed Start,
Protection digital licenses for
Started)
Windows and
Windows applications.
SPP Provides Software
Notification sppuinotify svchost.exe / sppuinotify.dll Licensing activation Manual
Service and notification
Discovers networked
devices and services
SSDP that use the SSDP
SSDPSRV svchost.exe / ssdpsrv.dll Manual (Started)
Discovery discovery protocol,
such as UPnP
devices.
Storage Enforces group policy
StorSvc svchost.exe / StorSvc.dll Manual
Service for storage devices

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

Maintains and
improves system Automatic
Superfetch SysMain svchost.exe / sysmain.dll
performance over (Started)
time.
Monitors system
System Event events and notifies
Automatic
Notification SENS svchost.exe / Sens.dll subscribers to COM+
(Started)
Service Event System of
these events.
Enables Tablet PC
Tablet PC
TabletInputService svchost.exe / TabSvc.dll pen and ink Manual
Input Service
functionality
Configure and
Task Automatic
Schedule svchost.exe / schedsvc.dll schedule automated
Scheduler (Started)
tasks.
Provides support for
Automatic
NetBIOS over TCP/IP
TCP/IP (Started)
(NetBT) and NetBIOS
NetBIOS lmhosts svchost.exe / lmhsvc.dll If not required can
name resolution for
Helper be set to manual
clients on the
or disabled.
network.
Provides Telephony
API (TAPI) support for
programs that control
telephony devices on
Telephony TapiSrv svchost.exe / tapisrv.dll the local computer Manual
and, through the LAN,
on servers that are
also running the
service.
Optional feature
Telnet TlntSvr (Control Panel add
features)
Provides user
svchost.exe / Automatic
Themes Themes experience theme
themeservice.dll (Started)
management.
Provides ordered
Thread execution for a group
Ordering THREADORDER svchost.exe / mmcss.dll of threads within a Manual
Server specific period of
time.
Enables access to the
Trusted Platform
Module (TPM), which
TPM Base provides hardware-
TBS svchost.exe / tbssvc.dll Manual
Services based cryptographic
services to system
components and
applications.
Allows UPnP devices
UPnP Device
upnphost svchost.exe / upnphost.dll to be hosted on this Manual
Host
computer.
Loading and
User Profile Automatic

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

ProfSvc svchost.exe / profsvc.dll unloading user


Service (Started)
profiles.
Provides
management services
Virtual Disk vds VDS.exe for disks, volumes, file Manual
systems, and storage
arrays.
Manages and
implements Volume
Volume
VSS VSSVC.exe Shadow Copies used Manual
Shadow Copy
for backup and other
purposes.
Web Optional feature
Management WMSVC (Control Panel add
Service features)
Enables Windows-
based programs to
WebClient WebClient svchost.exe / webclnt.dll create, access, and Manual
modify Internet-based
files.
Automatic
(Started)
Manages audio for If this service is
Windows Audio AudioSrv svchost.exe / audiosrv.dll Windows-based stopped, audio
programs. devices and
effects will not
function properly.
Automatic
(Started)
Manages audio
Windows Audio If this service is
devices for the
Endpoint AudioEndpointBuilder svchost.exe stopped, audio
Windows Audio
Builder devices and
service.
effects will not
function properly.
Windows Windows Backup and
SDRSVC svchost.exe / sdrsvc.dll Manual
Backup Restore capabilities.
The Windows
biometric service
gives client
applications the ability
Windows
to capture, compare,
Biometric WbioSrvc svchost.exe / wbiosrvc.dll Manual
manipulate, and store
Service
biometric data without
gaining direct access
to any biometric
hardware or samples.
Securely enables the
creation,
Windows
idsvc infocard.exe management, and Manual
CardSpace
disclosure of digital
identities.
Third-party Windows
Color System color
device model and
gamut map model

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

Windows Color svchost.exe / plug-in modules.


WcsPlugInService Manual
System WcsPlugInService.dll These plug-in
modules are vendor-
specific extensions to
the Windows Color
System baseline.
Microsoft's
Implementation of Wi-
Fi Protected Setup
Windows
(WPS) protocol. This
Connect Now –
wcncsvc svchost.exe / wcncsvc.dll is used to configure Manual
Config
Wireless LAN settings
Registrar
for an Access Point
(AP) or a Wi-Fi
Device.
Protection against
Automatic
Windows spyware and
WinDefend svchost.exe / MsMpRes.dll (Delayed Start,
Defender potentially unwanted
Started)
software.
Windows
Creates and manages
Driver
user-mode driver
Foundation –
wudfsvc svchost.exe / wudfsvc.dll processes. This Manual
User-mode
service cannot be
Driver
stopped.
Framework
Allows errors to be
reported when
programs stop
working or responding
Windows Error
and allows existing
Reporting WerSvc svchost.exe / wersvc.dll Manual
solutions to be
Service
delivered. Also allows
logs to be generated
for diagnostic and
repair services.
Manages persistent
subscriptions to
events from remote
sources that support
WS-Management
Windows Event
Wecsvc svchost.exe / wecsvc.dll protocol. This Manual
Collector
includes Windows
Vista event logs,
hardware and IPMI-
enabled event
sources.
Windows Event Manages events and Automatic
EventLog svchost.exe / wevtsvc.dll
Log event logs. (Started)
Windows svchost.exe / Automatic
MpsSvc Windows Firewall
Firewall FirewallAPI.dll (Started)
Automatic
Windows Font Cache commonly
FontCache svchost.exe / FntCache.dll (Delayed Start,
Cache Service used font data.
Started)
Windows Provides image
Image acquisition services
StiSvc svchost.exe / wiaservc.dll Manual

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

Acquisition for scanners and


(WIA) cameras
Adds, modifies, and
removes applications
Windows
msiserver MSIEXEC.exe provided as a Manual
Installer
Windows Installer
(*.msi) package.
Provides a common
interface and object
model to access
Windows
management Automatic
Management Winmgmt svchost.exe / wmisvc.dll
information about (Started)
Instrumentation
operating system,
devices, applications
and services.
Windows Windows Media
Optional feature
Media Center Center Service for TV
ehRecvr ehRecvr.exe (Control Panel add
Receiver and FM broadcast
features)
Service reception
Starts and stops
Windows
recording of TV Optional feature
Media Center
ehSched ehSched.exe programs within (Control Panel add
Scheduler
Windows Media features)
Service
Center
Shares Windows
Media Player libraries
Windows to other networked
Media Player players and media
Network WMPNetworkSvc wmpnetwk.exe devices using Manual (Started)
Sharing Universal Plug and
Service Play - provided for
backward
compatibility only.
Enables installation,
Windows modification, and
Modules TrustedInstaller TrustedInstaller.exe removal of Windows Manual
Installer updates and optional
components.
Windows Cache commonly
Presentation used font data for
Foundation FontCache3.0.0.0 PresentationFontCache.exe Windows Presentation Manual
Font Cache Foundation (WPF)
3.0.0.0 applications.
Windows
Optional feature
Process Performs Windows 7
WAS WatUX.exe (Control Panel add
Activation Validation.
features)
Service
Implements the WS-
Management protocol
for remote
management. WS-
Windows Management is a
Remote standard web
Management WinRM svchost.exe / wsmsvc.dll services protocol used Manual
(WS- for remote software

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

Management) and hardware


management.
The WinRM service
reserves the /wsman
URL prefix.
Provides content
indexing, property
Optional feature
Windows caching, and search
WSearch SearchIndexer.exe (Control Panel add
Search results for files, e-
features)
mail, and other
content.
Maintains date and
time synchronization
Windows Time W32Time svchost.exe / w32time.dll on all clients and Manual
servers in the
network.
Enables the detection,
download, and Automatic
Windows
wuauserv svchost.exe / wuaueng.dll installation of updates (Delayed Start,
Update
for Windows and Started)
other programs.
Implements the client
HTTP stack and
provides developers
WinHTTP Web
with a Win32 API and
Proxy Auto-
WinHttpAutoProxySvc svchost.exe / winhttp.dll COM Automation Manual
Discovery
component for
Service
sending HTTP
requests and
receiving responses.
IEEE 802.1X
Wired
dot3svc svchost.exe / dot3svc.dll authentication on Manual
AutoConfig
Ethernet interfaces.
Provides the logic
required to configure,
discover, connect to,
WLAN and disconnect from a
Wlansvc svchost.exe / wlansvc.dll Manual
AutoConfig wireless local area
network (WLAN) as
defined by IEEE
802.11 standards.
Provides performance
library information
WMI from Windows
WmiApSrv.exe /
Performance wmiApSrv Management Manual
wmiapsrv.exe
Adapter Instrumentation (WMI)
providers to clients on
the network.
Creates and
maintains client
network connections Automatic
Workstation LanmanWorkstation svchost.exe / wkssvc.dll
to remote servers (Started)
using the SMB
protocol.
World Wide Optional feature

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

Web Publishing W3SVC (Control Panel add


Service features)
Manages mobile
broadband (GSM &
CDMA) data
WWAN card/embedded
WwanSvc svchost.exe / wwansvc.dll Manual
AutoConfig module adapters and
connections by auto-
configuring the
networks.

The defaults above are based on Windows 7 Professional SP1, defaults for other versions, Home/Ultimate etc can be found
over on the Black Viper Service Tweaking guide.

Before changing any of the defaults - use the links above to find what exactly the service does.

It is inadvisable to disable a service without being aware of the consequences, always start by setting the service to manual,
reboot and test for any problems.

A service set to manual will be automatically restarted if another service is dependent on it.
A service set to disabled will not restart even if it's required to boot the machine!

If a service crashes the machine at startup, you can DISABLE it using the recovery console.

Stopping or disabling a service will generally save a small amount of memory and will reduce the number of software
interrupts (cpu message queue.) The main reason for tinkering with services is to harden the system against security
vulnerabilities. Disable everything that you don’t need or use - then any future problems with those services cannot affect the
machine.

The security group All Services (NT SERVICES\ALL SERVICES) includes all service processes that are configured on the
system. Membership of this group is controlled by the OS.

To document all the services currently installed:


SC QUERY state= all |findstr "DISPLAY_NAME STATE" >my_services.csv

Some services communicate and send data directly to Microsoft, this is not generally something to lose sleep over. Managing
the running of these services might be a consideration if confidentiality or anonymity is highly important to you.

Remove a service completely


To delete a service use the SC delete command:
SC delete NameofServiceTodelete

Built-in Service Accounts


In addition to other Default User & Group accounts there are 3 built-in accounts, designed for running background services.

Local Service Account ( NT AUTHORITY\LOCAL SERVICE) - has the same level of access to resources and objects as members of
the Users group. This limited access helps safeguard the system if individual services or processes are compromised.
Services that run as the Local Service account access network resources as a null session without credentials. (This account
is not supported for running SQL Server services.)

Network Service Account ( NT AUTHORITY\NETWORK SERVICE) - has more access to resources and objects than members of the
Users group. Services that run as the Network Service account access network resources by using the credentials of the
computer account.

Local System Account ( NT AUTHORITY\SYSTEM) - a very high-privileged built-in account. It has extensive privileges on the local
system and acts as the computer on the network.

Windows 2008 introduced a new feature: Managed Service Accounts these provide automatic password management and
simplified service principal name (SPN) management. Service accounts are created in PowerShell with New-

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Windows 7 Services - Windows CMD - SS64.com

ADServiceAccount

“The service we render to others is really the rent we pay for our room on this earth. It is obvious that man is himself a traveler; that the
purpose of this world is not 'to have and to hold' but 'to give and serve.' There can be no other meaning” - Sir Wilfred T. Grenfell

Related:

SC - Service Control
TASKLIST - List running tasks and services
PORTQRY - Enumerate SQL Server instances, Local ports, local services and the DLL modules loaded.
WinMSD - List running services
ServiceStatus.ps1 - List all services (Powershell)
Safe Mode - Press F8 during bootup to start with mimimal services running.
Recovery - The Recovery Console
WMIC SERVICE - WMI access to services
DComCnfg - Disable/configure Component Services
windows\system32\drivers\etc\services - Ports and Services
The Elder Geek - Services Guide
Q137890 - SRVANY - create a User-Defined Service
Q288129 - Grant users the right to manage services (Windows 2000 KB but still works in Windows 7)

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-services.html[8/24/2017 10:34:39 AM]


Parenthesis/Brackets - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Using parenthesis/brackets to group expressions


Parenthesis can be used to split commands across multiple lines. This can make code more readable. Variables will be
evaluated for the code block just as if the command was a single line.
(command)
(
command
command )

Example
IF EXIST C:\pagefile.sys (
ECHO pagefile found on C: drive)

If the command will fit on a single line, then the parenthesis can be omitted e.g.

IF EXIST data.xls Echo The file was found.

vs
IF EXIST data.xls (
Echo The file was found.
)

Using variables within parenthesis


The CMD shell will expand [read into memory] all the variables at the beginning of a code block and use those
values even if the variable’s value is changed within the code block. Turning on DelayedExpansion will force the
shell to read variables at the start of every line.

Code blocks can be used to expand variables in places where they would not otherwise be accepted such as the
"tokens" parameter of the FOR command:
@echo off
set tknz="tokens=1-2"
(
for /f %tknz% %%A in ('echo') do (
echo %%B
echo %%A
)
)

Things that break inside parenthesis


The CMD shell does not use any great intelligence when evaluating parenthesis, so for example the command
below will fail:
IF EXIST MyFile.txt (ECHO Some(more)Potatoes)

This version will work:


IF EXIST MyFile.txt (ECHO Some[more]Potatoes)

You could also escape the extra parenthesis like (ECHO Some^(more^)Potatoes)
Or use quotes; though they will appear in the output (ECHO "Some(more)Potatoes")

Although parenthesis are legal in NTFS pathnames, they are often misinterpreted.

Chaining to a second batch file (without using CALL) will normally exit the first batch file completely, but if you do
this from a code block within parentheses then execution will return to the first batch file and continue where it left
off.

https://ss64.com/nt/syntax-brackets.html[8/24/2017 10:34:50 AM]


Parenthesis/Brackets - Windows CMD - SS64.com

This action appears to be very similar to just using CALL, but in some cases; particularly using parenthesis within
the DO section of a FOR loop; the behaviour becomes buggy. A recommended coding style is to always explicitly
use CALL when running a second batch file.

The CMD shell will read the entire content of a code block in parenthesis into memory at once. That code will
always be executed unless you break out of the block by executing a goto :label or goto :eof

A GOTO command inside a bracketed code block will break the parenthesis context and may cause errors. For
example within a For-Do Loop, a GOTO command will exit the entire loop not just the current iteration.

The interpretation of comments/Labels within a code block is problematic, so put all comments outside the
parenthesis.

Testing Numeric values


Do not use parenthesis or quotes if you are comparing numeric values with an IF command.
For example
IF (2) GEQ (15) echo "bigger"
or
IF "2" GEQ "15" echo "bigger"
Will perform a character comparison and will echo "bigger"

however the commands:


IF 2 GEQ 15 echo "bigger"
or
IF (2 GEQ 15) echo "bigger"
Will perform a numeric comparison and return the correct result.

This behaviour is opposite to the SET /a command where quotes are required.

The maximum number of nested expressions in parenthesis is 256 (more will cause a buffer overrun).

“Yes, we are the richest major nation. But because so much of our national income is concentrated in relatively few hands, large numbers
of Americans are worse off economically than their counterparts in other advanced countries” - Paul Krugman

Related

DelayedExpansion - Force the shell to read variables at the start of every line.
IF - conditional command

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-brackets.html[8/24/2017 10:34:50 AM]


EnableDelayedExpansion - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

EnableDelayedExpansion
Delayed Expansion will cause variables within a batch file to be expanded at execution time rather than at parse time, this
option is turned on with the SETLOCAL EnableDelayedExpansion command.

Without this, by default, when a batch file is executed, the command processor (CMD.exe) will parse complete lines and
complete compound commands. Variables are replaced by their values just once, BEFORE the commands of the line are
executed.

Generally this only makes a difference when working within a loop, e.g. FOR... DO... If you want to perform operations on a
variable within the loop then you will need to enable Delayed Expansion.

When delayed expansion is in effect, variables can be immediately read using !variable_name! you can also still read and
use %variable_name% that will show the initial value (expanded at the beginning of the line).

Example:

@echo off
SETLOCAL
Set "_var=first"
Set "_var=second" & Echo %_var%

This will output: first


The value of %_var% was read into memory BEFORE the Set command which changes it.

Now repeating this with Delayed Expansion:

@echo off
SETLOCAL EnableDelayedExpansion
Set "_var=first"
Set "_var=second" & Echo %_var% !_var!

This will output: first second


T he value of the !_var! variable is evaluated as late as possible while the %_var% variable works just as before.

There are some advantages - we can swap the value of two variables in one line:
Set "var1=%var2%" & set "var2=%var1%"

Why this behaviour?


The SET command was first introduced with MS-DOS 2.0 in March 1983, at that time memory and CPU were very
limited and the expansion of variables once per line was enough.
Delayed Expansion was introduced some 16 years later in 1999 by which time millions of batch files had been
written using the earlier syntax. Retaining immediate expansion as the default preserved backwards compatibility
with existing batch files.

This is not how anyone would design a language if starting from scratch, indeed PowerShell behaves like this:
PS C:\> $demo = "First"
PS C:\> $demo = "Second" ; echo $demo
Second

Other effects - Punctuation


Because DelayedExpansion expands variables later, that means that any escape characters (^) and redirection
characters in your expressions will be evaluated before the variable expansion and this can be very useful:
@echo off

https://ss64.com/nt/delayedexpansion.html[8/24/2017 10:34:59 AM]


EnableDelayedExpansion - Windows CMD - SS64.com

Setlocal
Set _html=Hello^>World
Echo %_html%

In the above, the Echo command will create a text file called 'world' - not quite what we wanted! This is because
the variable is expanded at parse time, so the last line is executing Echo Hello > World and the > character is
interpreted as a redirection operator.

If we now try the same thing with EnableDelayedExpansion:

Setlocal EnableDelayedExpansion
Set _html=Hello^>World
Echo !_html!

With delayed expansion, the variable (including the > ) is only expanded at execution time so the > character is
never interpreted as a redirection operator.
This makes it possible to work with HTML and XML formatted strings in a variable.

When delayed expansion is enabled AND at least one exclamation mark in a line is present, then any carets will be
interpreted as an escape and so will disappear from the output:

Setlocal EnableDelayedExpansion
Echo "Hello^World"
Echo "Hello^World!"

The above will output:

"Hello^World"
"HelloWorld"

Even if you double the carets ^^, which normally would act as an escape, or add an escape just before the
exclamation mark, the presence of an exclamation mark anywhere in the line will still have this effect.

FOR Loops
Delayed variable expansion is often useful when working with FOR Loops, normally an entire FOR loop is
evaluated as a single command even if it spans multiple lines of a batch script.
This is the default behaviour of a FOR loop:
@echo off
setlocal
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [%_tst%] & set /a _tst+=1)
echo Total = %_tst%
C:\> demo_batch.cmd
[0]
[0]
[0]
[0]
[0]
Total = 5

Notice that when the FOR loop finishes we get the correct total, so the variable correctly increments, but during
each iteration of the loop the variable is stuck at it's initial value of 0

The same script with EnableDelayedExpansion, gives the same final result but also displays the intermediate
values:
@echo off
setlocal EnableDelayedExpansion
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [!_tst!] & set /a _tst+=1)
echo Total = %_tst%
C:\> demo_batch.cmd
[0]
[1]
[2]
[3]

https://ss64.com/nt/delayedexpansion.html[8/24/2017 10:34:59 AM]


EnableDelayedExpansion - Windows CMD - SS64.com

[4]
Total = 5

Notice that within the for loop we use !variable! instead of %variable%.

An alternative way to write this is by calling a subroutine, because this breaks out of the loop it does not need
Delayed Expansion
@echo off
setlocal
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (call :sub %%G)
echo Total = %_tst%
goto :oef
:sub
echo [%1] & set /a _tst+=1
goto :eof
C:\> demo_batch.cmd
[1]
[2]
[3]
[4]
[5]
Total = 5

More Examples
Set and then Echo the same variable within a FOR command:

Setlocal EnableDelayedExpansion
for /f %%G in ("abc") do ( set _demo=%%G & echo !_demo!)

Replace a variable_name using values from another variable:


@echo off
setlocal EnableDelayedExpansion
Set var1=Hello ABC how are you
Set var2=ABC
Set result=!var1:%var2%=Beautiful!
Echo [!result!]

Another method for replacing a variable named with the content of another is CALL SET

Some unexpected behaviours when using delayed variable expansion


If DelayedExpansion is used in conjunction with a FOR command looping through a set of files, if any file in the set
has an exclamation mark '!' in the filename, that will be interpreted like a !variable! .
Although this is not a common character used in filenames, it can cause scripts to fail. This happens because the
parameter expansion (%%P) happens just before the delayed expansion phase tries to interpret my!filen!ame.txt

When DelayedExpansion is used inside a code block (one or several commands grouped between parentheses)
whose output is Piped, the variable expansion will be skipped.
When you use a pipe, both parts of the pipe will be executed in a new cmd.exe instance and these instances are
started by default with disabled delayed expansion.

EnableDelayedExpansion is Disabled by default.


EnableDelayedExpansion can also be enabled by starting CMD with the /v switch.

EnableDelayedExpansion can also be set in the registry under HKLM or HKCU:

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"DelayedExpansion"= (REG_DWORD)
1=enabled 0=disabled (default)

“At times it is folly to hasten at other times, to delay. The wise do everything in its proper time” - Ovid

Related:

https://ss64.com/nt/delayedexpansion.html[8/24/2017 10:34:59 AM]


EnableDelayedExpansion - Windows CMD - SS64.com

Forum discussion - EnableDelayedExpansion (many thanks to Jeb and Aacini for clarifying quite a few points)
OldNewThing - Longer explanation of EnableDelayedExpansion
SETLOCAL - Start localisation of environment changes in a batch file.

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/delayedexpansion.html[8/24/2017 10:34:59 AM]


Quotes, Escape Characters, Delimiters - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Syntax : Escape Characters, Delimiters and Quotes


Using "Double Quotes"
If a single parameter contains spaces, you can still pass it as one item by surrounding in "quotes" - this works well
for long filenames.

If a parameter is used to supply a filename like this:


MyBatch.cmd "C:\Program Files\My Data File.txt"

This parameters will be:


%0 =MyBatch
%1 ="C:\Program Files\My Data File.txt"

To launch a batch script with spaces in the Program Path requiring "quotes"
CMD /k ""c:\batch files\test.cmd" "Parameter 1 with space" "Parameter2 with space""

In the FIND comand, the " quote can be escaped by doubling it to ""

Removing Quotes
Several methods for removing quotes are listed on the dequote page.

Working without Quotes


Without surrounding quotes, a long filename will be passed as %1 %2 %3...
MyBatch C:\Program Files\My Data File.txt

To refer to the pathname above use %* rather than %1 %2 %3 - the %* will cover all parameters - even if there
are more than %9

You can apply Extended Filename syntax to %* with the following workaround:
@ECHO OFF
SET _params=%*
:: pass params to a subroutine
CALL :sub "%_params%"
GOTO :eof
:sub
:: Now display just the filename (not path)
ECHO %~n1

Delimiters
Delimiters separate one parameter from the next - they split the command line up into words.

Parameters are most often separated by spaces, but any of the following are also valid delimiters:

Comma (,)
Semicolon (;)
Equals (=)
Space ( )
Tab (     )

Notice that although / and - are commonly used to separate command options, they are absent from the list
above. This is because batch file parameters are passed to CMD.exe which can accept it's own parameters

https://ss64.com/nt/syntax-esc.html[8/24/2017 10:35:08 AM]


Quotes, Escape Characters, Delimiters - Windows CMD - SS64.com

(which are invoked using / and - )

One exception to this standard list of delimiters is the FOR command where the default is just [space] and [tab]
and you can use the delims= option to specify something different.

When using the TAB character as a delimiter be aware that many text editors will insert a TAB as a series of
SPACEs.

When you use %* to refer to all parameters, the value returned will include the delimiters, under NT 4.0 this will
include the leading space, under Windows 2000 and above it won’t.

Escape Character
^ Escape character.

Adding the escape character before a command symbol allows it to be treated as ordinary text.
When piping or redirecting any of these charcters you should prefix with the escape character: & \ < > ^ |
e.g. ^\ ^& ^| ^> ^< ^^

Escaping CR/LF line endings.


The ^ escape character can be used to make long commands more readable by splitting them into multiple lines
and escaping the Carriage Return + Line Feed (CR/LF) at the end of a line:
ROBOCOPY \\FileServ1\e$\users ^
\\FileServ2\e$\BackupUsers ^
/COPYALL /B /SEC /MIR ^
/R:0 /W:0 /LOG:MyLogfile.txt /NFL /NDL

One thing to be careful of with this technique is that a stray space at the end of a line (after the ^) will break the
command, this can be hard to spot unless you have a text editor that displays spaces and tab characters.

Some commands (e.g. REG and FINDSTR) use the standard escape character of \ (as used by C, Python, SQL,
bash and many other languages.)
The \ escape can cause problems with quoted directory paths that contain a trailing backslash because the
closing quote " at the end of the line will be escaped \".

To save a directory path with a trailing backslash ( \) requires adding a second backslash to 'escape the escape'
so for example instead of "C:\My Docs\" use "C:\My Docs\\"

To be sure that a path includes a trailing backslash, you can test for it:
Set _prog=C:\Program Files\SS64 App
IF %_prog:~-1% NEQ \ (Set _prog=%_prog%\)
Echo "%_prog%"

Escaping the pipeline


When a pipe is used, the expressions are parsed twice. First when the expression before the pipe is executed and
a second time when the expression after the pipe is executed. So to escape any characters in the second
expression double escaping is needed:

The line below will echo a single `&` character:


break| echo ^^^&

Escaping Percents
The % character has a special meaning for command line parameters and FOR parameters.
To treat a percent as a regular character, double it:

%%

https://ss64.com/nt/syntax-esc.html[8/24/2017 10:35:08 AM]


Quotes, Escape Characters, Delimiters - Windows CMD - SS64.com

Many characters such as \ = ( ) do not need to be escaped when they are used within a "quoted string"
typically these are charcters you might find in a filename/path. The percent character is one exception to this rule,
even though under NTFS % is a valid filename character.

Escaping Exclamation marks


When the shell is running in EnableDelayedExpansion mode the ! character is used to denote a variable and so
must be escaped (twice) if you wish to treat it as a regular character:

^^!

Escape the Escape character


The escape character can be used to escape itself ^^ (meaning don’t treat the first ^ as an escape character), so
you are escaping the escape character:
The characters in bold get escaped:
^& => &
^^^& => ^&
^^^^^& => ^^&

Special Cases
A small number of commands follow slightly different rules, FINDSTR, REG and RUNAS all use \ as an escape
character instead of ^

“All the best stories in the world are but one story in reality - the story of escape. It is the only thing which interests us all and at all
times, how to escape” ~ A. C. Benson

Related:

SETLOCAL EnableDelayedExpansion - More examples, particularly for HTML.


Long Filenames and NTFS - Valid characters in filenames
FINDSTR Escapes and Length limits
How does the Windows Command Interpreter (CMD.EXE) parse scripts? - StackOverflow
cmd Syntax
Powershell Escape Character
In bash use \ to escape a line ending.

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-esc.html[8/24/2017 10:35:08 AM]


Set - Environment Variable - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

SET
Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current
CMD session.
Syntax
SET variable
SET variable=string
SET /A "variable=expression"
SET "variable="
SET /P variable=[promptString]
SET "
Key
variable : A new or existing environment variable name e.g. _num
string : A text string to assign to the variable.
expression : Arithmetic expression

Arithmetic expressions (SET /a)


The expression to be evaluated can include the following operators:
+ Add set /a "_num=_num+5"
+= Add variable set /a "_num+=5"
- Subtract (or unary)set /a "_num=_num-5"
-= Subtract variable set /a "_num-=5"
* Multiply set /a "_num=_num*5"
*= Multiply variable set /a "_num*=5"
/ Divide set /a "_num=_num/5"
/= Divide variable set /a "_num/=5"
% Modulus set /a "_num=5%%2"
%%= Modulus set /a "_num%%=5"
! Logical negation 0 (FALSE) 1 (TRUE) and any non-zero value (TRUE) 0 (FALSE)
~ One's complement (bitwise negation)
& AND set /a "_num=5&3" 0101 AND 0011 = 0001 (decimal 1)
&= AND variable set /a "_num&=3"
| OR set /a "_num=5|3" 0101 OR 0011 = 0111 (decimal 7)
|= OR variable set /a "_num|=3"
^ XOR set /a "_num=5^3" 0101 XOR 0011 = 0110 (decimal 6)
^= XOR variable set /a "_num=^3"
<< Left Shift. (sign bit 0)
>> Right Shift. (Fills in the sign bit such that a negative number always remains negative.)
Neither ShiftRight nor ShiftLeft will detect overflow.
<<= Left Shift variable set /a "_num<<=2"
>>= Right Shift variable set /a "_num>>=2"
( ) Parenthesis group expressions set /a "_num=(2+3)*5"
, Commas separate expressions set /a "_num=2,_result=_num*5"
If a variable name is specified as part of the expression, but is not defined in the
current environment, then SET /a will use a value of 0.
See SET /a examples below and this forum thread for more.
also see SetX, VarSearch and VarSubstring for more on variable manipulation.

Variable names are not case sensitive but the contents can be.

It is good practice to avoid using any delimiter characters (spaces, commas etc) in the variable name, for example IF
DEFINED _variable will often fail if the variable name contains a delimiter character.

It is a common practice to prefix variable names with either an undescore or a dollar sign _variable or $variable , these
prefixes are not required but help to prevent any confusion with the standard built-in Windows Environment variables or any
other other command strings.

Any extra spaces around either the variable name or the string, will not be ignored, SET is not forgiving of extra spaces like
many other scripting languages.

Display a variable:
In most contexts, surround the variable name with %'s and the variable's value will be used
e.g. To display the value of the _department variable with the ECHO command:
ECHO %_department%

If the variable name is not found in the current environment then SET will set %ERRORLEVEL% to 1 .

https://ss64.com/nt/set.html[8/24/2017 10:35:17 AM]


Set - Environment Variable - Windows CMD - SS64.com

This can be detected using IF ERRORLEVEL ...

Including extra characters can be useful to show any white space:


ECHO [%_department% ]
ECHO "%_department% "

Type SET without parameters to display all the current environment variables.

Type SET with a variable name to display that variable


SET _department

The SET command invoked with a string (and no equal sign) will display a wildcard list of all matching variables

Display variables that begin with 'P':


SET p
Display variables that begin with an underscore
SET _

Set a variable:
Example of storing a text string:

C:\> SET _dept=Sales and Marketing


C:\> set _
_dept=Sales and Marketing

Set a variable that contains a redirection character, note the position of the quotes which are not saved:
SET "_dept=Sales & Marketing"

One variable can be based on another, but this is not dynamic


E.g.
C:\> set xx=fish
C:\> set msg=%xx% chips
C:\> set msg
msg=fish chips

C:\> set xx=sausage


C:\> set msg
msg=fish chips

C:\> set msg=%xx% chips


C:\> set msg
msg=sausage chips

Avoid starting variable names with a number, this will avoid the variable being mis-interpreted as a parameter
%123_myvar% < > %1 23_myvar

To display undocumented system variables:


SET "

Values with Spaces - using Double Quotes


There is no need to add quotation marks when assigning a value that includes spaces
SET _variable=one two three

For special characters like & you can surround the entire expression with quotation marks.
The variable contents will not include the surrounding quotes:
SET "_variable=one & two"

If you place quotation marks around the value, then those quotes will be stored:

https://ss64.com/nt/set.html[8/24/2017 10:35:17 AM]


Set - Environment Variable - Windows CMD - SS64.com

SET _variable="one & two"

Variable names with spaces


A variable can contain spaces and also the variable name itself can contain spaces, therefore the following
assignment:
SET _var =MyText
will create a variable called "_var " - note the trailing space

Prompt for user input


The /P switch allows you to set a variable equal to a line of input entered by the user.
The Prompt string is displayed before the user input is read.
@echo off
Set /P _dept=Please enter Department || Set _dept=NothingChosen
If "%_dept%"=="NothingChosen" goto :sub_error
If /i "%_dept%"=="finance" goto sub_finance
If /i "%_dept%"=="hr" goto sub_hr
goto:eof
:sub_finance
echo You chose the finance dept
goto:eof
:sub_hr
echo You chose the hr dept
:sub_error
echo Nothing was chosen

The Prompt string can be empty. If the user does not enter anything (just presses return) then the variable will be
unchanged and an errorlevel will be set.

To place the first line of a file into a variable:


Set /P _MyVar=<MyFilename.txt

The CHOICE command is an alternative to SET /P (but accepts only one character/keypress.)

Delete a variable
Type SET with just the variable name and an equals sign:

SET _department=

Better still, to be sure there is no trailing space after the = place the expression in parentheses or quotes:
(SET _department=)
  or
SET "_department="

Arithmetic expressions (SET /a)


Placing expressions in "quotes" is optional for simple arithmetic but required for any expression using logical
operators.

Any SET /A calculation that returns a fractional result will be rounded down to the nearest whole integer.

Examples:
SET /A "_result=2+4"
(=6)
SET /A "_result=5"
(=5)
SET /A "_result+=5"
(=10)
SET /A "_result=2<<3"
(=16) { 2 Lsh 3 = binary 10 Lsh 3 = binary 10000 = decimal 16 }

https://ss64.com/nt/set.html[8/24/2017 10:35:17 AM]


Set - Environment Variable - Windows CMD - SS64.com

SET /A "_result=5%%2"
(=1) { 5/2 = 2 + 2 remainder 1 = 1 }
SET /A "_var1=_var2=_var3=10"
(sets 3 variables to the same value - undocumented syntax.)

In a batch script, the Modulus operator ( %) must be doubled up to ( %%).

SET /A will treat any character string in the expression as an environment variable name. This allows you to do
arithmetic with environment variables without having to type any % signs to get the values. SET /A _result=5 +
_MyVar

Multiple calculations can be performed in one line, by separating each calculation with commas, for example:
_year=1999
Set /a _century=_year/100, _next=_century+1

The numbers must all be within the range of 32 bit signed integer numbers (-2,147,483,648 through
2,147,483,647) to handle larger numbers use PowerShell or VBScript.

Leading Zero will specify Octal


Numeric values are decimal numbers, unless prefixed by
0x for hexadecimal numbers,
0 for octal numbers.

So 0x10 = 020 = 16 decimal

The octal notation can be confusing - all numeric values that start with zeros are treated as octal but 08 and 09 are
not valid octal digits.
For example SET /a _month=07 will return the value 7, but SET /a _month=09 will return an error.

Permanent changes
Changes made using the SET command are NOT permanent, they apply to the current CMD prompt only and
remain only until the CMD window is closed.
To permanently change a variable at the command line use SetX
or with the GUI - Control Panel | System | Environment | System/User Variables

Changing a variable permanently with SetX will not affect any CMD prompt that is already open.
Only new CMD prompts will get the new setting.

You can of course use SetX in conjunction with SET to change both at the same time:
Set _Library=T:\Library\
SetX _Library T:\Library\ /m

Change the environment for other sessions


Neither SET nor SetX will affect other CMD sessions that are already running on the machine . This as a good
thing, particularly on multi-user machines, your scripts won't have to contend with a dynamically changing
environment while they are running.

It is possible to add permanent environment variables to the registry ( HKCU\Environment), but this is an
undocumented (and likely unsupported) technique and still it will not take effect until the users next login.

System environment variables can be found in the registry here:


HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

CALL SET
The CALL SET syntax allows a variable substring to be evaluated, the CALL page has more detail on this technique,
Setlocal EnableDelayedExpansion

https://ss64.com/nt/set.html[8/24/2017 10:35:17 AM]


Set - Environment Variable - Windows CMD - SS64.com

in most cases a better approach is to use

Autoexec.bat
Any SET statement in c:\autoexec.bat will be parsed at boot time
Variables set in this way are not available to 32 bit gui programs - they won't appear in the control panel.
They will appear at the CMD prompt.

If autoexec.bat CALLS any secondary batch files, the additional batch files will NOT be parsed at boot.
This behaviour can be useful on a dual boot PC.

Errorlevels
When CMD Command Extensions are enabled (the default)

If the variable was successfully changed %ERRORLEVEL% = 0


No variable found/invalid name = 1
SET /A Unbalanced parentheses = 1073750988
SET /A Missing operand = 1073750989
SET /A Syntax error = 1073750990
SET /A Invalid number = 1073750991
SET /A Number larger than 32-bits = 1073750992
SET /A Division by zero = 1073750993

SET is an internal command. If Command Extensions are disabled all SET commands are disabled other than simple
assignments like: _variable=MyText

The CMD shell will fail to read an environment variable if it contains more than 8,191 characters.

# I got my mind set on you


# I got my mind set on you... - Rudy Clark (James Ray/George Harrison)

Related:

Syntax - VarSubstring Extract part of a variable (substring)


Syntax - VarSearch Search & replace part of a variable.
Syntax - Environment Variables - List of default variables
CALL - Evaluate environment variables
SETX - Set an environment variable permanently.
SETLOCAL - Begin localisation of environment variable changes
ENDLOCAL - End localisation of environment changes, use to return values
EXIT - Set a specific ERRORLEVEL
Parameters - get a full or partial pathname from a command line variable.
PATH - Change the %PATH% environment variable.
PATHMAN - Resource Kit utility for modification of both the system and user paths. Pathman can resolve many problems and
can improve performance by removing duplicate paths. For details see Pathman.wri
REG - Read or Set Registry values
REGEDIT - Import or export registry settings
WMIC ENVIRONMENT - Set environment vars through WMI
StackOverflow - Storing a Newline in a variable
Powershell: Set-Variable - Set a variable and a value (set/sv)
Powershell: Read-Host - Prompt for user input
Equivalent bash command (Linux): env - Display, set, or remove environment variables

https://ss64.com/nt/set.html[8/24/2017 10:35:17 AM]


Set - Environment Variable - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/set.html[8/24/2017 10:35:17 AM]


variable substring - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Variables: extract part of a variable (substring)


It is possible to retrieve specific characters from a string variable.
Syntax
%variable:~num_chars_to_skip%
%variable:~num_chars_to_skip,num_chars_to_keep%
This can include negative numbers:
%variable:~num_chars_to_skip, -num_chars_to_keep%
%variable:~-num_chars_to_skip,num_chars_to_keep%
%variable:~-num_chars_to_skip,-num_chars_to_keep%

A negative number will count backwards from the end of the string.

Examples

The variable _test is used for all the following examples:


SET _test=123456789abcdef0
::Extract only the first 5 characters
SET _result=%_test:~0,5%
ECHO %_result% =12345
::Skip 7 characters and then extract the next 5
SET _result=%_test:~7,5%
ECHO %_result% =89abc
::Skip 7 characters and then extract everything else
SET _result=%_test:~7%
ECHO %_result% =89abcdef0
::Extract only the last 7 characters
SET _result=%_test:~-7%
ECHO %_result% =abcdef0
::Extract everything BUT the last 7 characters
SET _result=%_test:~0,-7%
ECHO %_result% =123456789
::Extract between 7 from the front and 5 from the end
SET _result=%_test:~7,-5%
ECHO %_result% =89ab
::Go back 7 from the end then extract 5 towards the end
SET _result=%_test:~-7,5%
ECHO %_result% =abcde
::Extract between 7 from the end and 5 from the end
SET _result=%_test:~-7,-5%
ECHO %_result% =ab

This variable substring syntax only works for CMD environment variables, like %MYVAR%, it will not work with FOR parameter
variables, like %%G , however a simple workaround is to set a variable first: Set %MYVAR%=%%G and then find the substring of the
new variable.

To discover if a given variable contains a given string: use the syntax above to remove the _SearchString and compare the
result with the original variable before removal. If both strings are the same, then_SearchString was not found:
IF /i "%_variable:_SearchString=%"=="%_variable%" (Echo String not found.) ELSE (Echo String found.)

To match an exact word, pad the search string with spaces: " John " instead of "John" will avoid a match with "Johnstone"

Advanced Usage of :~

https://ss64.com/nt/syntax-substring.html[8/24/2017 10:35:26 AM]


variable substring - Windows CMD - SS64.com

You can use the :~ syntax and provide each of the parameters from other variables, for example if you have

%_donor%=2539850
%_digit%=4

To extract digit # 4 from _donor you might try


SET _substring=%_donor:~%_digit%,1%

Unfortunately this will not work because the :~ syntax expects a value not a variable. To get around this use the CALL
command like this:
SET _startchar=2
SET _length=1
SET _donor=884777
CALL SET _substring=%%_donor:~%_startchar%,%_length%%%
ECHO (%_substring%)

:: Credits:
:: Clay Calvert - alt.msdos.batch.nt
:: Ritchie Lawrence - alt.msdos.batch.nt

#Substitute Me for him, Substitute My Coke for gin, Substitute You for my mum, At least I'll get my washing done# ~ The Who
(Substitute)

Related:

VarSearch - Search & replace part of a variable.


strlen.cmd - Get string length.

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-substring.html[8/24/2017 10:35:26 AM]


CMD Variable edit replace - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Variable Edit/Replace
Use the syntax below to edit and replace the characters assigned to a string variable.
Syntax
%variable:StrToFind=NewStr%
%~[param_ext]$variable:Param
Key
StrToFind : The characters we are looking for
NewStr : The chars to replace with (if any)
variable : The environment variable
param_ext : Any filename Parameter Extension
Param : A command line parameter (e.g. 1)

This Edit/Replace syntax can be used anywhere that you would use the %variable% such as ECHOing the variable to screen
or setting one variable = another

param_ext cannot be %* which typically represents a whole set of parameters, but this is easily worked around by setting a
variable =%*

"StrToFind" can begin with an asterisk, in which case it will replace all characters to the left of "StrToFind".
By leaving NewStr blank, you can delete characters.

Using both an asterisk and NewStr=null effectively provides a left$() or right$() function.

Examples:
The variable _test containing 12345abcabc is used for all the following examples:
::Replace '12345' with 'Hello '
SET _test=12345abcabc
SET _result=%_test:12345=Hello %
ECHO %_result% =Hello abcabc
::Replace the character string 'ab' with 'xy'
SET _test=12345abcabc
SET _result=%_test:ab=xy%
ECHO %_result% =12345xycxyc
::Delete the character string 'ab'
SET _test=12345abcabc
SET _result=%_test:ab=%
ECHO %_result% =12345cc
::Delete the character string 'ab' and everything before it
SET _test=12345abcabc
SET _result=%_test:*ab=%
ECHO %_result% =cabc
::Replace the character string 'ab' and everything before it with 'XY'
SET _test=12345abcabc
SET _result=%_test:*ab=XY%
ECHO %_result% =XYcabc

:: To remove characters from the right hand side of a string is


:: a two step process and requires the use of a CALL statement
:: e.g.
SET _test=The quick brown fox jumps over the lazy dog
:: To delete everything after the string 'brown'
:: first delete 'brown' and everything before it
SET _endbit=%_test:*brown=%
Echo We dont want: [%_endbit%]
::Now remove this from the original string
CALL SET _result=%%_test:%_endbit%=%%
echo %_result%

All the examples on this page assume the default Expansion of variables, if you are using DelayedExpansion then you may
want to change the variable references to !_variable! instead of %_variable%

https://ss64.com/nt/syntax-replace.html[8/24/2017 10:35:35 AM]


CMD Variable edit replace - Windows CMD - SS64.com

Remove spaces from a text string


To delete space characters use the same syntax as above:

SET _no_spaces=%_some_var: =%

Boolean Test "does string exist ?"


To test for the existence of a value we can use a temporary variable, delete the string we are looking for (if it
exists) and then compare the two variables with EQU

Example: test for the existence of the string "London" in a variable containing text (that could be in any order)
"Aberdeen, London, Edinburgh "

Set _cities="Aberdeen, London, Edinburgh"


:: Remove London if found
Set _dummy=%_cities:London=%
IF NOT %_dummy% == %_cities% (ECHO London was found.) ELSE (ECHO London was not found.)

Finding items within the PATH environment variable


The %PATH% variable contains a list of folder names.

If you have a parameter containing a valid 'folder' this can be compared with the PATH variable.

This is done using the syntax: $variable:parameter

Example

%PATH% = C:\Windows\system32;C:\Windows;C:\utils\jdk\bin
batch parameter %1 = C:\utils\jdk\bin

To get the drive and Path


ECHO %~dp$PATH:1
This will either return "C:\utils\jdk\bin" or a NULL if the item is not found in the %PATH%

If the batch parameter was supplied as %2 then this would be: ECHO %~dp$PATH:2

This syntax can be applied where:

The parameter is any valid parameter (%1 %2 %G) but it must contain a Full Path (not a pathname)
The variable is %PATH% or any other variable that contains one or more Paths or pathnames separated by
semicolons ;
If nothing is found by the search, then this will return an empty string (NULL)

Be wary of using the syntax on this page to modify the PATH - the User path can be edited, but the System path
remains read-only for most users.

“A phony smile will never replace honest integrity” ~ Bob Martinelli

Related:

SUBSTRING of a variable :~
PARAMETERS - Filename Parameter Extensions.
strlen.cmd - Get string length.
PATHMAN - This Resource Kit utility allows quick modification of both the system and user paths. Pathman can resolve many
problems such as duplicate characters, and can improve performance by removing duplicate paths. For details see
Pathman.wri in the resource kit.

https://ss64.com/nt/syntax-replace.html[8/24/2017 10:35:35 AM]


CMD Variable edit replace - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-replace.html[8/24/2017 10:35:35 AM]


Random Numbers - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Random Numbers
The Windows CMD shell contains a dynamic variable called %RANDOM% that can be used to generate random numbers.

%RANDOM% generates a random integer from 0 to 32,767 (inclusive)

 0 ≤ %RANDOM% ≤ 32767

The range of numbers can be made smaller than 32767 with a little arithmetic,
for example to generate a range between 1 and 500:
@ECHO OFF
SET /a _rand=(%RANDOM%*500/32768)+1
ECHO Random number %_rand%

(The Set /a will always round down)

If you try, it may look as though a larger range than 32767 will work, but doing this will produce gaps, for example changing
500 in the above to 65536 will result in a sequence of "random" numbers which only consists of odd numbers.

The distribution of numbers returned will be a determined by both the range and the quantity of numbers drawn.

For example if you are drawing random integer numbers where each number is between 0 and 100 then on average:

If you draw 10 numbers then you should expect around 6% to be duplicates.


If you draw 100 numbers then just over 63% will be duplicates i.e. matching one or more of the other 99 numbers.
If you draw 1,000 numbers then almost all will be duplicates as there are only 100 possible values.

Random vs Pseudorandom numbers


A pseudorandom sequence is not truly random but is determined by a small set of initial values (state), the initial
seed is often based on the clock time. In the case of the CMD %RANDOM% the seed is based on the clock time when
the CMD session started. This can be problematic when running a batch file, if the script always takes about the
same time to run before calling %RANDOM% then the number returned will always lie within a small predictable range.

As an example create a file numbers.cmd:


@Echo off
Echo %RANDOM%

Then call the above with


CMD /c numbers.cmd
CMD /c numbers.cmd
CMD /c numbers.cmd

Johannes Baagøe has published a comparison of better random numbers for javascript. The fastest of these is Alea(), which
you can find a copy of below. This has a number of advantages, you can create much larger numbers, it will create a lot of
numbers quickly and if you call it passing a seed number then the results become repeatable - you can create exactly the
same sequence of random numbers again at a later date.
// random.js
// call this from the command line with:
// C:\> cscript /nologo random.js
// or from PowerShell
// PS C:\> $myrandom = & cscript /nologo "c:\batch\random.js"
// will create an array of 10 random numbers which you can then treat like any array variable:
// PS C:\> $myrandom[4]
// Calling without a seed, the current time will be used as a seed
var srandom=Alea();
// Calling with a seed will return the same value for the same seed

https://ss64.com/nt/syntax-random.html[8/24/2017 10:35:45 AM]


Random Numbers - Windows CMD - SS64.com

//var seed=1234
//var srandom=Alea(seed);
var i=0
// Return 10 random numbers
while ( i < 10 ) {
// Return a number between 1 and 500 million
WScript.echo(Math.floor((srandom()*500000000)+1) );
i++;
}
function Mash() {
var n = 0xefc8249d;
var mash = function(data) {
data = data.toString();
for (var i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
var h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
mash.version = 'Mash 0.9';
return mash;
}
function Alea() {
return (function(args) {
// Johannes Baagoe <[email protected]>, 2010
var s0 = 0;
var s1 = 0;
var s2 = 0;
var c = 1;
if (args.length == 0) {
args = [+new Date];
}
var mash = Mash();
s0 = mash(' ');
s1 = mash(' ');
s2 = mash(' ');
for (var i = 0; i < args.length; i++) {
s0 -= mash(args[i]);
if (s0 < 0) {
s0 += 1;
}
s1 -= mash(args[i]);
if (s1 < 0) {
s1 += 1;
}
s2 -= mash(args[i]);
if (s2 < 0) {
s2 += 1;
}
}
mash = null;
var random = function() {
var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32
s0 = s1;
s1 = s2;
return s2 = t - (c = t | 0);
};
random.uint32 = function() {
return random() * 0x100000000; // 2^32
};
random.fract53 = function() {
return random() +
(random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
};
random.version = 'Alea 0.9';
random.args = args;
return random;
} (Array.prototype.slice.call(arguments)));
};
/* licensed according to the MIT - Expat license:
Copyright (C) 2010 by Johannes Baagoe <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights

https://ss64.com/nt/syntax-random.html[8/24/2017 10:35:45 AM]


Random Numbers - Windows CMD - SS64.com

to use, copy, modify, merge, publish, distribute, sublicense, and/or sell


copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */

“Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin” ~ John von Neumann

Related:

PowerShell Equivalent: Get-Random


VBScript: Rnd - Return a pseudorandom number.
Random.org - Generate true random numbers online.

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-random.html[8/24/2017 10:35:45 AM]


Wildcards - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Wildcards
The * wildcard will match any sequence of characters
(0 or more, including NULL characters)
The ? wildcard will match a single character
(or a NULL at the end of a filename)

A few quirks affect the operation of wildcards which are best illustrated by example:

To match the filename BAR.TXT any of the following patterns will match
?AR.TXT
BAR.*
??R.TXT
B?R.???
BA?.TXT
BA??.TXT

However the following will fail to match with BAR.TXT


??AR.TXT
?BAR.TXT
B??AR.TXT

Wildcard matching rules


* Generally matches any 0 or more characters, with one exception (see next rule). The non-greedy wildcard is
free to match as many or as few characters as are necessary for the remainder of the mask to match.

*.At end of mask matches any 0 or more characters except for {dot}. In actuality, the rule applies with any
number of {dot} and {space} characters between the * and terminal {dot}. The regular expression for this term is
"[*][. ]*[.]$"

? Match 0 or one character, except for {dot}.


The only time it matches 0 characters is when it matches the end of the name, or the position before a {dot}.
The question mark can also be used more than once to match more than one character.

Wildcards match both the Short and Long filename


The command DIR /X will reveal short filenames if they exist, where many similar names exist in the same folder the short file
name (SFN) will not always be an obvious contraction of the long name. e.g.
DIR /X
2012-05-12 01:12 96 DIABLO~1 diablo1640
2012-05-12 01:12 96 DIABLO~2 diablo1641
2012-05-12 01:12 96 DIABLO~3 diablo1642
2012-05-12 01:12 96 DIABLO~4 diablo1643
2012-05-12 01:12 96 DIE359~1 diablo1644
2012-05-12 01:12 96 DIC49C~1 diablo1648
2012-05-12 01:12 96 DIF2E9~1 diablo1740
2012-05-12 01:12 96 DIE2EF~1 diablo1649

As you can see, the first four short filenames follow the usual numeric tails (~1, ~2, ~3, ~4).
Then, from fifth and more files with similar beginning, the short names have four hex digits in the middle. This is actually a hex
checksum of the long filename. (If you need a true file checksum look at CertUtil -hashfile )

Wildcards are supported by the following commands:


ATTRIB, CACLS, CIPER, COMPACT, COPY, DEL, DIR, EXPAND, EXTRACT, FIND, FINDSTR, FOR, FORFILES, FTP,
ICACLS, IF EXIST, MORE, MOVE, MV, NET (*=Any Drive), PERMS, PRINT, QGREP, REN, REPLACE, ROBOCOPY,
ROUTE, TAKEOWN, TYPE, WHERE, XCACLS, XCOPY

The commands COPY and REN accept two sets of wildcards, there are some subtle differences between how these are

https://ss64.com/nt/syntax-wildcards.html[8/24/2017 10:35:54 AM]


Wildcards - Windows CMD - SS64.com

treated, see the REN page for details.

Undocumented Wildcards
The two undocumented wildcards, < and > can be used with commands like DIR and COPY, or to supply a command name
but only if quoted: DIR /b "<demo<"

< Matches any 0 or more characters in either the base name or the extension, but never both.
Unlike the * wildcard, a single < cannot match characters in both the base name and the extension.
The {dot} is considered to be part of the base name, not the extension. There is one exception - If the name
consists solely of an extension, without a base name, then the {dot} is considered to be part of the extension. This
non-greedy wild card is free to match as many or as few characters as are necessary for the remainder of the
mask to match.

> Is identical to ?. The only difference is that it can be placed after a {dot} to prevent the {dot} from matching the
end of the name.

Examples at Dostips

The < and > wildcards work with the following commands: CACLS, CIPHER, COPY, DEL, DIR, FINDSTR, IF EXIST, MOVE,
TYPE

Numeric Comparisons
There are several contexts where CMD.EXE will parse a string as a numeric expression:

IF comparisons - EQU, NEQ, LSS, LEQ, GEQ, GTR


SET /A
variable substring expansion - %var:~n,m%
FOR /F "TOKENS=n"
FOR /F "SKIP=n"
FOR /L %%A in (n1 n2 n3)

For many purposes a 4 byte signed integer value ranging from -2,147,483,648 to 2,147,483,647 will suffice, but in the above
contexts it is also possible to express the numbers in hexadecimal or octal notation.

e.g. Octal: 00, 07 Hex: 0x00, 0xFF

There are a number of subtle differences (Negative numbers, command, version of Windows) which affect how these
numbers are parsed and these are described in the DosTips forum thread Rules for how CMD.EXE parses numbers.

“We usually see only the things we are looking for, so much that we sometimes see them where they are not” ~ Eric Hoffer

Related:

FINDSTR
REN - Rename files
Long and short filename issues

https://ss64.com/nt/syntax-wildcards.html[8/24/2017 10:35:54 AM]


Wildcards - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-wildcards.html[8/24/2017 10:35:54 AM]


CMD syntax - How to Run a script - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Run a CMD batch file


To run a batch script from the CMD shell, save the file as plain ASCII text with the file extension .CMD, then from the
command line, enter the name of the script and press return.

C:\Batch> Demo.cmd

To run a batch file from within another batch file, use the CALL command, otherwise the first script will exit without performing
any further commands.

It is also possible to run batch scripts with the old (Windows 95 style) .BAT extension, but be aware that these will set
ERRORLEVEL differently.

Run a Powershell script


To run a PowerShell script from the CMD shell:
C:\> powershell -file "c:\batch\demo.ps1"

Run a VBScript file


To run a VBScript from the CMD shell:
C:\> cscript c:\batch\demo.vbs

“The method of the enterprising is to plan with audacity and execute with vigor” ~ John Christian Bovee

Related

Run a script from PowerShell


Run a script from VBScript

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-run.html[8/24/2017 10:36:03 AM]


Run with elevated permissions UAC - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Run with elevated permissions


The CMD shell, START and RUNAS commands have no built-in options to elevate or run commands 'As Admin'

It is possible to right click CMD.exe (or it's Start menu shortcut) and run it As Admin.
Shortcuts can be edited to always run as Admin - Properties | Shortcut | Advanced then tick "Run as
administrator".

To elevate from the command line will require running either VBScript or PowerShell, this does not have to involve
completely rewriting existing scripts, you can use a couple of lines of either VBScript or PowerShell to launch an
elevated CMD.exe and that will run a batch file elevated.

Another approach is to use a third party utility that will elevate permissions.

Testing for Elevation


Testing if the current session is elevated can be done with the FSUTIL command (via StackOverflow) or SFC.
Note that you don't even have to pass a drive letter to FSUTIL, it will set an errorlevel without reading any drive
information.
fsutil dirty query >nul
If %errorLevel% NEQ 0 (
Echo Failure, please rerun this script from an elevated command prompt. Exiting...
Ping 127.0.0.1 3>&1 > nul
Exit /B 1
)
Echo Success: this script is running elevated.

When a script is run with elevated permissions several aspects of the user environment will change: The current
directory, the current TEMP folder and any mapped drives will be disconnected.

Run without Elevation


In some cases you may wish to run an application without elevation, this will restrict what the application can do.

The undocumented environment variable __COMPAT_LAYER can be used to lower the ExecutionLevel to
RunAsInvoker

@Echo Off
SETLOCAL
Set __COMPAT_LAYER=RunAsInvoker
regedit.exe

The example above will run REGEDIT using the user's native permissions, attempting to modify any protected
area of the registry (such as HKLM) within this session will produce an error.

Scheduled Tasks
If a scheduled task invokes a UAC prompt, then the task will fail to run unattended, to prevent this make sure to
select the 'Run With Highest Privileges' check box:

“A man in public life expects to be sneered at – it is the fault of his elevated situation, and not of himself” ~ Charles Dickens

Related

https://ss64.com/nt/syntax-elevate.html[8/24/2017 10:36:12 AM]


Run with elevated permissions UAC - Windows CMD - SS64.com

UAC (User Account Control) - Disable or Limit popup prompts


PowerShell: Run with Elevated Permissions
VBScript: Run with Elevated Permissions
SS64 Forum thread on UAC detection.
elevate - Command-Line UAC Elevation Utility

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-elevate.html[8/24/2017 10:36:12 AM]


Date Math - Add or subtract days - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

DateMath.cmd
Add or subtract days from any date, copy the script below or download here and save as DateMath.cmd
@ECHO off
SETLOCAL
:: DateMath, a general purpose date math routine
:: If DateMath detects an error, variable _dd_int is set to 999999.
SET v_dd_int=0
SET v_mm_int=0
SET v_yy_int=0
SET v_ymd_str=
SET v_mm_str=
SET v_dd_str=
IF "%3"=="" goto s_syntax
IF "%4"=="+" goto s_validate_year
IF "%4"=="-" goto s_validate_year
IF "%4"=="" goto s_validate_year
:s_syntax
echo:
echo DATEMATH SYNTAX:
echo _______________
echo:
echo DateMath will set the variables as listed below
echo 'str' variables include leading zeros e.g. "01"
echo 'int' variables leading zeros are stripped e.g. "1"
echo:
echo CALL DateMath YY MM DD - YY2 MM2 DD2
echo:
echo Will set variable _dd_int to the signed difference
echo between the 2 dates (measured in days)
echo:
echo:
echo CALL DateMath YY MM DD +/- Days
echo:
echo Will set the following variables to the result of
echo adding or substracting days from the initial date:
echo _ymd_str, _yy_int
echo _mm_str, _mm_int,
echo _dd_str, _dd_int
echo:
echo:
echo ___________________________________
pause
echo:
echo:
echo CALL DateMath YY MM DD
echo:
echo Will set the following variables:
echo _ymd_str, _yy_int
echo _mm_str, _mm_int,
echo _dd_str, _dd_int
echo:
echo ___________________________________
echo:
echo _ymd_str is in YYYYMMDD format.
echo:
echo _yy_int is in YYYY format, even if YY format was originally supplied.
echo This conversion is useful for FAT/NTFS file dates which are in YY format.
echo:
ENDLOCAL & SET /a _dd_int=999999
goto :eof
:s_validate_year
::strip leading zeros
SET v_yy=%1
if %v_yy:~0,1% EQU 0 set v_yy=%v_yy:~1%
:: Check for Y2K
IF %v_yy% LSS 100 IF %v_yy% GEQ 80 SET /A v_yy += 1900
IF %v_yy% LSS 80 SET /A v_yy += 2000
:: at this point v_yy contains a 4 digit year
::validate month and day
if %2 GTR 12 goto s_syntax
if %3 GTR 31 goto s_syntax
SET v_mm=%2
SET v_dd=%3

https://ss64.com/nt/syntax-datemath.html[8/24/2017 10:36:22 AM]


Date Math - Add or subtract days - Windows CMD - SS64.com

::strip leading zeros


if %v_mm:~0,1% EQU 0 set v_mm=%v_mm:~1%
if %v_dd:~0,1% EQU 0 set v_dd=%v_dd:~1%
:: Set the int variables
SET /a v_dd_int=%v_dd%
SET /a v_yy_int=%v_yy%
SET /a v_mm_int=%v_mm%
:: Determine which function to perform - ADD, SUBTRACT or CONVERT
If not "%6"=="" goto s_validate_2nd_date
if "%4"=="" goto s_convert_only
:: Add or subtract days to a date
SET /a v_number_of_days=%5
goto s_add_or_subtract_days
:s_convert_only
SET /a v_dd_int=%v_dd%
IF %v_dd% LEQ 9 (SET v_dd_str=0%v_dd%) ELSE (SET v_dd_str=%v_dd%)
IF %v_mm% LEQ 9 (SET v_mm_str=0%v_mm%) ELSE (SET v_mm_str=%v_mm%)
SET v_ymd_str=%v_yy%%v_mm_str%%v_dd_str%
ECHO DATEMATH - Convert date only (no maths)
goto s_end
::::::::::::::::::::::::::::::::::::::::::::::::::
:s_validate_2nd_date
If "%4"=="+" goto s_syntax
:: Subtracting one date from another ::::::
:: strip leading zero
SET v_yy2=%5
if %v_yy2:~0,1% EQU 0 set v_yy2=%v_yy2:~1%
if %v_yy2% GTR 99 goto s_validate2nd_month
if %v_yy2% GTR 49 goto s_prefix_2_1950_1999
if %v_yy2% LSS 10 goto s_prefix_2_2000_2009
SET v_yy2=20%v_yy2%
goto s_validate2nd_month
:s_prefix_2_2000_2009
SET v_yy2=200%v_yy2%
goto s_validate2nd_month
:s_prefix_2_1950_1999
SET v_yy2=19%v_yy2%
:s_validate2nd_month
::strip leading zeros
::SET /a v_yy2=%v_yy2%
if %v_yy2:~0,1% EQU 0 set v_yy2=%v_yy2:~1%
::v_yy2 now contains a 4 digit year
if %6 GTR 12 goto s_syntax
SET v_mm2=%6
if %7 GTR 31 goto s_syntax
SET v_dd2=%7
::strip leading zeros
::SET /a v_mm2=%v_mm2%
if %v_mm2:~0,1% EQU 0 set v_mm2=%v_mm2:~1%
::SET /a v_dd2=%v_dd2%
if %v_dd2:~0,1% EQU 0 set v_dd2=%v_dd2:~1%
call :s_julian_day %v_yy_int% %v_mm_int% %v_dd_int%
SET v_sumdays1=%v_JulianDay%
call :s_julian_day %v_yy2% %v_mm2% %v_dd2%
SET v_sumdays2=%v_JulianDay%
SET /a v_dd_int=%v_sumdays1% - %v_sumdays2%
ECHO DATEMATH - Subtracting one date from another = days difference
ECHO ~~~~~~
ECHO %v_dd_int%
ECHO ~~~~~~
goto s_end_days
::::::::::::::::::::::::::::::::::::::::::::::::::
:s_add_or_subtract_days
if /i "%4"=="+" goto s_add_up_days
:: Subtract all days ::::::
SET /a v_dd=%v_dd% - %v_number_of_days%
:s_adjust_month_year
if %v_dd% GEQ 1 goto s_add_subtract_days_DONE
SET /a v_mm=%v_mm% - 1
if %v_mm% GEQ 1 goto s_add_days_%v_mm%

https://ss64.com/nt/syntax-datemath.html[8/24/2017 10:36:22 AM]


Date Math - Add or subtract days - Windows CMD - SS64.com

SET /a v_yy=%v_yy% - 1
SET /a v_mm=%v_mm% + 12
goto s_add_days_%v_mm%
:s_add_days_2
SET /a v_dd=%v_dd% + 28
SET /a v_leapyear=%v_yy% / 4
SET /a v_leapyear=%v_leapyear% * 4
if %v_leapyear% NEQ %v_yy% goto s_adjust_month_year
SET /a v_dd=%v_dd% + 1
goto s_adjust_month_year
:s_add_days_4
:s_add_days_6
:s_add_days_9
:s_add_days_11
SET /a v_dd=%v_dd% + 30
goto s_adjust_month_year
:s_add_days_1
:s_add_days_3
:s_add_days_5
:s_add_days_7
:s_add_days_8
:s_add_days_10
:s_add_days_12
SET /a v_dd=%v_dd% + 31
goto s_adjust_month_year
:s_add_up_days
:: add all days ::::::
SET /a v_dd=%v_dd% + %v_number_of_days%
:s_subtract_days_
goto s_subtract_days_%v_mm%
:s_adjust_mth_yr
SET /a v_mm=%v_mm% + 1
if %v_mm% LEQ 12 goto s_subtract_days_%v_mm%
SET /a v_yy=%v_yy% + 1
SET /a v_mm=%v_mm% - 12
goto s_subtract_days_%v_mm%
:s_subtract_days_2
SET /a v_leapyear=%v_yy% / 4
SET /a v_leapyear=%v_leapyear% * 4
If %v_leapyear% EQU %v_yy% goto s_subtract_leapyear
if %v_dd% LEQ 28 goto s_add_subtract_days_DONE
SET /a v_dd=%v_dd% - 28
goto s_adjust_mth_yr
:s_subtract_leapyear
if %v_dd% LEQ 29 goto s_add_subtract_days_DONE
SET /a v_dd=%v_dd% - 29
goto s_adjust_mth_yr
:s_subtract_days_4
:s_subtract_days_6
:s_subtract_days_9
:s_subtract_days_11
if %v_dd% LEQ 30 goto s_add_subtract_days_DONE
SET /a v_dd=%v_dd% - 30
goto s_adjust_mth_yr
:s_subtract_days_1
:s_subtract_days_3
:s_subtract_days_5
:s_subtract_days_7
:s_subtract_days_8
:s_subtract_days_10
:s_subtract_days_12
if %v_dd% LEQ 31 goto s_add_subtract_days_DONE
SET /a v_dd=%v_dd% - 31
goto s_adjust_mth_yr
:s_add_subtract_days_DONE
SET /a v_dd_int=%v_dd%
SET /a v_mm_int=%v_mm%
SET /a v_yy_int=%v_yy%
IF %v_dd% GTR 9 (SET v_dd_str=%v_dd%) ELSE (SET v_dd_str=0%v_dd%)
IF %v_mm% GTR 9 (SET v_mm_str=%v_mm%) ELSE (SET v_mm_str=0%v_mm%)
SET v_ymd_str=%v_yy%%v_mm_str%%v_dd_str%
ECHO DATEMATH - add or subtract days from a date = new date
goto s_end
::::::::::::::::::::::::::::::::::::::::::::::::::
:s_julian_day
SET v_year=%1
SET v_month=%2
SET v_day=%3

https://ss64.com/nt/syntax-datemath.html[8/24/2017 10:36:22 AM]


Date Math - Add or subtract days - Windows CMD - SS64.com

SET /a v_month=v_month
SET /a v_day=v_day
SET /A a = 14 - v_month
SET /A a /= 12
SET /A y = v_year + 4800 - a
SET /A m = v_month + 12 * a - 3
SET /A m = 153 * m + 2
SET /A m /= 5
SET /A v_JulianDay = v_day + m + 365 * y + y / 4 - y / 100 + y / 400 - 32045
ECHO The Julian Day is [%v_JulianDay%]
goto :eof
::::::::::::::::::::::::::::::::::::::::::::::::::
:s_end
ECHO ~~~~~~~~~~~~
ECHO [%v_ymd_str%] YY=[%v_yy_int%] MM=[%v_mm_str%] DD=[%v_dd_str%]
ECHO ~~~~~~~~~~~~
:s_end_days
ENDLOCAL&SET /a _yy_int=%v_yy_int%&SET /a _mm_int=%v_mm_int%&SET /a _dd_int=%v_dd_int%&SET
_ymd_str=%v_ymd_str%&SET _mm_str=%v_mm_str%&SET _dd_str=%v_dd_str%

Examples

D:\> datemath 02 05 08
DATEMATH - Convert date only (no maths)
~~~~~~~~~~~~
[20020508] YY=[2002] MM=[05] DD=[08]
~~~~~~~~~~~~

D:\> datemath 2007 12 30


DATEMATH - Convert date only (no maths)
~~~~~~~~~~~~
[20071230] YY=[2007] MM=[12] DD=[30]
~~~~~~~~~~~~

D:\> datemath 27 12 01 - 02 11 02
The Julian Day is [2461741]
The Julian Day is [2452581]
DATEMATH - Subtracting one date from another = days difference
~~~~~~
9160
~~~~~~

D:\> datemath 02 11 02 + 9160


DATEMATH - add or subtract days from a date = new date
~~~~~~~~~~~~
[20271201] YY=[2027] MM=[12] DD=[01]
~~~~~~~~~~~~

D:\> datemath 2012 09 08 - 2011 09 08


The Julian Day is [2456179]
The Julian Day is [2455813]
DATEMATH - Subtracting one date from another = days difference
~~~~~~
366
~~~~~~

D:\> datemath 13 09 08 - 12 09 08
The Julian Day is [2456544]
The Julian Day is [2456179]
DATEMATH - Subtracting one date from another = days difference
~~~~~~
365
~~~~~~

“We were having one of those great first dates you can only have when it's not an actual date” ~ Sarah Jessica Parker

https://ss64.com/nt/syntax-datemath.html[8/24/2017 10:36:22 AM]


Date Math - Add or subtract days - Windows CMD - SS64.com

Related:

SetLocal - Control the visibility of environment variables in a batch file.


Powershell variables - these support Math operations out of the box ( .addDays )
Rules for how CMD.EXE parses numbers - DosTips forum (Dave Benham)

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-datemath.html[8/24/2017 10:36:22 AM]


Dequote - remove quotes - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Remove Quotes from a string


Several routines that can be used to remove quotes from the contents of a variable.

In the majority of cases running any current version of Windows, the simplest method is to use %~1 Parameter Extensions to
remove the quotes automatically
@ECHO OFF
Set _string=%~1
Echo the string passed to this script is %_string%

(you may also want to test IF the variable is empty/NULL)

This is equivalent to the following, which can be used to remove outer quotes from any string, not just a parameter string:
:: Remove quotes
SET _string=###%_string%###
SET _string=%_string:"###=%
SET _string=%_string:###"=%
SET _string=%_string:###=%

If you just want to remove ALL quotes from a string, this can be done in one line with variable replace syntax:
Set _somevariable=%_somevariable:"=%

File and folder names cannot (legally) contain quotes so the above is often all that's needed.

A one line function, using a FOR command to run parameter expansion and remove quotes (the %~A removes the quotes), this
is a good approach when you need to dequote multiple strings, just call the function with each string:
::::::::: one line Dequote example ::::::::::::
@Echo Off
Setlocal
Set _mypath="C:\Program Files\ss64\"
CALL :dequote _mypath
Echo %_mypath%
Goto :eof

:DeQuote
for /f "delims=" %%A in ('echo %%%1%%') do set %1=%%~A
Goto :eof

The above will turn "C:\Program Files\ss64\" into C:\Program Files\ss64\

If the line in bold is saved as a single line batch file DeQuote.cmd, then it can be called from other batch scripts:

CALL DeQuote.cmd VariableName

There may be cases when you only want to affect the string if it both starts and ends with a quote and raise an error or some
other action if mismatched quotes are found. Some more complex scripts to handle this can be found here in the forum.

“One look is worth a thousand words” ~ Fred R. Barnard

Related:

SetLocal - EnableDelayedExpansion
Long Filenames and NTFS - Valid characters in filenames

https://ss64.com/nt/syntax-dequote.html[8/24/2017 10:36:31 AM]


Dequote - remove quotes - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-dequote.html[8/24/2017 10:36:31 AM]


Delolder - Delete files older than - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Delete files older than N days


There are several ways to do this

1) Using ForFiles to delete files over 7 days old:

C:\> forfiles /p "C:\source_folder" /s /m *.* /c "cmd /c Del @path" /d -7

2) Using Robocopy /Move to delete files over 7 days old:


C:\> set _robodel=%TEMP%\~robodel
C:\> MD %_robodel%
C:\> ROBOCOPY "C:\source_folder" %_robodel% /move /minage:7
C:\> del %_robodel% /q

3) Using DateMath.cmd and Getdate.cmd, download DelOlder.cmd

4) With PowerShell delete files over 7 days old:


PS C:\> $now = get-date
PS C:\> dir "C:\source_folder\" | where {$_.LastWriteTime -le $now.AddDays(-7)} | del -whatif

Powershell also has .AddHours if you want to delete more recent files.

“We were having one of those great first dates you can only have when it's not an actual date” - Sarah Jessica Parker

Related:

SetLocal - Control the visibility of environment variables in a batch file.


Powershell methods - Math operations ( .addDays )

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-delolder.html[8/24/2017 10:36:40 AM]


GenChr.cmd - generate an ASCII/Unicode character - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

GenChr.cmd
Generate the ASCII/Unicode character for any byte value. The output is a file bytevalue.chr
@echo off
set "USAGE=echo:Usage: Supply an integer 0-255& goto :EOF"
if "%~1" equ "" %USAGE%
set /a "val=%~1" 2>nul
if "%~1" neq "%val%" %USAGE%
if %~1 lss 0 %USAGE%
if %~1 gtr 255 %USAGE%
set tempfile=%~1.tmp
set "options=/d compress=off /d reserveperdatablocksize=26"
if %~1 neq 26 (type nul >"%tempfile%"
makecab %options% /d reserveperfoldersize=%~1 "%tempfile%" %~1.chr >nul
type %~1.chr | (
(for /l %%N in (1 1 38) do pause)>nul&findstr "^">"%tempfile%")
>nul copy /y "%tempfile%" /a %~1.chr /b
del "%tempfile%"
) else (copy /y nul + nul /a 26.chr /a >nul)

Written via the teamwork of carlos, penpen, aGerman, dbenham & bluesxman - see forum thread

Examples

Create the 0 or NUL character (file 0.chr)


genchr.cmd 0

Create the 9 or tab character. (file 9.chr)


genchr.cmd 9

Create all 256 characters/files:


for /l %a in (0,1,255) do start "" cmd /c genchr %a

“When the character of a man is not clear to you, look at his friends” ~ Japanese Proverb

Related

Ascii table
MAKECAB Create .CAB files

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-genchr.html[8/24/2017 10:36:49 AM]


GetDate - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

GetDate.cmd
Display the date and time independent of OS Locale, Language or the users chosen date format (Control Panel/Regional).

If all you need is the current date and time in local format, you can just use the built in variables %date% and %time% the more
difficult problem is making this work for any locale so that it can be used across international networks.

Method 1 - Calling a VBScript getdate.vbs for Windows XP or greater


@Echo off
For /f %%G in ('cscript /nologo getdate.vbs') do set _dtm=%%G
Set _yyyy=%_dtm:~0,4%
Set _mm=%_dtm:~4,2%
Set _dd=%_dtm:~6,2%
Set _hh=%_dtm:~8,2%
Set _nn=%_dtm:~10,2%
Echo %_yyyy%-%_mm%-%_dd%T%_hh%:%_nn%

Method 2 - Calling WMIC for Windows XP Professional or Vista/Windows 7


@Echo off
:: Check WMIC is available
WMIC.EXE Alias /? >NUL 2>&1 || GOTO s_error
:: Use WMIC to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year
/Format:table') DO (
IF "%%~L"=="" goto s_done
Set _yyyy=%%L
Set _mm=00%%J
Set _dd=00%%G
Set _hour=00%%H
SET _minute=00%%I
)
:s_done
:: Pad digits with leading zeros
Set _mm=%_mm:~-2%
Set _dd=%_dd:~-2%
Set _hour=%_hour:~-2%
Set _minute=%_minute:~-2%
:: Display the date/time in ISO 8601 format:
Set _isodate=%_yyyy%-%_mm%-%_dd% %_hour%:%_minute%
Echo %_isodate%
GOTO:EOF
:s_error
Echo GetDate.cmd
Echo Displays date and time independent of OS Locale, Language or date format.
Echo Requires Windows XP Professional, Vista or Windows 7
echo:
Echo Returns 6 environment variables containing isodate,Year,Month,Day,hour and minute.
Based on the sorted date code by Rob van der Woude.

Previous versions of this script (for Windows XP) used the DATE command, under Windows 7 this now gives different output
strings dependent on the short date format and OS Language.

"I've been on the calendar, but never on time" ~ Marilyn Monroe

Related

datetime.vbs - Get Date, Time and daylight savings (VB Script)


Get UNIX format date - Dave Benham / StackOverflow (WMIC)
Standard date and time notation - YYYY-MM-DD
Date/Time scripts - Rob van der Woude
Date/Time scripts - Ritchie Lawrence

https://ss64.com/nt/syntax-getdate.html[8/24/2017 10:36:58 AM]


GetDate - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-getdate.html[8/24/2017 10:36:58 AM]


GetTime - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

GetTime.cmd
Returns the current time into the variable %_time%
@echo off
SETLOCAL
For /f "tokens=1-3 delims=1234567890 " %%a in ("%time%") Do set "delims=%%a%%b%%c"
For /f "tokens=1-4 delims=%delims%" %%G in ("%time%") Do (
Set _hh=%%G
Set _min=%%H
Set _ss=%%I
Set _ms=%%J
)
:: Strip any leading spaces
Set _hh=%_hh: =%
:: Ensure the hours have a leading zero
if 1%_hh% LSS 20 Set _hh=0%_hh%
Echo The time is: %_hh%:%_min%:%_ss%
ENDLOCAL&Set _time=%_hh%:%_min%

Although the default time delimiter, in Windows XP and above is either . or : users can change the delimiter to just about
any character they like. And you know theres always that one guy, the one who writes everything in green ink, who will do
this!

Based on the discussion thread here, this script always returns HH:MM no matter which time delimiter has been set in the
control panel. Thanks to avery_larry and bluesxman for their improvements. To include Milliseconds just tack on the %_ms%
variable.

“What may be done at any time will be done at no time” ~ Scottish Proverb

Related

datetime.vbs - Get Date, Time and daylight savings (VB Script)


%TIME% - variable containing current time
TIME - Set the time (list of default time formats for different countries)
GetDate.cmd - Get todays date (any region, any OS)
tdiff.cmd - Time difference in Hours/Minutes
Commandline.co.uk - date/time scripts
Rob Vanderwoude - date/time scripts

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-gettime.html[8/24/2017 10:37:07 AM]


GMT Time - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

GMT.cmd
Returns the current time into the variable %_gmt% adjusted to Greenwich Mean Time, this can be useful when comparing
events across multiple time zones or whenever you don’t want daylight savings to affect the result.
::gmt.cmd Display the current time in GMT (World Time)
@echo off
Setlocal
Set _key=HKLM\System\CurrentControlSet\Control\TimeZoneInformation
:: find offset from GMT in minutes
For /f "Tokens=3" %%G in ('Reg query %_key% /V ActiveTimeBias^|FIND "REG_DWORD"') do (
Set /a _offset=%%G
)
:: Convert to hours
Set /a _offset_hours=%_offset% / 60
:: Get current local time
For /f "tokens=1-3 delims=1234567890 " %%a in ("%time%") Do set "delims=%%a%%b%%c"
For /f "tokens=1-4 delims=%delims%" %%G in ("%time%") Do (
Set _hh=%%G
Set _min=%%H
)
:: Strip any leading spaces
Set _hh=%_hh: =%
:: Ensure the hours have a leading zero
if 1%_hh% LSS 20 set _hh=0%_hh%
Echo Local time: %_hh%:%_min%
:: add offset to the current time
Set /a _hh=%_hh% + %_offset_hours%
:: display result
Echo GMT time: %_hh%:%_min%
ENDLOCAL&Set _gmt=%_hh%:%_min%

“Time is like money, the less we have of it to spare, the further we make it go” ~ Josh Billings

Related

datetime.vbs - Get Date, Time and daylight savings (VB Script)


GetTime.cmd - Get the time now
TIME - Set the time (list of default time formats for different countries)
Rob Vanderwoude - date/time scripts

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-gmt.html[8/24/2017 10:37:16 AM]


StampMe.cmd - rename a file with todays date and time - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

StampMe.cmd
Rename a file (or folder) by appending the current date and time to the existing filename:
@ECHO off
SETLOCAL
IF [%1] NEQ [] goto s_start
:: Author - Simon Sheppard, Nov 2014
:: Tested for Windows XP Pro or greater
Echo StampMe.cmd
Echo Rename a file with the DATE/Time
Echo:
Echo Syntax
Echo STAMPME TestFile.txt
Echo:
Echo STAMPME "Test File.txt"
Echo:
Echo STAMPME "c:\docs\Test File.txt"
Echo:
Echo Will rename the file in the format "Test [email protected]"
Echo:
Echo In a batch file use CALL STAMPME ...
GOTO :eof
:s_start
Set _file=%~n1%
Set _pathname=%~f1%
Set _ext=%~x1%
:: Get the date/time
FOR /f %%a in ('WMIC OS GET LocalDateTime ^| find "."') DO Set _DTS=%%a
Set _datetime=%_DTS:~0,4%-%_DTS:~4,2%-%_DTS:~6,2%@%_DTS:~8,2%-%_DTS:~10,2%-%_DTS:~12,2%
Echo Year-MM-Day@HR-Min-Sec
Echo %_datetime%
:: Rename the file
REN "%_pathname%" "%_file%-%_datetime%%_ext%"

The last line of the batch file does the REName.

Examples
c:\> StampMe "sample file.txt"
c:\> StampMe "C:\logs\data\errorlog.txt"
c:\> StampMe "C:\docs\example folder"

An alternative 'quick and dirty' way to do the same thing in one line is shown below, this does work but is less robust as the
results will vary according to regional/control panel settings.
c:\> REN "sample file.txt" "* %Date:/= % %Time::=.%.*"

“The time you enjoy wasting is not wasted time” ~ Bertrand Russell

Related

DelOlder.cmd - Delete files more than n days old


GetDate and GetTime scripts
Standard date and time notation - YYYY-MM-DD
Stampme.ps1 - Powershell version

https://ss64.com/nt/syntax-stampme.html[8/24/2017 10:37:25 AM]


StampMe.cmd - rename a file with todays date and time - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-stampme.html[8/24/2017 10:37:25 AM]


tdiff - Time difference - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

tdiff.cmd
Calculate the time difference between two time values in hours, minutes and seconds.
@Echo off
Setlocal
if "%~1" EQU "" goto s_syntax
:: Convert start and end times to hundredths of a second
Call :s_calc_timecode %1
Set _start_timecode=%errorlevel%
Call :s_calc_timecode %2
Set _stop_timecode=%errorlevel%
:: Calculate the difference in hundredths
Set /a _diff_timecode=_stop_timecode - _start_timecode
:: Midnight rollover
if %_diff_timecode% LSS 0 set /a _diff_timecode+=(24 * 60 * 60 * 100)
Echo %_diff_timecode% hundredths of a second
:: Split out Hours, Mins etc and return the result
set /a hs=_diff_timecode %% 100
set /a _diff_timecode/=100
set /a ss=_diff_timecode %% 60
set /a _diff_timecode/=60
set /a mm=_diff_timecode %% 60
set /a _diff_timecode/=60
set /a hh=_diff_timecode
set hh=0%hh%
set mm=0%mm%
set ss=0%ss%
set hs=0%hs%
set _tdiff=%hh:~-2%:%mm:~-2%:%ss:~-2%.%hs:~-2%
Echo HH:MM:ss.hs
Echo %_tdiff%
endlocal & set _tdiff=%_tdiff%
goto :EOF

:s_calc_timecode
:: Remove delimiters and convert to hundredths of a second.
setlocal
For /f "usebackq tokens=1,2,3,4 delims=:." %%a in ('%1') Do (
set hh=00%%a
set mm=00%%b
set ss=00%%c
set hs=00%%d
)
set hh=%hh:~-2%
set mm=%mm:~-2%
set ss=%ss:~-2%
set hs=%hs:~-2%
set /a hh=((%hh:~0,1% * 10) + %hh:~1,1%) * 60 * 60 * 100
set /a mm=((%mm:~0,1% * 10) + %mm:~1,1%) * 60 * 100
set /a ss=((%ss:~0,1% * 10) + %ss:~1,1%) * 100
set /a hs=((%hs:~0,1% * 10) + %hs:~1,1%)
set /a _timecode=hh + mm + ss + hs
Endlocal & Exit /b %_timecode%
:s_syntax
Echo:
Echo Syntax: tdiff.cmd StartTime StopTime
Echo:
Echo The times can be given in the format:
Echo HH or HH:MM or HH:MM:ss or HH:MM:ss.hs
Echo:
Echo so for example: tdiff %%time%% 23
Echo will give the time difference between now and 23:00:00.00
Echo:
Echo The result is returned in variable %%_tdiff%%
Exit /b 1

Examples
c:\> tdiff 14:30 23:15

https://ss64.com/nt/syntax-tdiff.html[8/24/2017 10:37:34 AM]


tdiff - Time difference - Windows CMD - SS64.com

c:\> tdiff 14:30:05 16:45:12

“God, grant me the serenity to accept the things I cannot change, the courage to change the things I can, and the wisdom to know the
difference” ~ Reinhold Niebuhr

Related

Chronometer/Timer app - SS64 Forum


DelOlder.cmd - Delete files more than n days old
GetTime script

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-tdiff.html[8/24/2017 10:37:34 AM]


Which.cmd - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Which.cmd
Show the full path to an executable file.
:: WHICH.CMD CommandName [ReturnVar]
::
:: Determines the full path of the file that would execute if
:: CommandName were executed.
::
:: The result is stored in variable ReturnVar, or else it is
:: echoed to stdout if ReturnVar is not specified.
::
:: If no file is found, then an error message is echoed to stderr.
::
:: The ERRORLEVEL is set to one of the following values
:: 0 - Success: A matching file was found
:: 1 - No file was found and CommandName is an internal command
:: 2 - No file was found and CommandName is not an internal command
:: 3 - Improper syntax - no CommandName specified
::
@echo off
setlocal disableDelayedExpansion
set "file=%~1"
if not defined file (
>&2 echo Syntax error: No CommandName specified
exit /b 3
)
set "noExt="
setlocal enableDelayedExpansion
if "%~x1" neq "" if "!PATHEXT:%~x1=!" neq "!PATHEXT!" set noExt="";
set "modpath=.\;!PATH!"
@for %%E in (%noExt%%PATHEXT%) do @for %%F in ("!file!%%~E") do (
setlocal disableDelayedExpansion
if not "%%~$modpath:F"=="" if not exist "%%~$modpath:F\" (
endlocal & endlocal & endlocal
if "%~2"=="" (echo %%~$modpath:F) else set "%~2=%%~$modpath:F"
exit /b 0
)
endlocal
)
endlocal
>nul help %~1 && (
>&2 echo "%~1" is not a valid command
exit /b 2
)
>&2 echo "%~1" is an internal command
:: Credits:
:: Dave Benham
:: forum thread

Related

WHERE - Locate and display files in a directory tree.


whereis utility - Flounder.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-which.html[8/24/2017 10:37:43 AM]


xlong filename 256 character limit - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

xlong.cmd
It is possible to create very long filenames/pathnames on NTFS that exceed the Windows API limit. This typically happens
when a folder which is part of a deep hierarchy gets renamed. Very long filenames will often create errors in applications that
attempt to open them (even Windows Explorer.)

The script below will list any files that exceed this limit.
@Echo off
Setlocal EnableDelayedExpansion
:: Report all file / folder paths that exceed the 256 character limit
If {%1}=={} Echo Syntax: XLong DriveLetter&goto :EOF
Set wrk=%1
Set wrk=%wrk:"=%
For /F "Tokens=*" %%a in ('dir %wrk% /b /s /a') do (
set name=%%a
if not "!name:~255,1!"=="" echo Extra long name: "%%a"
)
Endlocal

Examples

Check the whole of the D: drive


c:\> xlong D:\

Check the current directory on the C: drive:


c:\> xlong C:

Check the S:\workgroups\ folder:


c:\> xlong S:\workgroups\

The maximum Windows API MAX_Path is 260 characters, subtract 3 characters for the drive and colon: and 1 character for a
terminating NULL and you have a maximum 256 characters that can be used for the pathname.

All .Net applications enforce the Windows API pathname limit including Windows Explorer and PowerShell.

To access very long paths use Robocopy, SUBST or the \\?\UNCPATH\ syntax.

“This report, by its very length, defends itself against the risk of being read” ~ Winston Churchill

Related

Which.cmd - Display full path to any command


Bash equivalent:
find . | awk '{print length($0) " " $0}' | sort -n | tail -n 15

https://ss64.com/nt/syntax-xlong.html[8/24/2017 10:37:52 AM]


xlong filename 256 character limit - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-xlong.html[8/24/2017 10:37:52 AM]


Autoexec and AutoRun| Windows CMD | SS64.com

(  SS64  ) CMD Syntax


Search

Autoexec commands
To run a command as soon as the command prompt is opened -

HKLM\Software\Microsoft\Command Processor\AutoRun
HKCU\Software\Microsoft\Command Processor\AutoRun

To run a command as soon as a user logs in -

The STARTUP folder (Start Menu)


HKLM\Software\Microsoft\Windows\CurrentVersion\Run
HKCU\Software\Microsoft\Windows\CurrentVersion\Run
HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\Run

To run a command as soon as the machine powers up, (like AUTOEXEC.BAT in MS-DOS), use the Windows Task
Scheduler - choosing the option:

Run a task:
When my computer starts (before a user logs on)

Autoexec.bat file

The autoexec.bat file was an MS-DOS feature. Under Windows there is a still a degree of backwards compatibility - if the file
(C:\autoexec.bat) exists, any SET statements within it will be parsed at boot time.
Variables set in this way are not available to gui programs - they will be visible from the CMD prompt but don’t appear in the
control panel. All other commands in autoexec.bat will be ignored. This behaviour is to allow old DOS applications to install
correctly.

Scripts running at Windows startup


To see exactly what is running (or running slowly) at windows startup/login, set the following registry key:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system]
"verbosestatus"=dword:00000001

AutoRun
In Windows 7/2008 R2, autorun events are (mostly) restricted to drives of type DRIVE_CDROM. The default behaviour is to
invoke AutoPlay. The NoAutoRun registry entry can be used to disables the AutoPlay and/or AutoRun feature on individual
drives. This can be set in the registry under HKCU and/or HKLM. (If both are set then HKLM will take priority.)

The NoDriveTypeAutoRun registry entry disables or enables the AutoRun feature on all drives of the type specified. It can be
set in the registry under HKCU and/or HKLM. (If both are set then HKLM will take priority.) Values: 0xFF =Disable AutoRun on
all types of drive, 0x91 =Disable AutoRun on network drives, 0x95 =Disable AutoRun on removable + network drives.

The NoDriveAutoRun registry entry disables or enables the AutoRun feature on individual drives. It can be set in the registry
under HKCU and/or HKLM. (If both are set then HKLM will take priority.)

In all cases the registry keys are set under:


\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer

The registry key HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2 contains cached information


about every removable device seen so far. This cache can bypass the registry settings above which can leave a machine
vulnerable. See Q967715 for patches that address this issue. Alternatively the iniFileMapping method described below will
disable AutoRun completely.

To effectively disable AutoRun in all versions of Microsoft Windows, import the following registry value (source: US-Cert Alert
TA09-020A) this applies to any autorun.inf in any location and on any drive:

https://ss64.com/nt/syntax-autoexec.html[8/24/2017 10:38:01 AM]


Autoexec and AutoRun| Windows CMD | SS64.com

REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\IniFileMapping\Autorun.inf]
@="@SYS:DoesNotExist"

“The real danger is not that machines will begin to think like men, but that men will begin to think like machines” ~ Sydney J. Harris

Related:

SC - Service Control
SET - Display, set, or remove Windows environment variables
Q967715 - How to disable the Autorun functionality in Windows
Q137890 - SRVANY - create a User-Defined Service
Q243486 - AutoExNT Run a Batch File before Logging on (Windows 2000)

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-autoexec.html[8/24/2017 10:38:01 AM]


Slow Network Browsing - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Slow network browsing issues in Windows


1) Listing the contents of a shared folder is slow - Desktop.ini
The file permissions set on desktop.ini files can slow down browsing the folder structure. This issue affects Windows clients
using mapped drives or UNC connections, this issue was fixed in XP sp2 (Q840309), but from Q326549 has re-emerged in
Windows 7.

When listing a directory, Windows will search for and parse Desktop.ini files. This will noticably affect performance when a
large number of subfolders are involved, it does this for the current folder and one level down the directory tree.

Desktop.ini can be used to provide a custom icon, thumbnail view, and can make normal file folders into 'Special Folders' (eg
Fonts, History, Temporary Internet Files, "My Music", "My Pictures", and "My Documents").

Desktop.ini files are only visible in Windows Explorer if you first un-check "Hide protected operating system files" (under
Tools, Options, View)

To see the file locks created by this process run the following command on the file server, while a client is (slowly) listing a
large directory:
NET FILE | Find "desktop.ini"

A quick solution to this performance problem is to remove the READ_ONLY attribute from the folder and/or delete the non-
essential desktop.ini files.

2) Explorer randomly locks files


There are reports that Windows Explorer can run very slowly or stop responding if some of the profile permissions get
corrupted.

To fix this logout and login with a different (Administrator level) account and rename this folder:
C:\Users\<profilename>\AppData\Local\Microsoft\Windows

When you login again the folder will be re-created with the correct permissions.

3) Shortcuts in the Windows XP 'My Network Places' make network browsing very slow.
If the 'My Network Places' folder contains a shortcut to a network share, then each refresh of the explorer window will attempt
to read icon information from every file in the remote location, causing the system to slow to a crawl.

Removing all shortcuts from 'My Network Places' will return the system response to normal.
In Windows 7, network places have been moved under 'Computer' and this issue seems to have been fixed.

Every time you open a file via a UNC name, Windows XP will automatically add another shortcut to the 'My Network Places'
folder - so the issue tends to get worse over time.

You can prevent the automatic addition of shortcuts with the registry setting below:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]
"NoRecentDocsNethood"=dword:00000001

4) Network Shortcuts on the Start menu and Desktop


Placing a shortcut to a network resource in either the Start menu or Desktop (including the recycle bin) can drastically slow
down system response, particularly when the network resource is unavailable. Shortcuts to Domains or Machines don’t suffer
from these problems as they always have the same icon.

https://ss64.com/nt/slow_browsing.html[8/24/2017 10:38:10 AM]


Slow Network Browsing - Windows CMD - SS64.com

A sensible routine for managing desktop shortcuts can be found here.

An alternative worksround is to create a shortcut to Explorer.exe and pass the UNC name of the resource.
explorer /e, \\Server\FileShare

"Total world oil reserves amount to one thousand billion barrels, yearly consumption is 27 billion barrels" ~ BP Amoco

Related:

CleanRoamingProfile.vbs - VBScript to delete selected files from a roaming profile.


Q841978 - Explorer.exe stops responding when you use network shortcuts (XP)
SysInternals - Mark Russinovich - Desktop.ini files fill up the audit event log.
Windows 7 Slow Logon – Waiting for the User Profile Service
Q904160 - File sharing on the network is slower than expected (WinServer 2003 SP1)
Q885189 - Slow performance from a mapped drive - Windows Server 2003
Q841978 - Explorer.exe stops responding when you use network shortcuts (XP)
Q834350 - Access to network resources is slower
Q822219 - Slow File Server Performance
Q819017 - Long delay before files appear in My Computer (XP)
Q816375 - XP Explorer pane flickers
Q814112 - Network shares open slowly SMB/AntiVirus scanning
Q326549 - Read-only & System attributes for folders
Q321281 - Desktop.ini does not work correctly when you customise the Default Profile
Q320138 - Disable automatic search for network printers and folders (XP)
Q320829 - Increase the Request Size Buffer on the file server - (try between 32 and 64 Kb)
Q319470 - Office2000: Screen response is slow in Save As dialog box in Word
Q315237 - 100-Megabit network packets
Q312403 - Distributed Link Tracking
Q265396 - Slow network performance on a share that uses NTFS
Q245800 - Delay viewing shares (Windows 98/2000)
CleanMgr - Automated cleanup of Temp files, recycle bin

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/slow_browsing.html[8/24/2017 10:38:10 AM]


Desktop Heap - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Increasing the Desktop Application Heap


When you run a large number of Windows-based programs, "Out Of Memory" error messages appear when you attempt to
start new programs or try to use programs that are already running.

In the case of WinNT services the process simply dies for no obvious reason.

This error can occur if the desktop heap in the WIN32 subsystem is depleted; even though you still have plenty of physical
and pagefile memory available.

Desktop Heap memory is defined in the registry under the (long string) key 'SharedSection'::

Default settings Windows XP:


HKLM\System\CurrentControlSet\Control\Session Manager\SubSystems
%SystemRoot%\system32\csrss.exe
ObjectDirectory=\Windows
SharedSection=1024,3072
Windows=On
SubSystemType=Windows
ServerDll=basesrv,1
ServerDll=winsrv:UserServerDllInitialization,3
ServerDll=winsrv:ConServerDllInitialization,2
ProfileControl=Off MaxRequestThreads=16

In this case 1024 defines the system heap size, 3072 controls the size of the interactive desktop heap (used for Windows
objects).
If a third value is present e.g. "1024,3072,512", this covers the non-interactive desktop heap. All values are KBytes.
If the 3rd value is not present non-interactive desktops will default to the same value as interactive desktops (typically 3072
K).

In Vista SP1 or Windows Server 2008 this increases to 12 MB:


HKLM\System\CurrentControlSet\Control\Session Manager\SubSystems\Windows
SharedSection=1024,12288,512

64-bit Windows has a default interactive desktop heap size of 20MB

Microsoft do not recommend that you set a value that is over 20,480 KB for the second SharedSection value.

Lower values increase performance at the risk of crashing any process which can run out of resources.

For many applications (in Win XP) 3072K is too high, although MS recommend 512 K (in Q142676) for many applications this
is too low.

512 K will support approximately 2,500 windows, menus, pens, icons, etc.
1024 K will support approximately 5,000 windows, menus, pens, icons, etc.
3072 K will support approximately 15,000 windows, menus, pens, icons, etc.

Because the non-interactive desktop heap is mapped into the address space of each and every process', this value should
not be set to an arbitrarily high value, but should only be increased sufficiently to allow all the desired applications to run. Note
that many server side applications such as Oracle Forms will spawn multiple processes for each user request.

Because NT only supports one interactive session at a time; tuning the interactive desktop heap has less impact on total
memory use.

Windows NT has a system wide memory limit of 48 Mb for all the above desktop heaps, if this limit is exceeded there might
not be enough memory to create an error message dialog box. As a result, the requested operation fails without any
indication.

Related

https://ss64.com/nt/syntax-desktopheap.html[8/24/2017 10:38:19 AM]


Desktop Heap - Windows CMD - SS64.com

Desktop heap monitor - Examine desktop heap usage for WinXP/2003


Q126962 - Desktop Heap - NT 4, Windows 2000
Q184802 - Desktop Heap - NT 4, Windows 2000, Windows XP, 2003
Q947246 - Desktop Heap - Vista
Desktop Heap Overview - Blog from the Microsoft Critical Problem Resolution (CPR) Platforms Team.

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-desktopheap.html[8/24/2017 10:38:19 AM]


Long filenames - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Long filenames, NTFS and legal filename characters


Long file names - If a filename contains spaces you must surround it "with double quotes" Filenames that include quotes or
parenthesis (') - these are legal filenames but they can cause problems.

Short file names - The order in which you create files will affect short 8.3 names
e.g.
echo abc > "a long file 1.txt"
echo abc > "a long file 3.txt"
echo abc > "a long file 2.txt"
DIR /x
:: will produce this:
ALONGF~1.TXT a long file 1.txt
ALONGF~3.TXT a long file 2.txt
ALONGF~2.TXT a long file 3.txt

If these files are now copied to another folder the 8.3 filenames will change, this is most likely to happen when upgrading
server storage or restoring data from a backup.

Similarly for folders


md "a long folder 1"
md "a long folder 3"
md "a long folder 2"
DIR /x
:: will produce this:
ALONGF~1 a long folder 1
ALONGF~3 a long folder 2
ALONGF~2 a long folder 3

Again copying these to somewhere else will change the 8.3 names to:
ALONGF~1 a long folder 1
ALONGF~2 a long folder 2
ALONGF~3 a long folder 3

See the Wildcards page for more long/short filename issues.

Enable or Disable 8.3 filenames in NTFS


If 8.3 filenames are disabled, ancient 16 bit software (like WordPerfect 3) will still be able to read/write short
filenames (C:\WORK\JAN.WPD), but won’t see a short equivalent for long filenames (C:\My Documents\new
stuff.wpd).
An 8.3 filename can also be useful when dealing with corruption such as an 'undeletable' file.

Disable the creation of 8.3 filenames


[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem]
NtfsDisable8dot3NameCreation=1

Enable the creation of 8.3 filenames (default)


[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem]
NtfsDisable8dot3NameCreation=0

Batch files .BAT or .CMD ?


Batch files can be saved with the extension .BAT or .CMD
The .BAT extension will run under Windows 95/MSDOS but the .CMD extension will only run under NT, XP or
later.
One key difference between .CMD and .BAT scripts (running under CMD.EXE) is that with extensions enabled,

https://ss64.com/nt/syntax-filenames.html[8/24/2017 10:38:28 AM]


Long filenames - Windows CMD - SS64.com

commands like PATH/APPEND/PROMPT/SET/ASSOC will reset ERRORLEVEL to 0 if they succeed. In the old
style .BAT file, the ERRORLEVEL will not be changed unless there is a new error (source).

NTFS file system


Legal characters in NTFS include the following:
! [ ] . ; = ( )

Illegal Characters: The following characters are not permitted in Windows file or directory names:
/ \ : * ? " < > |

The control characters ( 0x00-0x1F, 0x7F ) are also invalid in Windows' FAT and NTFS.
Windows Explorer will not create files with a period (.) as the first or only character in the filename, although NTFS
(and many command-line tools) do support this.

A long file name (LFN) can be up to 255 characters long.


NTFS supports paths up to 32768 characters in length, but only when using the Unicode APIs.

When using very long path names, prefix the path with the characters \\?\ and use the Unicode versions of the C
Runtime functions.

8.3 format filenames


These can have between 1 and 8 characters in the file name. Short file names have the 8.3 format and are
compatible with MS-DOS and other legacy operating systems.
The name must start with a letter or a number and can contain any characters except the following:

 / \ : * ? " [ ] | = , . ; (space)

An 8.3 file name typically has a file name extension between one and three characters long with the same
character restrictions. A period separates the file name from the file name extension.

It should be noted that some characters are invalid in 8.3 format filenames but are valid in NTFS filenames and
are also valid Delimiters Typically the Windows GUI will silently rename such files where necessary.

You can use long file names in both NTFS and FAT volumes.

Special file names reserved by the system (cannot be used for files or folders):

CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, NUL , conIN$ , conOUT$

“Tongues, like governments, have a natural tendency to degeneration; we have long preserved our constitution, let us make some
struggles for our language” - Samuel Johnson: Preface to the Dictionary

Related:

Escape Characters, Delimiters and Quotes

https://ss64.com/nt/syntax-filenames.html[8/24/2017 10:38:28 AM]


Long filenames - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-filenames.html[8/24/2017 10:38:28 AM]


DPI display settings - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

DPI display settings


The DPI setting of a display monitor is a measure of the number of dots that are visible in a single inch (Dots-per-Inch or
Pixels-per-inch).

DPI is not the same as resolution. (Resolution is the number of horizontal and vertical pixels. For example, 1024 x 768 pixels.)
An image with 100 x 100 pixel resolution would be 1 x 1 inch when printed at 100 DPI.

When a display DPI is chosen in Microsoft Windows, you are telling the system how the attached monitor will display images,
Windows will then rescale to take this into account.

For example changing from 96 DPI to 120 DPI, Windows will assume that you now have a display with closely packed (dense)
pixels that make everything 20% smaller, so to compensate will scale everything to be 25% larger.

The changes made by adjusting DPI are more subtle than changing screen resolution, but setting DPI correctly can be
important for preventing eye strain when using high pixel density displays.

The ideal* DPI for a display can be calculated using pythagoras as follows:

Given:
W = Width in Pixels
H = Height in Pixels
S = Diagonal Size in Inches (display size)

Then the DPI = √(W 2 + H2) / S


examples
An iPad with a 9.7" screen √(10242 + 768 2) / 9.7= 132 DPI
An IBM Thinkpad with a 15" screen √(19202 + 1200 2) / 15.4= 147 DPI

* In practice you should select DPI based on individuals eyesight/preference.


It is not advisable to set a DPI lower than 96 as the majority of Windows fonts are not hinted to display correctly at very small
sizes.

Windows 7/2008 DPI settings:


96 to 500 DPI
Control Panel | Display | Set Custom Text Size (DPI)
or
Control Panel | Personalisation | Adjust Font Size (DPI)

For custom sizes, tick: “ Use Windows XP style DPI Scaling” un-ticking this option will turn on full scaling of all
non-DPI aware applications, which can cause fonts to become blurry.

When Windows SETUP is run to install Windows, the DPI will be set according to the capabilities of the attached
monitor.
This will automatically set most high resolution monitors to 120 DPI.

Citrix and Terminal servers


Setting the DPI for individual users connected to a terminal server (or Citrix) can only be done in the registry, if the DPI is
changed in the Control Panel as above, then the change will apply to all users.

Registry settings for Per-User DPI setting (Windows 2003/2008):

Small 96 DPI
Medium 120 DPI
Large 144 DPI

https://ss64.com/nt/syntax-dpi.html[8/24/2017 10:38:37 AM]


DPI display settings - Windows CMD - SS64.com

Default 96 DPI (includes AppliedDPI value)

“There are three classes of people: those who see. Those who see when they are shown. Those who do not see” ~ Leonardo da Vinci

Related

Q2726399 - Cannot change the DPI setting through an RDP session.


REGEDIT - Import or export registry settings.
DPI ruler
DPI Calculator & list of common display sizes.
Detect your monitor DPI

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-dpi.html[8/24/2017 10:38:37 AM]


CMD syntax - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

CMD Shell
Notes on working with the Windows CMD shell.

Pausing or stopping a batch script


Execution of any batch script can be paused by pressing CTRL-S this also works for pausing a single command such as a DIR
listing. Pressing any key will resume the operation.

Execution of any batch script can be canceled by pressing CTRL-C

If one batch file CALLs another batch file CTRL-C will exit both batch scripts.
If CMD /c is used to call one batch file from another then CTRL-C will cause only one of the batch scripts to terminate. (see
also EXIT)

Copy and Paste / QuickEdit


In Windows 10 the standard Ctrl-X & Ctrl-C shortcuts are supported.

For earlier versions of Windows you can enable QuickEdit cut and paste at the Command Prompt as follows:

Activate the control menu at the top left of the current cmd window, go to Properties, Options tab and then tick
against QuickEdit Mode. Now you can select text with the mouse and hit Enter (or right click) to copy it to the
clipboard. Paste anywhere using Control+V (or Right Click) or via the menu.

ESC will cancel any selection and return to editing mode.


When copying between windows, you need one click to select the window and a second click to paste.

History of Previous Commands


Pressing the UP arrow will list previous commands entered at the command prompt.
Other DOSKEY function keys are loaded by default (F7, F8, F9)

Quote Characters in a command


If /C or /K is specified, then the remainder of the command line is interpreted as a command and the following
logic is used to process quote (") characters:

1. If all of the following conditions are met, then quote characters on the command line are preserved:

- No /S switch (Strip quotes)


- Exactly two quote characters
- No special characters between the two quote characters, where special is one of: & < >( ) @ ^ |
- There are one or more whitespace characters between the the two quote characters
- The string between the two quote characters is the name of an executable file.

2. Otherwise, old behavior is to see if the first character is a quote character and if so, strip the leading character
and remove the last quote character on the command line, preserving any text after the last quote character. To
negate this behaviour use a double set of quotes "" at the start and end of the command line.

CMD /c ""c:\work\my reports\profit ^& Loss.doc""

Command.com vs CMD.exe
All the commands on these pages assume you are running the 32 bit or 64 bit command line (cmd.exe)

https://ss64.com/nt/syntax-cmd.html[8/24/2017 10:38:46 AM]


CMD syntax - Windows CMD - SS64.com

The old 16 bit command processor command.com is supplied to provide backward compatibility for 16 bit DOS
applications. Command.com has very limited functionality compared to cmd.exe e.g. it will fail to set an
%errorlevel% after many commands.

If you name your batch scripts with the extension .CMD rather than .BAT then they will not run under
command.com even if copied to a Windows 95 machine.

The %COMSPEC% environment variable will show if you are running CMD.EXE or command.com

One key difference between .CMD and .BAT scripts (running under CMD.EXE) is that with extensions enabled,
commands like PATH/APPEND/PROMPT/SET/ASSOC will reset ERRORLEVEL to 0 if they succeed. In the old
style .BAT file, the ERRORLEVEL will not be changed unless there is a new error (source).

On 64 bit versions of Windows, the 32 bit CMD.exe can be found at %windir%\SysWoW64\cmd.exe To reduce
compatibility issues, the WOW64 subsystem isolates 32-bit binaries from 64-bit binaries by redirecting registry
calls and some file system calls.

Opening CMD from Windows Explorer


You can open a new CMD prompt by choosing START, Search box, cmd , OK

Registry Keys:
Allow UNC paths at command prompt
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]
"DisableUNCCheck"=dword:00000001

Run a command when CMD.exe starts


[HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor]
"AutoRun"=-

Activate Automatic Completion


[HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor]
"CompletionChar"=0x9

For Windows 7: Add an elevated 'Open CMD prompt here (Admin)' option to the
context menu for file system folders :
[HKEY_CLASSES_ROOT\Directory\shell\runas]
@="Open CMD prompt here (Admin)"
[HKEY_CLASSES_ROOT\Directory\shell\runas\command]
@="cmd.exe /k pushd %L"

For Windows 7: Add an elevated 'Open CMD prompt here (Admin)' option to the
My Computer context menu :
[HKEY_CLASSES_ROOT\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\shell\runas]
@="Open CMD prompt here (Admin)"
[HKEY_CLASSES_ROOT\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\shell\runas\command]
@="cmd.exe"

For Windows 10
See this article on TenForums

Run multiple instances of CMD.exe


At the command line or in a batch script CMD will start a new instance of CMD.exe which will appear in the same
window. The EXIT command will close the second CMD instance and return to the previous shell.

A method of calling one Batch script from another is to run a command like CMD /c C:\docs\myscript.cmd

The output of CMD can be redirected into a text file. When CMD /c is used, the EXIT command is not required.

The environment Variable %CMDCMDLINE% will expand into the original command line passed to CMD.EXE

The native version of CMD.exe is always in %windir%\system32, on 64 bit operating systems there is also a 32 bit
CMD.exe in %windir%\SysWOW64

https://ss64.com/nt/syntax-cmd.html[8/24/2017 10:38:46 AM]


CMD syntax - Windows CMD - SS64.com

Long Commands and long filenames


The maximum length of any command line (or variable) within CMD is 8191 characters.
For all versions of Windows, NTFS and FAT allows pathnames of up to 260 characters.

A workaround for the limited pathname length is to prefix \\?\


for example:
\\?\C:\TEMP\Long_Directory\Long_Filename.txt

“The method of the enterprising is to plan with audacity and execute with vigor” ~ John Christian Bovee

Related

CMD - Start a new CMD shell.


CMD Internal - Commands that are Internal to the CMD shell.
ConEmu-Maximus5 - a Windows console emulator with tabs

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-cmd.html[8/24/2017 10:38:46 AM]


Internal commands - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Internal commands
The Windows CMD shell CMD.exe contains a number of 'internal' commands, additional 'external' commands are also
supplied as separate executable files. External commands are generally stored in the C:\WINDOWS\System32 folder, this
folder is part of the system PATH .

This arrangement means that both internal and external commands are always available no matter what your current
directory happens to be.
ASSOC, BREAK, CALL ,CD/CHDIR, CLS, COLOR, COPY, DATE, DEL, DIR, DPATH, ECHO, ENDLOCAL, ERASE, EXIT, FOR, FTYPE,
GOTO, IF, KEYS, MD/MKDIR, MKLINK (vista and above), MOVE, PATH, PAUSE, POPD, PROMPT, PUSHD, REM, REN/RENAME,
RD/RMDIR, SET, SETLOCAL, SHIFT, START, TIME, TITLE, TYPE, VER, VERIFY, VOL

In the main A-Z list of CMD commands the internal commands are indicated with a •

When you are working from any other shell, such as PowerShell then none of the internal commands are available unless you
first open a CMD shell.

Passing arguments
Arguments can be passed to an internal command, just like an external command, e.g. COPY /Y
In some cases (when the command is being parsed by CMD.exe) the space before each argument can be omitted
e.g. COPY/Y this can save time when working at the command line, but for scripts and scheduled tasks it is better
to include the space.

for example from PowerShell:


PS C: > cmd /c date /t

will launch a CMD shell, run the DATE /T command and then exit back to PowerShell. Of course in many cases
this is not neccessary, (PowerShell has its own Date command) but can be useful if you need to run something
'the old way'.

It is possible for a system to have an internal command and an external command with the same name. If you have a
command called DATE.exe and want to run that in preference to the internal DATE command, use the full pathname to the
file e.g. C:\utils\date.exe even if your current directory is C:\utils\

“Tongues, like governments, have a natural tendency to degeneration; we have long preserved our constitution, let us make some
struggles for our language” - Samuel Johnson: Preface to the Dictionary

Related:

Which.cmd - Show full path to executable.


Escape Characters, Delimiters and Quotes

https://ss64.com/nt/syntax-internal.html[8/24/2017 10:38:56 AM]


Internal commands - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-internal.html[8/24/2017 10:38:56 AM]


Organising File Shares - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Organising File Shares


Some thoughts on how to arrange shared files. Here we discuss the what rather than the how - there is a separate page
covering the technical aspects of folder sharing.

Awareness
A key consideration in organising shared files is making sure that all the people in a team are aware exactly which
data of theirs is being shared with other teams.

Particularly in larger teams, the people asking for data to be shared may not be aware that the area includes
sensitive data.

Such problems can occur long after the sharing is initially setup, but it is not practical to do a review of access
permissions every time a new data file is saved.

Take an example of an HR Team and a Finance team, it might seem reasonable to share the HR folder with
Finance staff so they can get figures on annual workforce costs, but if one of the many HR subfolders has
information about redundancies that may eventually affect the Finance team then they certainly don’t want that to
be shared.

Listing what is available


When a list of folders is shared, you have a choice of hiding all folders for which the user does not have
permission. This was once a Novell Netware feature, but all recent versions of Windows now have Access-based
Enumeration turned ON by default. This has the advantage of simplifying day-to-day working, but has the
disadvantage that by hiding the folders of other teams, no one has any information on what might be available.

This can cause some ridiculous situations - a new hire needs to collate information about X, a shared folder full of
data about X already exists, but not knowing anything about that they start generating all the same documents
again from scratch.

If the list of fileserver shares is hidden from Windows Explorer, then something equivalent should be made
available elsewhere, perhaps on the company intranet.

Shared with everyone drives


One approach to sharing files is to have a file server area that is open and read/write to everyone. This is a
common approach in small organisations with little need for security.

With no clear ownership, file shares like this tend to become disorganised fairly quickly. Tidying this up typically
involves some kind of cleardown or reorg but this is never a popular approach and is likely to result in data loss at
some point.

Team only shares


This is very common in larger organisations, shared areas where the access is limited to only members of one
team or another. This access control means that when any need arises to share documents with people not in that
team they have to use email or some other means of sharing.

Split Folder Sharing


One approach to address these issues is to setup TWO sets of shared folders, and corresponding mapped drives.
For each Team there is one shared folder that’s only available within the team and a second that is shared with
other teams.

S: Shared – users will typically have access to multiple folders, here, including their own teams shared folder.

https://ss64.com/nt/syntax-shares.html[8/24/2017 10:39:05 AM]


Organising File Shares - Windows CMD - SS64.com

All folders are visible.

T: Team only – each user will have access to one and only one folder in this share corresponding to their own
Team. Other folders are hidden from view.

With this arrangement, users can save the files they want to share with other teams into their shared folder.

Because the Team Only and Shared areas are delivered to the end users via two separate drive mappings, any
movement of files between them (whether Moved or Copied) will retain the desired permissions inherited from the
parent folder.

You may be tempted to Map drive T: directly to each users Team folder, allowing work to be saved in T:\file.doc
rather than T:\teamName\file.doc but there are good reasons for keeping the name of the team folder visible:

If they try to email a link to a T: file or folder, to someone in a different team, they will quickly see that the
other team doesnt have access to that folder, so they will realise and use the S: shared folder instead.

In contrast, they are quite likely to be completely baffled as to whya link to T:\file.doc doesn't appear for
the other person, it's not intuitive.

It acts as a reminder of their teams Folder Name.

Login scripts are easy to setup, everyone gets exactly the same two drive mappings.

In Windows explorer and many other places, they can switch between their Team and Shared folders, by just
changing T: to S:

Some teams may store their work almost exclusively in the shared area, other teams may mostly work using their
Team-only folder. It places decisions about document sharing with individual users and means that shared access
is both visible and can be done on a per-file basis without having to involve the IT department at all.

For ease of use, the team folder names should be kept short - think 16 characters or less, that leaves ~ 240
characters for all the filenames within the group folder.

Access Permissions on the shared folders


Granting read-only access to everyone across all shared folders makes it simple and clear that shared items are
visible to everyone, but the ownership is still held by one team.

Alternatively you may want to allow multiple teams to work collaboratively with read/write access to the same
shared folder. The same logic would apply - shared items are read/write to selected other teams, but the
ownership is still held by one team.

It is likely to be worth setting up two AD groups for each team, one for the team members T: drive and one that
grants permissions to the S: drive for other people/teams. That gives complete flexibility about who can access the
Shared folder.

https://ss64.com/nt/syntax-shares.html[8/24/2017 10:39:05 AM]


Organising File Shares - Windows CMD - SS64.com

Large projects
One flaw in this arrangement is that while it works well for people in two teams sharing data, the structure may not
work so well for large project folders shared by many teams or sharing between a mish mash of people dotted
around the organisation.

For those cases - create a new shared folder for the project, just like an actual team using the T: and S: structure.

If you setup every file share the same consistent way, it simplifies management, some T: drives might never be
seen or used, but having them ensures you are covered for that case where a new hire is allocated to work on the
mega project and nothing else.

Home Folders
In addition to the above, every user typically has a home folder.

If a large proportion of users need to work with files that are kept private, set the Home directory to H: so it
appears at the top of the list. Conversely, mapping the Home directory to U: will put it at the bottom of the list.

For software packages like Microsoft Office, consider where the default save folder should be set to.
In some organisations the home folder may get very little use and so not require a drive mapping at all.

Every organisation is different


The arrangement described above may not work for every organisation, but hopefully it will give you ideas to
improve and simplify the management of your shared files. It will not eliminate the need for custom share
permissions but may help to reduce the number and complexity of changes that need to be managed.

In secure environments there is a tendency to say – "we can’t share document X with any other teams, therefore
we can’t share any files. The fallback option then becomes email, which is actually far more difficult to monitor and
control.

Even in the most complex environments, with many permissions to consider there is often an advantage to be
found in providing a file storage area that everyone understands will never be accidentally shared with any other
teams.

“The sky is filled with stars, invisible by day” ~ Henry Wadsworth Longfellow

See also

Groups - Full description of AD Local Domain groups, Global and Universal groups.
Built-in Groups - Built-In Users and Security Groups.
NoDrives - Hide mapped drives from Windows Explorer
MapDrive - Map a Drive letter to a network file share, non-persistent (VBScript)

  Copyright © SS64.com 1999-2017

https://ss64.com/nt/syntax-shares.html[8/24/2017 10:39:05 AM]


Organising File Shares - Windows CMD - SS64.com

Some rights reserved

https://ss64.com/nt/syntax-shares.html[8/24/2017 10:39:05 AM]


Windows command prompt Keyboard shortcuts - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Windows Keyboard shortcuts


Keyboard shortcuts for the Windows CMD shell and PowerShell.
ALT+ENTER
Switch to/from full screen mode.
[Tab] Autocomplete folder/file name.
↓ / ↑ Scroll through history of typed commands.
F1 F1 F1
Print characters of the previous command one by one.
F2 Z Repeat part of the previous command; up to character Z
F3 Repeat the previous command.
F4 Z Beginning from the current cursor position, delete up to character Z.
F5 Scroll through history of typed commands (↑).
F7 Show history of previous commands.
ALT+F7 Clear command history.
F8 Move backwards through the command history, but only display
commands matching the current text at the command prompt.
F9 Run a specific command from the command history.
ESC Clear command line.
INSERT Toggle Insert/Overwrite.
Ctrl Home Erase line to the left.
Ctrl End Erase line to the right.
Ctrl ← Move one word to the left (backward).
Ctrl → Move one word to the right (forward).
Erase character to the left.
[Home] Move to beginning of line.
[End] Move to end of line.
PgUp Scroll window up.
PgDn Scroll window Down.
Ctrl-C Abort current command/typing.
Left Alt + Left + PrtScn
Toggle High Visibility screen mode.
Ctrl-Z Signal end-of-file.

Group Policy GPO


F5 Mark all settings on the page as "green" (apply all).
F6 Mark current settings on the page as "green" (apply this setting).
F7 Mark current settings as "red" (don't apply this setting).
F8 Mark all settings on the page as "red" (don't apply).
F3 Display a list of available variables.
is the Shift key
is the Backspace key

"If NumLock is on, pressing a key on the numeric keypad while holding SHIFT overrides NumLock and instead generates an arrow key"
~ OldNewThing

Related:

Doskey /history - Show history of previous commands


Equivalent PowerShell cmdlet - Get-History (history)
Equivalent bash Keyboard shortcuts

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-keyboard.html[8/24/2017 10:39:14 AM]


NoDrives - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

NoDrives
Hide drive mappings in 'My Computer', Windows Explorer and the standard Open dialog box.

A: B: C: D: E: F: G: H: I: J: K: L: M: None

1 2 4 8 16 32 64 128 256 512 1024 2048 4096 0


N: O: P: Q: R: S: T: U: V: W: X: Y: Z: ALL

 
8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108863

Result: 0 Decimal

Copy the result into the registry to hide the drive letter(s)

User Key:
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]

System Key:
[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]

Value Name: NoDrives


Data Type: DWORD

After changing the registry, logoff or reboot so that it takes effect.

Drive mappings hidden with a nodrives registry setting are still available, just type the drive letter into the explorer address bar.

“The dream is the small hidden door in the deepest and most intimate sanctum of the soul, which opens to that primeval cosmic night that was soul long
before there was conscious ego and will be soul far beyond what a conscious ego could ever reach” ~ Carl Jung

Related:

REG - Registry: Read, Set, Export, Delete keys and values


REGEDIT - Import or export registry settings

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-nodrives.html[8/24/2017 10:39:23 AM]


Network Printing - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

An overview of Windows Network Printing


Print Drivers and the Print$ share
Every Print Server has a hidden file share (called Print$) that is used to deliver print Drivers to Windows clients.

When a PC connects to a Print Share the drivers on the server and client are compared, if the client is missing the
driver; or has an older version; then it will be automatically downloaded.

The achilles heel of this system is version control: consider that you have two similar printers on two different print
servers. One server has a driver version 26.232 the other has version 26.234, in theory the client will download the
latest driver and use it for both printers, in practice the results are less predictable - the worst case being a driver
download every time the user prints.

Whenever a new driver is installed on a print server, you can force all users who have a connection to that print
queue, to download the updated driver. This is done by changing the Print Share name on the server [Press Apply]
Then change back to the original Share Name [Press Apply again].
E.g.
Change the printer MyPrintShare to MyPrintShareX [Apply] then change back to MyPrintShare.

If you can arrange that each user connects to only one print server, management becomes much easier. If you
have multiple print servers, consider duplicating queues so that no user has to access more than one print server.

Printer Migration - bulk changes


The Microsoft Print Migrator has now been superseded by PRINTBRM which can backup and restore Print
Queues.

Client Printer connections (Print Map)


To update client printer connections, use qchange this will not only change the clients connection to a different Print
Queue but will also also preserve the user's default printer.

List all the print queues currently shared on a server with


net view \\MyServer >file_print_shares.txt

Printer Name vs Print Share Name


Every shared printer has both a Printer name and a Share name - these appear in different places:

Browsing Network Neighborhood (NetBios UNC Name) = ShareName


Add Printer Wizard (DNS) = PrinterName
Find Printer Wizard (DNS) = PrinterName

Active Directory and the Control Panel will display the PrinterName in most places.

A key difference between these two names is what happens when you rename them:

Changing the ShareName on the server, clients stay connected.

Changing the PrinterName on the server, clients will lose their connection. The control panel status will display
"Printer not found on server, unable to connect"

For example:

Create Printer called HP1 and share it as Share1

https://ss64.com/nt/syntax-printing.html[8/24/2017 10:39:32 AM]


Network Printing - Windows CMD - SS64.com

Connect a client to the printer

Now turn off the print Share on the server (set to Not Shared)

Create Printer called KYO2 and share it as Share1, you might expect the client to now connect to this
new queue, but it will still point to the old one (and will fail).

Now Rename HP1 to HPold and rename KYO2 (still shared as Share1) to HP1
The client will now connect to Share1 successfully.

Naming conventions
As you have probably figured by now; it pays to keep things simple and make the printer's SHARE Name and
PRINTER Name identical.

I recommend short printer names (8 characters or less) with no spaces, for example a simple naming convention
with 2 characters and a number (AA1, ZZ9...) will support 6,760 print queues. This is likely more than you will want
to host on a single Print Server.
\\London\RS7

Short Printer Names without spaces are portable and easy to script. If you choose to use long names with spaces,
expect that some third party software can have problems.

Over time Teams tend to move around different offices and buildings. Over time Printers tend to also move
around, either due to maintenance or to satisfy demand. This means that 'meaningful' printer names such as
HPLJ14 or FirstFloor21 or FinanceTeam tend to get out-of-date and become unhelpful.

Details such as the printer model and features (colour/duplex etc) should be placed in the Print Queue
DESCRIPTION field.

Filling in the LOCATION field will allow the Find Printer Wizard to display all the relevant printers for a team or site.

Attach a large physical label to the printer with it's share name, this will save on paper, user frustration and
helpdesk calls.

Deploying Printer Location with Active Directory


This feature helps users to find a printer by storing PC and Printer locations in Active Directory.
For example with 500 printers you might define 10 locations with 50 printers in each. Groups of computers are
then allocated to appropriate Locations, and Windows will pre-populate the Find Printer Wizard with the 50
nearest printers.

This is a good feature for large organisations following the trend to consolidate multiple print/file servers.

Default Printer
The default Printer connection is per user, and will travel with roaming profiles. it can be changed with Defptr,
WMIC or WSH.

If the default printer is a local printer, then roaming to a different PC without an identical local printer, will change
the default to the next available printer.

Print to File
In the Printers folder, click Add Printer.
Click My Computer, and then Next.
Click "Local printer attached to this computer"
(don’t tick automatically detect) >Next
Click Create a new Port. >Next
When prompted for a local port name, type a path and file name for the file.
Choose the Generic/Text print driver.

https://ss64.com/nt/syntax-printing.html[8/24/2017 10:39:32 AM]


Network Printing - Windows CMD - SS64.com

Local Printers
Any PC with a shared local printer will also setup a Print$ share - acting as a source of driver DLL's for other
machines. This presents a possible security risk that needs to be understood and managed. If the printer is never
accessed by other machines don’t share the printer.

Printer connections are normally per user, and roam with roaming profiles. Local shared printers and roaming
profiles are generally not a good mix. (They don’t cause problems but do confuse users who roam.)

It is possible to create printer connections per machine with rundll32 - these will not follow a roaming profile.

Windows XP Professional will support a maximum of 10 users per Share (This applies to both file and print
shares) for more than this you will need a server licence.

New features in Windows 7/Vista


Location-aware printing - mobile computers can automatically switch default printer according to the connected
network.

Avalon graphics provide improved color printing.

The NextGen print spool file uses human-readable XAML, an XML-based declarative programming language.
This opens up possibilities such as including multiple documents in a single print job.

LPR - Line Printers


The Line Printer protocol LPR is a useful method of printing to a character printer, typically used with monospaced
fonts for printing over pre-printed stationary such as cheques.
LPR print jobs are sent direct to the printer, this allows the application to manage/send printer control codes,
(page feed etc).
LPR can also be used to send print jobs to a UNIX Print Server.

The "Microsoft TCP/IP Printing service (UNIX)" provides a TCP/IP-based printing service using the Line Printer
protocol. This is not installed by default.

To create an LPR printer, Select Control Panel - Add Printer - My Computer - Add Port - LPR port.
At the prompt type the host name or IP Address of the printer (or remote Unix host).

Once installed, the LPR protocol will use the Service: LPDSVC

Printer Options
Priority: The priority sliding bar sets the default priority for documents printed.
A common approach is to create one printer for the majority of users with a default priority of 1
then create a separate 'high priority' printer that sends output to the same printing device but with a higher priority
setting.

Spool print documents so program finishes printing faster


(& Start printing immediately) - preferred option for most applications.

Print directly to the printer - this sends documents directly to the printer. This gives the fastest time-to-output but
you lose the ability to use the PC while the print job is in progress.

Print spooled documents first - if you disable this option, high priority jobs will interrupt lower priority jobs that are
already printing. (so the pages get mixed up)

Print Processor
The default Print Processor is WINPRINT.DLL, (this can be replaced for advanced DTP work)
This Print Processor supports several data formats:

https://ss64.com/nt/syntax-printing.html[8/24/2017 10:39:32 AM]


Network Printing - Windows CMD - SS64.com

Raw: [default] This datatype indicates that the job is in a ready-to-print format in the printing device’s native
language. (Good for PostScript printing).

Raw [FF Appended]: As RAW but appends a form-feed character to the end of the print job.

Text: This indicates a print job that consists of ANSI text.

PSCRIPT (PostScript support for Macintosh clients using non-PostScript printer)

EMF: A Windows application will partially rendered the job and the print driver then completes the rendering
process. EMF takes advantage of print server CPU resources, EMF files sizes are smaller than RAW which
reduces network congestion.
(Good formost PCL-based laser printers)

Printer Pools
A printer pool allows multiple physical printing devices to appear as a single'virtual' printer. When print jobs are
sent to a printer pool, Windows routes the job to the first availabledevice.

In a busy printing environment pooling will allow more efficent and faster printing but does not provide any failure
resilience e.g. Windows cannot redirect a job from a failed port, so when a printer is offline the printer pool will
continue to send jobs to that port.

To enable Printer pooling, go to Printer properties - Ports, check the 'Enable printer pooling' tickbox
Note: it's quite possible to have individual print queues in addition to the printer pool queue.

Printing requires the Spooler service to be running

Related:

NET PRINT - View and Delete print jobs


NET SHARE - Create file share
qchange.vbs - Connect to a different Printer Queue.
PRNCNFG - Configure or rename a printer.
PRNMNGR - Add, delete, list printers and printer connections.
RMTSHARE - List or edit a file share or print share
RUNDLL32 - Add/remove print connections
SHARE - List or edit a file share or print share
WMIC PRINTER - Set printing options through WMI
Print Management Snap-in - TechNet
Q234270 - Group Policies to Control Printers
Q888744 - Printer driver not updated on the client
Print Notification - this is set under Control Panel, Printers, File, Server Properties, Advanced
Equivalent bash command (Linux): printf - Format and print data

https://ss64.com/nt/syntax-printing.html[8/24/2017 10:39:32 AM]


Network Printing - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-printing.html[8/24/2017 10:39:32 AM]


Recovery Console - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Windows Recovery Console


When dealing with a Blue Screen of Death at boot - the first option should be to boot into Safe Mode (press F8 during
bootup). From safe mode you can run a system restore with %systemroot%\system32\restore\rstrui.exe

Some hardware failures are so severe they prevent booting into Safe Mode.

The recovery console allows an alternative boot option giving a limited command prompt - this can be used to disable services
or replace system files until you are able to boot into safe mode.
Recovery Console commands:
ATTRIB Change file attributes
BATCH Execute a batch file
CD Change directory
CHKDSK Check Disk
CLS Clear screen
COPY Copy files*
DEL Delete Files*
DIR Directory listing
DISABLE Disable Service
DISKPART Create or delete disk Partitions (like running setup)
ENABLE Enable Service
EXIT Quit the recovery console and reboot
EXPAND
FIXBOOT Write a new boot sector to the system partition
FIXMBR Repair the Master boot Record
FORMAT FORMAT drive /FS:NTFS
HELP
LISTSVC List all services and drivers
LOGON Logon as administrator (local)
MAP List local physical drive mappings
MAP arc List local physical drive mappings(ARC path)
MD Make Directory*
MORE
RD Remove Directory*
REN Rename file*
SYSTEMROOT Set the current directory to be %Systemroot%
* File operations are only possible on:
system directories, floppy drive(removable media), Root directories,
local install sources. You can copy FROM but not TO a floppy disk.

Installation:

The recovery console is not installed by default, from the install CD use the command: D:\i386\winnt32 /cmdcons
Then restart the machine.

“When a deep injury is done us, we never recover until we forgive” ~ Alan Paton

Related:

SC - Service Control
WinMSD - List running services
Q326215 - Recovery console Windows 2003
Q308402 - Recovery Console and Sysprep
Q812450 - Program Files Are Missing or Damaged
Q330184 - Invalid Boot.ini / Hal.dll error message
Q816579 - Perform an In-Place Upgrade of Windows Server 2003
List of Windows Services

https://ss64.com/nt/syntax-recovery.html[8/24/2017 10:39:41 AM]


Recovery Console - Windows CMD - SS64.com

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-recovery.html[8/24/2017 10:39:41 AM]


Windows 10 registry - user interface settings - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Windows 10 registry - user interface settings


Registry settings for user interface settings and options under Windows 10.
The older Windows 7 version of this page is here
Windows Registry Editor Version 5.00
; Win10.REG
; Usual disclaimers apply - don't edit the registry unless you know what you are doing and
; BACKUP THE REGISTRY FIRST

; Comment lines are prefixed with ; (REGEDIT will ignore them)


; so uncomment the parts you want to run.

; ============ Start menu ===========


;Start menu speed - the default is 400
; [HKEY_CURRENT_USER\Control Panel\Desktop]
; "MenuShowDelay"="50"
; ============ Taskbar ===========
;No Glomming (keep every icon on the taskbar separate)
; [HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer]
; "TaskbarGlomming"=dword:00000000
;Glomming enabled
; [HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer]
; "TaskbarGlomming"=dword:00000001
;Always combine Taskbar icons + hide labels
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "TaskbarGlomLevel"=dword:00000000
;Combine icons when taskbar is full (default)
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "TaskbarGlomLevel"=dword:00000001
;Never combine Taskbar icons
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "TaskbarGlomLevel"=dword:00000002
;TaskBar left/right grouping by age (oldest first) (default).
; [HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer]
"TaskbarGroupSize"=dword:00000000
;or group by size largest first
; "TaskbarGroupSize"=dword:00000001
;or group all with 2 or more, or 3 or more:
; "TaskbarGroupSize"=dword:00000002
; "TaskbarGroupSize"=dword:00000003
;or prevent grouping altogether
; "NoTaskGrouping"=dword:00000001
;Don't hide the log-off option from the Start Menu
;(setting to 0 does not prevent users from using other methods to log off.)
; [HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer]
; "StartMenuLogOff"=dword:00000001
;Don't hide the Themes tab in Control Panel Personalisation
; [HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer]
; "NoThemesTab"=dword:00000000
; Remember my Explorer views
; [HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer]
; "NoSaveSettings"=dword:00000000
; ============ System Tray ===========
; System Tray - Show all icons (The default for this can be set under HKLM)
; [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer]
; "EnableAutoTray"=dword:00000000
; or hide inactive icons
; [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer]
; "EnableAutoTray"=dword:00000001
;
; ============ Explorer / General ===========
;Don't tie new shortcuts to a specific PC
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]
; "LinkResolveIgnoreLinkInfo"=dword:00000001

https://ss64.com/nt/syntax-reghacks.html[8/24/2017 10:39:51 AM]


Windows 10 registry - user interface settings - Windows CMD - SS64.com

;Don't use Windows NTFS link tracking to resolve existing shortcuts.


; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]
; "NoResolveTrack"=dword:00000001
;Don't hide any local Drives
; "NoDrives"=dword:00000000
;Don't add "-Shortcut" text to the name of newly created shortcuts.
; [HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer]
; "link"=hex:00,00,00,00
;or Restore the default adding "-Shortcut" text to the name of newly created shortcuts.
; "link"=hex:1e,00,00,00
;Show all folders in Explorer including Recycle Bin, Desktop, Control Panel
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "NavPaneShowAllFolders”=dword:00000001
;or only show current folder path in Explorer
; "NavPaneShowAllFolders”=dword:00000000
;Remove the OneDrive icon
; [HKEY_CLASSES_ROOT\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}]
; "System.IsPinnedToNameSpaceTree"=dword:00000000
; [HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}]
; "System.IsPinnedToNameSpaceTree"=dword:00000000
;Add Right Click "Open PowerShell window here" Context Menu
; see this article on TenForums
; ============ Explorer\Advanced ===========
;Show hidden files and folders
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "Hidden"=dword:00000001
;or Don't show hidden files and folders:
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "Hidden"=dword:00000002
;Don't Hide file extensions
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "HideFileExt"=dword:00000000
;Don't hide recently opened Programs from the Start menu /Start Run
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "Start_TrackProgs"=dword:00000001
;Don't hide recently opened Documents from the Start menu /Start Run
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "Start_TrackDocs"=dword:00000001
;Don't add a Games shortcut to the start menu
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "Start_ShowMyGames"=dword:00000000
;Don't slow down search by including all public folders
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "Start_SearchFiles"=dword:00000001
;Don't change the upper/lower case of filenames
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "DontPrettyPath"=dword:00000000
;Don't show notifications/adverts (OneDrive & new feature alerts) in Windows Explorer
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
; "ShowSyncProviderNotifications"=dword:00000001
; ============ Personalization ===========

;Allow changing Windows Color


; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System]
; "NoDispAppearancePage"=dword:00000000
;Allow Color scheme changes
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System]
; "NoColorChoice"=dword:00000000
;Allow changing the font size
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System]
; "NoSizeChoice"=dword:00000000
;Change desktop background (any wallpaper will override this)
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System]
; "NoDispBackgroundPage"=dword:00000000
;Allow changing the Screen Saver
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System]
; "NoDispScrSavPage"=dword:00000000
;Allow changing the Display
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System]
; "NoDispCPL"=dword:00000000

https://ss64.com/nt/syntax-reghacks.html[8/24/2017 10:39:51 AM]


Windows 10 registry - user interface settings - Windows CMD - SS64.com

;Allow changing the Display Settings


; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System]
; "NoDispSettingsPage"=dword:00000000
;Allow changing the Screen Saver
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System]
; "NoDispScrSavPage"=dword:00000000
;Allow changing the wallpaper
;If a wallpaper value is set here (or via policy) it will override the users choice
;in the control panel (HKCU\Control Panel\Desktop) so delete the key to allow changes:
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System]
; "Wallpaper"=-

; ============ Control Panel / Add-Remove Programs ===========


;
;Don't hide any Control Panel applets see Q207750
; [HKEY_CURRENT_USER\Control Panel\don't load]
; "appwiz.cpl"=-
;These keys make sure you can install or uninstall programs:
; [HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Programs]
; "NoProgramsAndFeatures"=-
; "NoProgramsCPL"=-
; or disallow access:
; "NoProgramsAndFeatures"=dword:00000001
; ============ Windows Update [HKLM] ===========
; These affect all users [HKLM] and would typically be set via Group Policy
; [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update]
;Download and install
; "AUOptions"=dword:00000004
;Download but don't install
; "AUOptions"=dword:00000003
;Check but don't download
; "AUOptions"=dword:00000002
;Don't check
; "AUOptions"=dword:00000001
;Disable P2P uploads/downloads (Windows Update>Advanced>Choose how updates are delivered)
; [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Config]
; "DODownloadMode"=dword:00000000

; ============ Misc [HKLM] All users ===========


;
;Set the Screen Saver grace period (this only works if a valid screensaver is set)
;an alternative is adjusting the power / hibernate settings for the display.
; [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon]
; "ScreenSaverGracePeriod"="5"
;When opening files with an unknown extension, dont prompt to 'Look for an app in the Store'
; [HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Explorer]
; "NoUseStoreOpenWith"=dword:00000001
;this can also be set for all users
; [HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Explorer]ß
; "NoUseStoreOpenWith"=dword:00000001
;Display verbose messages during login (Group policy, profile loading etc)
; [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
; "verbosestatus"=dword:00000001
;Disable Cortana (Windows 10 Anniversary+)
; HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Windows Search
; "AllowCortana"=dword:00000000

Many of the On/Off registry values above can be toggled between TRUE ( 00000001 ) and FALSE ( 00000000 )

If any of the above settings could have been modified by Group Policy, use RSOP.msc (GUI utility) to see the policy settings
that have been applied to the current user, or run GPRESULT /z to see the full details of registry keys set.

If you are running DISM then equivalent settings for All Users can be found under
[HKEY_LOCAL_MACHINE\WIM_Default\Software\Microsoft\Windows\CurrentVersion\Explorer\

Windows 10 Themes can be found under:


%userprofile%\AppData\Local\Microsoft\Windows\Themes

https://ss64.com/nt/syntax-reghacks.html[8/24/2017 10:39:51 AM]


Windows 10 registry - user interface settings - Windows CMD - SS64.com

"It's not like I let people do things for me, so I guess you can call me a control freak, or you can call me passionate" ~ Courteney Cox

Related:

TenForums - Tutorials on Windows 10 personalization


AskVG - Windows 10 Hidden Secret Registry Tweaks

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-reghacks.html[8/24/2017 10:39:51 AM]


Windows Built-in Users and Default Groups - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Windows Built-in Users and Default Groups


Items in italics are implicit placeholders, these items don’t appear in "Active Directory Users and Computers" but are available
when applying permissions – membership is automatically calculated by the OS.

User/
Group Description
Session
A built-in group that exists only on domain controllers. By default, the group has no
members. By default, Account Operators have permission to create, modify, and
delete accounts for users, groups, and computers in all containers and organizational
Account Operators   units (OUs) of Active Directory except the Builtin container and the Domain
Controllers OU. Account Operators do not have permission to modify the
Administrators and Domain Admins groups, nor do they have permission to modify
the accounts for members of those groups.
A user account for the system administrator. This account is the first account created
  Administrator during operating system installation. The account cannot be deleted or locked out. It
is a member of the Administrators group and cannot be removed from that group.
A built-in group . After the initial installation of the operating system, the only member
of the group is the Administrator account. When a computer joins a domain, the
Domain Admins group is added to the Administrators group. When a server becomes
Administrators   a domain controller, the Enterprise Admins group also is added to the Administrators
group. The Administrators group has built-in capabilities that give its members full
control over the system. The group is the default owner of any object that is created
by a member of the group.
  Anonymous A user who has logged on anonymously.
Authenticated A group that includes all users whose identities were authenticated when they logged
 
Users on. Membership is controlled by the operating system.
A built-in group. By default, the group has no members. Backup Operators can back
Backup Operators   up and restore all files on a computer, regardless of the permissions that protect those
files. Backup Operators also can log on to the computer and shut it down.
A group that implicitly includes all users who have logged on through a batch queue
Batch   facility such as task scheduler jobs. Membership is controlled by the operating
system.
A global group that includes all computers that are running an enterprise certificate
Cert Publishers   authority. Cert Publishers are authorized to publish certificates for User objects in
Active Directory.
Cert Server Certificate Authority Administrators - authorized to administer certificates for User
 
Admins objects in Active Directory. (Domain Local)
Cert Requesters   Members can request certificates (Domain Local)
A placeholder in an inheritable ACE. When the ACE is inherited, the system replaces
Creator Group   this SID with the SID for the primary group of the object's current owner. The primary
group is used only by the POSIX subsystem.
Creator A placeholder in an inheritable access control entry (ACE). When the ACE is inherited,
 
Owner the system replaces this SID with the SID for the object's current owner.
A group that implicitly includes all users who are logged on to the system through a
Dialup  
dial-up connection. Membership is controlled by the operating system.
DnsAdmins
Members of this group have administrative access to the DNS Server service. This

https://ss64.com/nt/syntax-security_groups.html[8/24/2017 10:40:00 AM]


Windows Built-in Users and Default Groups - Windows CMD - SS64.com

(installed with  
group has no default members.
DNS)
DnsUpdateProxy
Members of this group are DNS clients that can perform dynamic updates on behalf of
(installed with  
other clients, such as DHCP servers. This group has no default members.
DNS)
A global group whose members are authorized to administer the domain. By default,
the Domain Admins group is a member of the Administrators group on all computers
that have joined a domain, including the domain controllers. Domain Admins is the
Domain Admins  
default owner of any object that is created in the domain's Active Directory by any
member of the group. If members of the group create other objects, such as files, the
default owner is the Administrators group.
A global group that includes all computers that have joined the domain, excluding
Domain Computers  
domain controllers.
A global group that includes all domain controllers in the domain. New domain
Domain Controllers  
controllers are added to this group automatically.
A global group that, by default, has only one member, the domain's built-in Guest
Domain Guests  
account.
A global group that, by default, includes all user accounts in a domain. When you
Domain Users  
create a user account in a domain, it is added to this group automatically.
A group that exists only in the root domain of an Active Directory forest of domains. It
is a universal group if the domain is in native mode, a global group if the domain is in
Enterprise Admins   mixed mode. The group is authorized to make forest-wide changes in Active
Directory, such as adding child domains. By default, the only member of the group is
the Administrator account for the forest root domain.
Enterprise A group that includes all domain controllers an Active Directory directory service
 
Controllers forest of domains. Membership is controlled by the operating system.
A group that includes all users, even guests. Membership is controlled by the
operating system.
Everyone   In Windows XP and later, the Anonymous Logon security group has been removed
from the Everyone security group: see Q278259 and the group policy Let Everyone
permissions apply to anonymous users
A global group that is authorized to create new Group Policy objects in Active
Directory. By default, the only member of the group is Administrator. The default
Group Policy
  owner of a new Group Policy object is usually the user who created it. If the user is a
Creators Owners
member of Administrators or Domain Admins, all objects that are created by the user
are owned by the group. Owners have full control of the objects they own.
A user account for people who do not have individual accounts. This user account
  Guest
does not require a password. By default, the Guest account is disabled.
A built-in group. By default, the only member is the Guest account. The Guests group
Guests   allows occasional or one-time users to log on with limited privileges to a computer's
built-in Guest account.
HelpServicesGroup   XP - Group for the Help and Support Center
A group that includes all users who have logged on interactively. Membership is
Interactive  
controlled by the operating system.
  KRBTGT A service account that is used by the Key Distribution Center (KDC) service.
Local
  A service account that is used by the operating system.
System
A group that implicitly includes all users who are logged on through a network
Network  
connection. Membership is controlled by the operating system.

https://ss64.com/nt/syntax-security_groups.html[8/24/2017 10:40:00 AM]


Windows Built-in Users and Default Groups - Windows CMD - SS64.com

Network Members of this group can make changes to TCP/IP settings and renew and release
Configuration   TCP/IP addresses on domain controllers in the domain. This group has no default
Operators members.
  Nobody No security principal.
Members of this group can monitor performance counters on domain controllers in the
Performance
  domain, locally and from remote clients without being a member of the Administrators
Monitor Users
or Performance Log Users groups.
Members of this group can manage performance counters, logs and alerts on domain
Performance Log
  controllers in the domain, locally and from remote clients without being a member of
Users
the Administrators group.
A built-in group. By default, the group has no members. This group does not exist on
domain controllers. Power Users can create local users and groups; modify and
Power Users   delete accounts that they have created; and remove users from the Power Users,
Users, and Guests groups. Power Users also can install most applications; create,
manage, and delete local printers; and create and delete file shares.
A backward compatibility group which allows read access on all users and groups in
Pre-Windows 2000
  the domain. By default, the special identity Everyone is a member of this group. Add
Compatible Access
users to this group only if they are running Windows NT 4.0 or earlier.
A placeholder in an ACE on a user, group, or computer object in Active Directory.
Principal Self Principal Self
When you grant permissions to Principal Self, you grant them to the security principal
or or
represented by the object. During an access check, the operating system replaces the
Self Self
SID for Principal Self with the SID for the security principal represented by the object.
A built-in group that exists only on domain controllers. By default, the only member is
Print Operators  
the Domain Users group. Print Operators can manage printers and document queues.
Servers in this group are permitted access to the remote access properties of users. A
domain local group . By default, this group has no members. Computers that are
RAS and IAS running the Routing and Remote Access service are added to the group
 
Servers automatically. Members of this group have access to certain properties of User
objects, such as Read Account Restrictions, Read Logon Information, and Read
Remote Access Information.
Remote Desktop
  XP - Members in this group are granted the right to logon remotely
Users
In NT 4 domains, this group was called Replicators and is used by the directory
Replicator   replication service. In 2K/XP the group is present but is not used. Do not add users to
this group.
A group that exists only in the root domain of an Active Directory forest of domains. It
is a universal group if the domain is in native mode , a global group if the domain is in
mixed mode . The group is authorized to make schema  changes in Active Directory.
Schema Admins  
By default, the only member of the group is the Administrator account for the forest
root domain. Because this group has significant power in the forest, add users with
caution.
A built-in group that exists only on domain controllers. By default, the group has no
members. Server Operators can log on to a server interactively; create and delete
Server Operators  
network shares; start and stop services; back up and restore files; format the hard
disk of the computer; and shut down the computer.
A group that includes all security principals that have logged on as a service.
Service  
Membership is controlled by the operating system.
Terminal Server A group that includes all users who have logged on to a Terminal Services server.
 
Users Membership is controlled by the operating system.
A built-in group. After the initial installation of the operating system, the only member
is the Authenticated Users group. When a computer joins a domain, the Domain

https://ss64.com/nt/syntax-security_groups.html[8/24/2017 10:40:00 AM]


Windows Built-in Users and Default Groups - Windows CMD - SS64.com

Users group is added to the Users group on the computer. Users can perform tasks
Users   such as running applications, using local and network printers, shutting down the
computer, and locking the computer. Users can install applications that only they are
allowed to use if the installation program of the application supports per-user
installation.

Default Admin Users and Groups:

Related:

Groups - Local Domain groups, Global and Universal groups.


Q271876 - Large Numbers of ACEs in ACLs Impair Directory Service Performance.
Q243330 - Well-known security identifiers (sids) in Windows operating systems.
Q277752 - Security Identifiers for built-in groups are unresolved when modifying group policy.

  Copyright © SS64.com 1999-2017

https://ss64.com/nt/syntax-security_groups.html[8/24/2017 10:40:00 AM]


Windows Built-in Users and Default Groups - Windows CMD - SS64.com

Some rights reserved

https://ss64.com/nt/syntax-security_groups.html[8/24/2017 10:40:00 AM]


Local Domain groups, Global groups and Universal groups. - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

AD Local Domain groups, Global groups and Universal groups.


This page describes the different types of Active Directory group, group scope and nesting permissions within and across WANS and
domains.

Types of Groups
Security groups are used to control access to resources.
Security groups can also be used as email distribution lists.

Distribution groups can be used only for email distribution lists, or simple administrative groupings.
Distribution groups cannot be used for access control because they are not "security enabled."

Group Scope
Assuming a Native-mode enterprise.

Universal groups
Provide a simple 'does everything' group suitable mainly for small networks. Typically, organizations using WANs should
use Universal groups only for relatively static groups in which memberships change rarely. Changes in membership will
impose global catalog replication throughout an entire enterprise.

Global groups
Provide domain-centric membership, place all user accounts into Global groups. Global groups can be nested within
other Global groups, this can be particularly useful when delegating OU administrative functionality.

It can be useful to give each Global group a name that is meaningful to the staff involved, i.e. matching the name of a
Team or a Project, particularly if the group is also to be used as an email distribution list.

Domain Local groups


Used for the direct assignment of access permissions on files, printer queues, and other such resources.

It can be useful to give each Domain Local group a name that is meaningful to the IT Operations team e.g. if a group
assigns rights to a shared folder on a specific server then the group name might include a prefix or suffix indicating the
server name.

Local groups
Stored on the local SAM (Local Computer) use for security settings that apply just to this one machine.
Local groups will work even if the network becomes unavailable, e.g. during a disaster recovery exercise.

Best Practice
Place users in Global groups, nest those inside Domain Local groups which in turn are used to apply permissions, as shown below.
This will also maximise performance in a multi-domain forest.

https://ss64.com/nt/syntax-groups.html[8/24/2017 10:40:10 AM]


Local Domain groups, Global groups and Universal groups. - Windows CMD - SS64.com

Group membership is evaluated when a user logs on to a domain. To be sure that any membership changes have taken effect, ask
the users to log-off. In contrast ACL changes or permissions applied directly to User accounts will take place immediately.
Granting permissions using a group from a different domain is only possible where a trust relationship exists between the domains.

Single Domains
In a single domain the scope of groups will have no effect on performance. Global groups can be used for everything but
you can nest groups and use Domain Local Groups to simplify management.

The fact that you cannot add a Domain Local group to a Global group is very useful to enforce the correct inheritance of
rights. A common mistake is adding group permissions the wrong way around. e.g. a resource group (such as one for
color printers) is added to an organisational group (such as the personnel dept) if at a later date you add someone else to
the colour printers group then they will also be able to read all the personnel files.

If all organisational groups are Global and resource groups are Domain Local then it is simply not possible to add group
permissions the wrong way around. Within a single domain individual User accounts can join either type of group, so in
the above example if one extra user needed access to the printers they could still be added directly to the Domain Local
colour printer group.

Separating People and Resources


It is tempting to use the same groups to hold users and also apply resource permissions but this seemingly simple setup

https://ss64.com/nt/syntax-groups.html[8/24/2017 10:40:10 AM]


Local Domain groups, Global groups and Universal groups. - Windows CMD - SS64.com

will involve more effort to maintain.

For example, you have a finance department with 25 accountants and clerks, they need access to the Crest system, they
also need editor permissions on the intranet and they need access to all the shared Account_Balances spreadsheets.

A common way to deal with this is to create 3 groups and add the 25 people to each:
25 25 25
[CREST] [INTRANET] [ACCOUNT_BALANCES]

The extra work starts when someone changes job or a new hire arrives, now someone has to remember and sort out
which groups each of these people needs to be added to or removed from.

The better way of managing this, is to still create the 3 groups as before but also create a group called Accounting, put the
25 people into the Accounting group, and make all the resources available to the group rather than to individuals.
25
[ACCOUNTING Group]
[res_CREST] [res_INTRANET] [res_ACCOUNT_BALANCES]

Now when a new hire arrives we add them to the accounting group and they will automatically get everything they need.
Similarly when someone changes job we remove them from the accounting group and add them to a different group
appropriate to their new role. Also note that this arrangement only requires 28 permissions to be set instead of 75.

Separating people and resources also makes it easy to temporarily remove access e.g. during maintenance downtime. In
the above example you could just remove the Accounting group from the res_Crest group. This is much easier than
having to either remove (and then later accurately replace) a bunch of individual user accounts, or having to edit the
actual permissions applied to files/printers/databases.

The two diagrams below both show 22 permissions being applied:

With a flat permission structure there are fewer groups to maintain.


With separate groups for users and resources, there are fewer permissions to manage (the arrows in the diagram above).

Nesting one Group within another with a different scope


Rules that govern when a group can be added to another group (same domain):

- Global groups can be nested within Domain Local groups, Universal groups and within other Global groups in the same
domain.

- Universal groups can be nested within Domain Local groups and within other Universal groups in any domain.

- A Domain Local group cannot be nested within a Global or a Universal group.

https://ss64.com/nt/syntax-groups.html[8/24/2017 10:40:10 AM]


Local Domain groups, Global groups and Universal groups. - Windows CMD - SS64.com

Rules that govern when a group can be added to another group (different domain):

- Domain Local groups can grant access to resources on the same domain. For example a Domain Local group named
Sales on the SS64.local domain can only grant access to resources on that domain, and not on SS64.com

- Domain Local groups can accept anything, except for Domain Local groups from another domain. Domain Local groups
accept user accounts from any domain.

- Global groups can grant access to anything, including files/folders in any domain.

- Global groups cannot be nested across domains. You cannot take a Global group from SS64.local , and nest it within
another Global group in SS64.com .

- A user or computer account from one domain cannot be nested within a Global group in another domain.

- Universal groups accept user/computer accounts from any domain. A Global group can also be nested within a Universal
group (from any domain).
A Universal group can be nested within another Universal group or Domain Local group in any domain.

Members - who can join a group:


User Computer
Local Domain
accounts Local Domain accounts Machine Domain
Group Users Users Global Universal
Location from Computer Computer from Local Local
Scope can can groups groups
another accounts accounts another groups groups
join? join?
domain? domain
Stored in
Machine local
Yes Yes   No No   No Yes Yes Yes
Local sam
database
Yes
Domain Stored in
No Yes Yes No Yes Yes No (same Yes Yes
Local AD
domain)
Yes
Stored in
Global No Yes No No Yes No No No (same No
AD
domain)
Stored in
Universal No Yes Yes No Yes Yes No No Yes Yes
AD

Resources that a group can grant access to:

https://ss64.com/nt/syntax-groups.html[8/24/2017 10:40:10 AM]


Local Domain groups, Global groups and Universal groups. - Windows CMD - SS64.com

File File
Can act as File/Printer Can be Can use to Permissions on
Group Permissions Permissions
Location distribution SHARE Mail assign Mailbox Active Directory
Scope (local Domain File
list? permissions enabled permissions objects
machine) Server
Yes
Stored in
Machine (same
local sam No Yes No No No No
Local machine
database
only)
Domain Stored in
Yes Yes Yes Yes Yes Yes Yes*
Local AD
Stored in
Global Yes Yes Yes* Yes* Yes Yes Yes
AD
Stored in
Universal Yes Yes Yes* Yes* Yes Yes Yes
AD

* Possible but not recommended by Microsoft.

Admin rights

To modify groups in AD, you must be a member of the Account Operators group, the Domain Admins group, or the Enterprise
Admins group, or you must have been delegated the appropriate authority.

“In the long history of humankind (and animal kind, too) those who learned to collaborate and improvise most effectively have prevailed” ~
Charles Darwin

Related

Built-in Groups - Built-In Users and Security Groups


NET localgroup / NET localgroup /domain / NET group /domain - Create new groups.
circular.ps1 - Script to find circular nested AD groups.
The Golden Rules of Permissions Administration (pt2) - NetworkAdminkb.com
ServerFault - Performance impact of AD Universal groups assignment
PowerShell script to remediate pre 2003 AD members that don't support LVR
Q231273 - Group Type and Scope Usage.
Q328889 - Users who are members of more than 1,015 groups may fail logon authentication
Q271876 - Large Numbers of ACEs in ACLs Impair Directory Service Performance (slow logon times.)
Q909264 - Naming conventions in Active Directory for computers, domains, sites, and OUs.
Q811965 - Domain Local Groups do not appear when you edit a group policy object.

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-groups.html[8/24/2017 10:40:10 AM]


Detect 64 vs 32 bit OS or Process - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Detecting 64 bit vs 32 bit


Before starting to look at this, its important to be clear about what you mean by "64 bit".
You can have a 64 bit CPU, a 64 bit operating system and a 64 bit process running.
It is equally possible to have 64 bit CPU, a 32 bit operating system installed and a 16 bit process running.

The table below shows a few of the combinations you need to account for:

  CPU Hardware Operating System Process


Windows 3.1 16 16 16
Windows 95/NT 32 32 32
Windows XP (16 bit compatibility) 32 32 16
Windows XP 32 32 32
Windows XP on new hardware 64 32 32
Windows 7+ on old hardware 32 32 32
Windows 7+ (32 bit compatibility) 64 64 32 (WOW)
Windows 7+ 64 64 64

Detect 64 bit processor hardware


In Vista and greater, you can use wmic os get osarchitecture , or in WMI Win32_ComputerSystem/OSArchitecture
sadly this is not supported in XP or 2003
There are a number of promising looking options in WMI and Systeminfo, but they all pertain to the OS not the
CPU.

Detect a 64 bit Operating System


:: Installed OS
Set _os_bitness=64
IF %PROCESSOR_ARCHITECTURE% == x86 (
  IF NOT DEFINED PROCESSOR_ARCHITEW6432 Set _os_bitness=32
  )
Echo Operating System is %_os_bitness% bit

Via David Wang’s blog post: Detect OS Bitness

Detect a 64 bit Process


On Windows 7, running C:\windows\SysWOW64\cmd.exe will launch a 32 bit instance of CMD.exe even if the OS is
64 bit. Applications that are compiled for a 32 bit processor will run in a similar way.

We can detect this by testing either the %ProgramFiles% or the %PROCESSOR_ARCHITECTURE% environment variables:

32bit CMD process:


C:\Windows\SysWOW64> set ProgramFiles
ProgramFiles=C:\Program Files (x86)

C:\Windows\SysWOW64> echo %PROCESSOR_ARCHITECTURE%


x86

64 bit CMD process:

https://ss64.com/nt/syntax-64bit.html[8/24/2017 10:40:19 AM]


Detect 64 vs 32 bit OS or Process - Windows CMD - SS64.com

C:\Windows\System32> set ProgramFiles


ProgramFiles=C:\Program Files

C:\Windows\System32> echo %PROCESSOR_ARCHITECTURE%


AMD64

Using this with a conditional IF to detect process bitness in a script:


If %PROCESSOR_ARCHITECTURE% == x86 (
Set _ps_bitness=32
) ELSE ( Set _ps_bitness=64)
Echo Process is %_ps_bitness% Bit

System Folders
64 bit versions of Windows have dynamic system folders C:\Windows\sys* to support both 64 and 32 bit programs.
PowerShell.exe, CMD.exe and many other programs are available as both 32 bit or 64 bit.

The dynamic sys folders will appear differently to a 32 bit session and a 64 bit session:

  32 bit folder 64 bit folder


32 bit session C:\Windows\system32\ C:\Windows\sysNative\
64 bit session C:\Windows\sysWOW64\ C:\Windows\system32\

By default a 32 bit session will launch 32bit executables from C:\Windows\System32\ but you can still choose to
launch 64 bit executables by specifying SysNative

By default a 64 bit session will launch 64bit executables also from C:\Windows\System32\ but you can still choose
to launch 32 bit executables by specifying sysWOW64.

The sysNative folder is not visible to 64 bit processes or programs and cannot been seen in Windows Explorer.

File location environment variables


%ProgramFiles% = 32 bit programs on 32 bit systems "C:\Program Files"
%ProgramFiles% = 64 bit programs on 64 bit systems "C:\Program Files"
%ProgramFiles(x86)% = 32 bit programs on 64 bit systems "C:\Program Files (x86)"

Run a 32 bit program


To run a 32 bit program or utility on a 64 bit OS, the 32 bit executable file must be called from
C:\Windows\SysWOW64\

if you run a 32 bit shell (such as C:\windows\syswow64\cmd.exe) and then try to launch a command, it will always
look for a 32 bit version of the command, even if you explicitly use a full path to system32, the 32 bit shell will
redirect to the 32 bit equivalent in syswow64 (if no 32 bit version of the command is found, then the new process will
fail to launch.)

Run a 64 bit program from a 32 bit process


To run a 64 bit program from a 32 bit process use the virtual folder C:\Windows\sysnative

In many cases this is not needed as most utilities (e.g. ping.exe) have both a 32 bit and 64 bit version, however a
few utilities (nbtstat, bcdedit) are only available as a 64-bit executable.

By default, running CMD from the start menu will launch a 64 bit process ( C:\Windows\System32\cmd.exe)

“It's not so much that we're afraid of change or so in love with the old ways, but it's that place in between that we fear... it's like being
between trapezes” ~ Marilyn Ferguson

https://ss64.com/nt/syntax-64bit.html[8/24/2017 10:40:19 AM]


Detect 64 vs 32 bit OS or Process - Windows CMD - SS64.com

Related:

Q556009 - How to check if a computer is running a 32 bit or 64 bit Operating System.

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-64bit.html[8/24/2017 10:40:19 AM]


Windows Key shortcuts - Windows CMD - SS64.com

(  SS64  ) CMD Syntax


Search

Windows Key Shortcuts  


For Windows 10

Description Windows Key combination


Open/Close the Start Menu Windows key
Open the Action center. Windows key + A
Open Cortana in listening mode Windows key + C
Fast-switch to/from the desktop - minimise all Windows key + D
Open File Explorer Windows key + E
Open Game bar (when a game is open) Windows key + G
Open Share Windows key + H

Open Settings Windows key + I


Open Connect Windows key + K
Switch accounts or lock the PC Windows key + L
Minimize all windows Windows key + M
Open the Run dialog box Windows key + R
Open Search Windows key + S
Open the Ease of Access center Windows key + U
Open the Quick Link menu Windows key + X
Snap app windows to the left Windows key + left arrow key
Snap app windows to the right Windows key + right arrow key
Maximize the app Windows key + up arrow key
Minimize the app Windows key + down arrow key
Open the app that is pinned to the taskbar in that number's position Windows key + a number
Open a quick look at the desktop Windows key + comma
Open Narrator Windows key + Enter
Minimize all but the active desktop window Windows key + Home
Capture a screenshot and save it to the Screenshots folder Windows key + PrtScn
Add a virtual desktop Windows key + Ctrl + D
Switch between virtual desktops Windows key + Ctrl + left or right arrow
Close the current virtual desktop Windows key + Ctrl + F4
Stretch the desktop window to the top and bottom of the screen Windows key + Shift + Up arrow
Open Task view Windows key + Tab
Zoom in Windows key +   +

https://ss64.com/nt/syntax-windows.html[8/24/2017 10:40:29 AM]


Windows Key shortcuts - Windows CMD - SS64.com

Zoom out Windows key +   -

“Madness is to think of too many things in succession too fast, or of one thing too exclusively” ~ Voltaire

Related

Windows key - Wikipedia, this includes older versions back to windows 95


Windows Start | Run commands
EXPLORER - Open Windows Explorer

  Copyright © SS64.com 1999-2017


Some rights reserved

https://ss64.com/nt/syntax-windows.html[8/24/2017 10:40:29 AM]

You might also like