Windows CMD Command Syntax
Windows CMD Command Syntax
com
Related:
( SS64 ) Search
About/contact - Last update: August 23rd
Copyright © SS64.com 1999-2017, some rights reserved.
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.
( SS64 ) CMD
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.
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.
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)
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.
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.
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
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
Related
MS Support Q no's
913086 »
“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)
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
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)
%~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.
%~s1 Change the meaning of f, n, s and x to reference the Short 8.3 name (if it exists.)
%~$PATH:1 Search the PATH environment variable and expand %1 to the fully qualified name of the first match
found.
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.
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.
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.
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
---hs----
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:
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%
“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:
Calculator calc
dcomcnfg
Component Services or
comexp.msc
CompMgmtLauncher.exe
Computer Management or
compmgmt.msc
hdwwiz
Device Manager or
devmgmt.msc
dfrgui
Disk Defragmenter
defrag
IP Configuration ipconfig
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
Services services.msc
sysdm.cpl SystemProperties
System Properties or
sysdm.cpl DisplaySYSDMCPL
control userpasswords2
User Accounts (Autologon)
C:\Windows\System32\rundll32.exe
User Profiles - Edit/Change type
sysdm.cpl,EditUserProfiles
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
System Administrator command line shortcuts to popular Microsoft Management Consoles (MMCs).
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
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
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
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
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
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.
* 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
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
Echo %_startmenu%
Related:
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.
FPS_BROWSER_APP_PROFILE_STRING
Internet Explorer
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.
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)
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
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
Unless stated otherwise, all the variables above are System variables
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.
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:
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
To prevent the > and < characters from causing redirection, escape with a caret: ^> or ^<
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: œ¾Ÿ?
C:\Windows\system32\cmd.exe /C /S /D "batch_command"
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:
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.
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
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.
Conditional Execution
Syntax
command1 || command2
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
“Conditional cooperation is like adulterated cement which does not bind” ~ Mohandas K. Gandhi
Related:
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
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:
Some rights reserved
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.
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.
: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.
“Cats are intended to teach us that not everything in nature has a function” ~ Garrison Keillor
Related:
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.
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:
Example:
@echo off
cls
setlocal DisableDelayedExpansion
set LF=^
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:
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)
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
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.
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
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
(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
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
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.
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.
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-
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)
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.
vs
IF EXIST data.xls (
Echo The file was found.
)
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
)
)
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.
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.
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
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%
@echo off
SETLOCAL EnableDelayedExpansion
Set "_var=first"
Set "_var=second" & Echo %_var% !_var!
There are some advantages - we can swap the value of two variables in one line:
Set "var1=%var2%" & set "var2=%var1%"
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
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.
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!"
"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]
[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!)
Another method for replacing a variable named with the content of another is CALL SET
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.
[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:
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.
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.
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
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. ^\ ^& ^| ^> ^< ^^
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 Percents
The % character has a special meaning for command line parameters and FOR parameters.
To treat a percent as a regular character, double it:
%%
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.
^^!
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:
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
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 .
Type SET without parameters to display all the current environment variables.
The SET command invoked with a string (and no equal sign) will display a wildcard list of all matching variables
Set a variable:
Example of storing a text string:
Set a variable that contains a redirection character, note the position of the quotes which are not saved:
SET "_dept=Sales & Marketing"
Avoid starting variable names with a number, this will avoid the variable being mis-interpreted as a parameter
%123_myvar% < > %1 23_myvar
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:
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.
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="
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 }
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.)
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.
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
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.
CALL SET
The CALL SET syntax allows a variable substring to be evaluated, the CALL page has more detail on this technique,
Setlocal EnableDelayedExpansion
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)
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.
Related:
A negative number will count backwards from the end of the string.
Examples
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 :~
You can use the :~ syntax and provide each of the parameters from other variables, for example if you have
%_donor%=2539850
%_digit%=4
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:
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
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%
SET _no_spaces=%_some_var: =%
Example: test for the existence of the string "London" in a variable containing text (that could be in any order)
"Aberdeen, London, Edinburgh "
If you have a parameter containing a valid 'folder' this can be compared with the PATH variable.
Example
%PATH% = C:\Windows\system32;C:\Windows;C:\utils\jdk\bin
batch parameter %1 = C:\utils\jdk\bin
If the batch parameter was supplied as %2 then this would be: ECHO %~dp$PATH:2
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.
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.
Random Numbers
The Windows CMD shell contains a dynamic variable called %RANDOM% that can be used to generate random numbers.
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%
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:
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
//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
“Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin” ~ John von Neumann
Related:
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
*.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
"[*][. ]*[.]$"
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 )
The commands COPY and REN accept two sets of wildcards, there are some subtle differences between how these are
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:
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.
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
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.
“The method of the enterprising is to plan with audacity and execute with vigor” ~ John Christian Bovee
Related
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.
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.
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
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
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
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 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 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
Related:
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%
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
If the line in bold is saved as a single line batch file DeQuote.cmd, then it can be called from other batch scripts:
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.
Related:
SetLocal - EnableDelayedExpansion
Long Filenames and NTFS - Valid characters in filenames
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:
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
“When the character of a man is not clear to you, look at his friends” ~ Japanese Proverb
Related
Ascii table
MAKECAB Create .CAB files
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.
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.
Related
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
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
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%"
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
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
“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
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
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
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
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 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.
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.)
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:
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)
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.
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
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:
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'::
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).
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
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.
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
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).
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.
When using very long path names, prefix the path with the characters \\?\ and use the Unicode versions of the C
Runtime functions.
/ \ : * ? " [ ] | = , . ; (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:
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)
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.
Small 96 DPI
Medium 120 DPI
Large 144 DPI
“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
CMD Shell
Notes on working with the Windows CMD shell.
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)
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.
1. If all of the following conditions are met, then quote characters on the command line are preserved:
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.
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)
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.
Registry Keys:
Allow UNC paths at command prompt
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]
"DisableUNCCheck"=dword:00000001
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
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
“The method of the enterprising is to plan with audacity and execute with vigor” ~ John Christian Bovee
Related
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.
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:
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.
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.
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.
S: Shared – users will typically have access to multiple folders, here, including their own teams shared folder.
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.
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.
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.
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.
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)
"If NumLock is on, pressing a key on the numeric keypad while holding SHIFT overrides NumLock and instead generates an arrow key"
~ OldNewThing
Related:
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
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]
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:
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.
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 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:
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.
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.
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.
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.
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.
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:
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.
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.
Related:
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
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\
"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:
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
(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.
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
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.
Related:
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.
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.
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.
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.
- 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.
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.
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
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
The table below shows a few of the combinations you need to account for:
We can detect this by testing either the %ProgramFiles% or the %PROCESSOR_ARCHITECTURE% environment variables:
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:
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.
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.)
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
Related:
“Madness is to think of too many things in succession too fast, or of one thing too exclusively” ~ Voltaire
Related