Treasure Of Tips

WIN XP,WIN 7,MOBILE SECRET CODES &TIPS, BLOGGING,PHOTOSHOP,&MANY MORE TIPS&TRICKS DAILY VISIT SITE FOR MORE TREASURE

New Posts

Search This Blog

Monday, January 30, 2012

Dos Syntax 11

To Know The Contents And Purpose Of This BLOG Go To ABOUT Page !

DOS COMMANDS SYNTAX 11, TREASURE--> DOWNLOAD
201). WINRM = Windows Remote Management...
(EXPLAIN - WINRM)
Windows Remote Management

Secure communication with local and remote computers using web services.

Syntax
winrm g[et] | s[et] | c[reate] | d[elete] | e[numerate] |
i[nvoke] | id[entify] | quickconfig | configSDDL | helpmsg

Retrieve instances of RESOURCE_URI:
winrm get RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] ...]

winrm get winrm/config
winrm get winrm/config/client
winrm get winrm/config/service

Modify settings in RESOURCE_URI:
winrm set RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] ...]
[@{KEY="VALUE"[;KEY="VALUE"]}]
[-file:VALUE]

Spawn an instance of RESOURCE_URI:
winrm create RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] ...]
[@{KEY="VALUE"[;KEY="VALUE"]}]
[-file:VALUE]

Control remote access to WinRM resources, launch a GUI to edit security settings.
winrm configsddl RESOURCE_URI

Enable this machine for remote management.
winrm quickconfig [-quiet] [-transport:VALUE]

This will start the WinRM service, set the service to auto start, create
a listener and enable an http firewall exception for WS-Management traffic

-q[uiet] Don't prompt for confirmation.

-transport:VALUE Perform quickconfig for either http or https. Default = http.

List instances of RESOURCE_URI:
winrm enumerate RESOURCE_URI [-ReturnType:Value] [-Shallow]
[-BasePropertiesOnly] [-SWITCH:VALUE [-SWITCH:VALUE] ...]

Remove an instance of RESOURCE_URI:
winrm delete RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] ...]

Execute method specified by ACTION on target object specified by RESOURCE_URI
winrm invoke ACTION RESOURCE_URI [-SWITCH:VALUE [-SWITCH:VALUE] ...]
[@{KEY="VALUE"[;KEY="VALUE"]}]
[-file:VALUE]

Display error message associate with the error code.
winrm helpmsg errorcode

Key

-a[uthentication]:VALUE
The authentication mechanism to use when communicating
with the remote machine.

-defaultCreds Allow implicit credentials when Negotiate is used.
Remote HTTPS operations for trusted machines.

-dialect:VALUE Dialect of the filter expression for enumeration or fragment.
Example: Use a WQL query
-dialect:http://schemas.microsoft.com/wbem/wsman/1/WQL
Example: Use XPATH for filtering with enumeration or fragment get/set.
-dialect:http://www.w3.org/TR/1999/REC-xpath-19991116

-encoding:VALUE The encoding type when talking to remote machine (see -remote).
Possible options are "utf-8" (the default) or "utf-16".

-f[ormat]:FORMAT The format of output. FORMAT can be "xml",
"pretty" (better formatted XML), or "text".

-r[emote]:VALUE Specify the identifier of a remote endpoint/system.
This may be a simple host name or a complete URL.

-skipCAcheck The certificate issuer need not be a trusted root authority.
Remote HTTPS operations for trusted machines.

-skipCNcheck The certificate common name (CN) of the server need not match
the hostname of the server. HTTPS operations for trusted machines.

-skipRevocationcheck Do not check the revocation status of the server certificate.
Remote HTTPS operations for trusted machines.

-SPNPort Append port number to the Service Principal Name (SPN) of the
remote server.
Service principal name is used when Negotiate or Kerberos authentication
mechanism is in use.

-timeout:MS Timeout in milliseconds. Limits duration of corresponding operation.
Default timeout can be configured by:
winrm set winrm/config @{MaxTimeoutms="XXXXXX"}
Where XXXXXX is an integer indicating milliseconds.

-file:VALUE

@{KEY="VALUE"[;KEY="VALUE"]}
Input from an XML file or via key/value pairs.
Applies to set, create, and invoke operations

-fragment:VALUE Specify a section inside the instance XML that is to be updated or
retrieved for the given operation.
Example: Get the status of the spooler service
winrm get wmicimv2/Win32_Service?name=spooler -fragment:Status/text()

-options:{KEY="VALUE"[;KEY="VALUE"]}

Key/value pairs for provider-specific options.

Example:
-options:{key1="value1";key2=$null}

WinRM is the Microsoft implementation of WS-Management Protocol, a standard Simple Object Access Protocol (SOAP)-based, firewall-friendly protocol that allows hardware and operating systems, from different vendors, to interoperate.

To improve security, WinRM 2.0 uses HTTP/HTTPS ports 5985/5986 by default.

If the computer name is passed using r: , then the default client port will be used (by default, 5985/5986).
If the computer name is passed as a URI, such as r:http://Mycomputer/wsman, then the IE default ports will be used (ports 80/443 by default).

Examples

Configure Windows Remote Management on the server (DemoServer2), run this from an elevated CMD (or powershell) prompt:
C:\> winrm quickconfig

On a client you can then open a remote shell connected to DemoServer2 with:
winrs -r:DemoServer2 cmd

Retrieve current configuration in XML format:
winrm get winrm/config -format:pretty

Retrieve spooler instance of Win32_Service class:
winrm get wmicimv2/Win32_Service?Name=spooler

Modify a configuration property of WinRM:
winrm set winrm/config @{MaxEnvelopeSizekb="100"}

Disable a listener on this machine:
winrm set winrm/config/Listener?Address=*+Transport=HTTPS @{Enabled="false"}

Create instance of HTTP Listener on IPv6 address:
winrm create winrm/config/Listener?Address=IP:3ffe:8311:ffff:f2c1::5e61+Transport=HTTP

Delete the HTTP listener on this machine for given IP address:
winrm delete winrm/config/Listener?Address=IP:192.168.2.1+Transport=HTTP

Call StartService method on Spooler service:
winrm invoke StartService wmicimv2/Win32_Service?Name=spooler

Call Create method of Win32_Process class with specified parameters:
winrm invoke Create wmicimv2/Win32_Process @{CommandLine="notepad.exe";CurrentDirectory="C:\"}

Display error message associated with the error code 0x5:

winrm helpmsg 0x5
Please Leave Your Comment

202). WINRS = Windows Remote Shell...
(EXPLAIN - WINRS)
Windows Remote Shell

Syntax
winrs [-/SWITCH[:VALUE]] COMMAND

Key
COMMAND Any string that can be executed as a command in the cmd.exe shell.

(All switches accept both short form or long form. For example both -r and
-remote are valid.)

-r[emote]:ENDPOINT The target endpoint using a NetBIOS name or the standard
connection URL: [TRANSPORT://]TARGET[:PORT].
If not specified -r:localhost is used.

-un[encrypted] Messages to the remote shell will not be encrypted. This is useful for
troubleshooting, or when the network traffic is already encrypted using
ipsec, or when physical security is enforced.
By default the messages are encrypted using Kerberos or NTLM keys.
This switch is ignored when HTTPS transport is selected.

-u[sername]:USERNAME Username. If -username is specified, -password must be as well.
If not specified Winrs will negotiate authentication or prompt.

-p[assword]:PASSWORD Password. If not specified winrs will prompt for it.

-d[irectory]:PATH The starting directory for remote shell.
If not specified the remote shell will start in %USERPROFILE%.

-env[ironment]:STRING=VALUE
A single environment variable to be set when shell starts.
This allows changing default environment for the shell.
Multiple occurrences of this switch may be used.

-noe[cho] Disable echo. This may be necessary to ensure that user's answers
to remote prompts are not displayed locally. By default echo is "on".

-nop[rofile] Do not load the user's profile. By default the server will attempt to load
the user profile. If the remote user is not a local administrator on the
target system then this option will be required.

-comp[ression] Turn on compression. Older installations on remote machines may
not support compression so it is off by default.

-[use]ssl Use an SSL connection when using a remote endpoint. Specifying this instead
of the transport "https:" will use the default WinRM default port.

-? Help

To terminate the remote command press Ctrl-C or Ctrl-Break, which will be sent to the remote shell. The second Ctrl-C will force termination of winrs.exe.
The URI alias to manage active shells is shell/cmd. The URI alias for WinRS configuration is winrm/config/winrs.

Examples

Configure Windows Remote Management on the server (DemoServer2), run this from an elevated CMD (or powershell) prompt:
C:\> winrm quickconfig

On a client you can then open a remote shell connected to DemoServer2 with:
winrs -r:DemoServer2 cmd

Batch file to quickly open a remote cmd shell:
[rshell.cmd]
@echo off
winrs -r:%1 cmd

Run a dir command on a remote machine:
C:\> winrs -r:DemoServer3 dir

Run an install package on a remote server:
C:\> winrs -r:Server25 msiexec.exe /i c:\install.msi /quiet

Run a powershell script on the remote box:

C:\> winrs /r:DemoServer2 powershell.exe -nologo -noprofile -command d:\test\test.ps1

Note that you can't open a full interactive remote powershell console, but as remoting functionality is built-in to Powershell 2.0 there isn't any need.

Connecting to the remote server 'myserver'

winrs -r:https://myserver.com command
winrs -r:myserver.com -usessl command
winrs -r:myserver command
winrs -r:http://127.0.0.1 command
winrs -r:http://169.51.2.101:80 -unencrypted command
winrs -r:https://[::FFFF:129.144.52.38] command
winrs -r:http://[1080:0:0:0:8:800:200C:417A]:80 command
winrs -r:https://myserver.com -t:600 -u:administrator -p:$%fgh7 ipconfig
winrs -r:myserver -env:PATH=^%PATH^%;c:\tools -env:TEMP=d:\temp config.cmd
winrs -r:myserver netdom join myserver /domain:testdomain /userd:johns /passwordd:$%fgh789
Please Leave Your Comment

203).WMIC = WMI Commands...
(EXPLAIN - WMIC.exe)
Windows Management Instrumentation Command.
Read a huge range of information about local or remote computers. Also provides a way to make configuration changes to multiple remote machines.

Syntax
Retrieve information about :
WMIC [global_switches] [/locale:ms_409] [options] [format]

Interactive mode:
WMIC

Aliases:
ALIAS - Access local system aliases [CALL]

BASEBOARD - Base board management (motherboard or system board)
BIOS - BIOS management (Basic input/output services)
BOOTCONFIG - Boot configuration

CDROM - CD-ROM
COMPUTERSYSTEM - Computer system [CALL/SET]
CPU - CPU
CSPRODUCT - Computer system product information from SMBIOS.

DATAFILE - DataFiles [CALL]
DCOMAPP - DCOM Applications.
DESKTOP - User's Desktop
DESKTOPMONITOR - Desktop Monitor
DEVICEMEMORYADDRESS - Device memory addresses
DISKDRIVE - Physical disk drive
DISKQUOTA - Disk space usage for NTFS volumes.[SET]
DMACHANNEL - Direct memory access (DMA) channel

ENVIRONMENT - System environment settings [SET]
FSDIR - Filesystem directory entry [CALL]

GROUP - Group account [CALL]

IDECONTROLLER - IDE Controller
IRQ - Interrupt request line

JOB - Jobs scheduled using the schedule service.[CALL]

LOADORDER - System services that define execution dependencies.
LOGICALDISK - Local storage devices [CALL/SET]
LOGON - LOGON Sessions.

MEMCACHE - Cache memory
MEMLOGICAL - System memory, layout and availability
MEMPHYSICAL - Physical memory management

NETCLIENT - Network Client management.
NETLOGIN - Network login information for a particular user.
NETPROTOCOL - Protocols (and their network characteristics).
NETUSE - Active network connection.
NIC - Network Interface Controller (NIC)
NICCONFIG - Network adapter. [CALL]
NTDOMAIN - NT Domain. [SET]
NTEVENT - NT Event Log.
NTEVENTLOG - NT eventlog file [CALL/SET]

ONBOARDDEVICE - Common adapter devices built into the motherboard.
OS - Operating System/s [CALL/SET]

PAGEFILE - Virtual memory file swapping
PAGEFILESET - Page file settings [SET]
PARTITION - Partitioned areas of a physical disk.
PORT - I/O ports
PORTCONNECTOR - Physical connection ports
PRINTER - Printer device [CALL/SET]
PRINTERCONFIG - Printer device configuration
PRINTJOB - Print job [CALL]
PROCESS - Processes [CALL]*
PRODUCT - Windows Installer [CALL]

QFE - Quick Fix Engineering (patches)
QUOTASETTING - Setting information for disk quotas on a volume. [SET]

REGISTRY - Computer system registry [SET]

SCSICONTROLLER - SCSI Controller [CALL]
SERVER - Server information
SERVICE - Service application [CALL]
SHARE - Shared resourcees [CALL]
SOFTWAREELEMENT - Elements of a software product*
SOFTWAREFEATURE - Subsets of SoftwareElement. [CALL]*
SOUNDDEV - Sound Devices
STARTUP - Commands that run automatically when users logon
SYSACCOUNT - System account
SYSDRIVER - System driver for a base service. [CALL]
SYSTEMENCLOSURE - Physical system enclosure
SYSTEMSLOT - Physical connection points including ports,
slots and peripherals, and proprietary connections points.

TAPEDRIVE - Tape drives
TEMPERATURE - Temperature sensor (electronic thermometer).
TIMEZONE - Time zone data

UPS - Uninterruptible power supply (UPS)
USERACCOUNT - User accounts [CALL/SET]

VOLTAGE - Voltage sensor (electronic voltmeter) data
VOLUME - Local storage volume [CALL/SET]
VOLUMEQUOTASETTING - Associates the disk quota setting with a specific disk volume. [SET]

WMISET - WMI service operational parameters [SET]

New aliases in Windows 2003:
MEMORYCHIP - Memory chip information.
RDACCOUNT - Remote Desktop connection permission [CALL]
RDNIC - Remote Desktop connection on a specific network adapter [CALL/SET]
RDPERMISSIONS - Permissions to a specific Remote Desktop connection [CALL]
RDTOGGLE - Turn Remote Desktop listener on or off remotely[CALL]
RECOVEROS - Blue Screen Information [SET]
SHADOWCOPY - Shadow copy management [CALL]
SHADOWSTORAGE - Shadow copy storage areas [CALL/SET]
VOLUMEUSERQUOTA - Per user storage volume quotas [SET]

Options

By default an alias will return a standard LIST of information, you can also choose to GET one or more specific properties.

Configuration changes can be made, where indicated above with: [CALL or SET ]

The CREATE and DELETE options allow you to change the WMI schema itself.

alias
alias LIST [BRIEF | FULL | INSTANCE | STATUS |SYSTEM | WRITEABLE]
[/TRANSLATE:BasicXml|NoComma ]
[/EVERY:no_secs] [/FORMAT:format]
alias GET [property list]
[/VALUE ] [/ALL ] [/TRANSLATE:BasicXml|NoComma ]
[/EVERY:no_secs] [/FORMAT:format]
alias CALL method_name [parameters]
alias SET [assignments]
alias CREATE
alias DELETE
alias ASSOC [/RESULTCLASS:classname] [/RESULTROLE:rolename][/ASSOCCLASS:assocclass]

For more help
WMIC /locale:ms_409 /alias /?
WMIC /locale:ms_409 /alias option /?
e.g.
WMIC /locale:ms_409 /BIOS /CALL /?
WMIC /locale:ms_409 /MEMLOGICAL /SET /?

The order of the /FORMAT and /TRANSLATE switches is significant: if /TRANSLATE follows /FORMAT, the output is formatted first and then translated.

All the options above can be extended with a WHERE clause, best shown by the examples below:

Format:

Format defines the layout of the information, XML output is automatically formatted using a default style sheet, while other formats (HTML, Table, MOF, Raw XML etc) can be specified using /FORMAT: stylesheet_name

Stylesheets supplied with WMIC:

csv.xsl, hform.xsl, htable-sortby.xsl, htable.xsl
texttable.xsl, textvaluelist.xsl, xml.xsl

All output files are unicode text (convert to ASCII with TYPE) Tab Separated Values (.tsv) can be opened in excel

The PROCESS alias can be used to start a new installation process, if doing this across the network, place the installer files on a share with permissions EVERYONE : Read Only. This is because network credentials will be dropped when jumping from one remote machine to another (unless you have kerberos configured).

Examples

WMIC /locale:ms_409 OS

WMIC OS LIST BRIEF

WMIC OS GET csname, locale, bootdevice

WMIC OS GET osarchitecture /value

WMIC /locale:ms_409 NTEVENT where LogFile='system'

WMIC NTEVENT where "LogFile='system' and Type>'0'"

WMIC SERVICE where (state=”running”) GET caption, name, state > services.tsv

WMIC SERVICE where caption='TELNET' CALL STARTSERVICE

WMIC PRINTER LIST STATUS

WMIC PRINTER where PortName="LPT1:" GET PortName, Name, ShareName

WMIC /INTERACTIVE:ON PRINTER where PortName="LPT1:" DELETE

WMIC PROCESS where name='evil.exe' delete

WMIC /output:"%computername%.txt" MEMORYCHIP where "memorytype=17" get Capacity

WMIC /node:@workstns.txt /failfast:on PROCESS call create "\\server\share\installer.cmd"

Interactive mode:
C:>START "Windows Management" WMIC
wmic:root\cli>/locale:ms_409
wmic:root\cli>OS get csname
wmic:root\cli>quit

Notes

WMIC is available on XP Professional and Windows 2003 or later versions of Windows.

The availability of WMI information does vary across different versions of Windows
e.g. ODBC, SNMP, Windows Installer.

To run WMIC requires administrator rights.

In Windows 2000, around 4,000 properties can be monitored, and around 40 can be configured.
In Windows XP around 6,000 properties can be monitored, and around 140 can be configured.

Windows 2003 offers a few improvements and bug fixes: the global option /locale:ms_409 is not required (it defaults to English US.)

When you type WMIC for the first time in Windows 2003 all the aliases are compiled. The second, and subsequent times you run WMIC, it will start immediately. Under XP WMIC is slower to initialise, therefore to run several WMI queries it can be quicker to use interactive mode.

* WMI information for installed software packages (PACKAGE and SOFTWAREFEATURE) is often incomplete and inconsistent for a variety of historical reasons. A more reliable method is to retrieve a list of installed programs directly from the Add/Remove list in the registry, with a WSH script like this from Torgeir Bakken.
Please Leave Your Comment

204). WUAUCLT = Windows Update...
(EXPLAIN - WUAUCLT)
Windows Update Agent, download new Windows Update files.

Syntax
wuauclt Options

Options:

/a or /ResetAuthorization Initiate an asynchronous background search for applicable updates.
If Automatic Updates are disabled, this has no effect.

/r or /ReportNow Send all queued reporting events to the server asynchronously.

/DetectNow Initiate detection right away, Query the WSUS server immediately
to see if any new updates are needed.

WSUS uses a cookie on client computers to store computer group membership when client-side targeting is used. By default this cookie expires an hour after WSUS creates it. If you are using client-side targeting and change group membership, use /ResetAuthorization /detectnow to expire the cookie, initiate detection, and have WSUS update computer group membership.

Examples:

C:\> wuauclt /a /DetectNow

C:\> wuauclt /r /DetectNow
Please Leave Your Comment

205). XCACLS = Change file and folder permissions...
(EXPLAIN - XCACLS.exe)
Display or modify Access Control Lists (ACLs) for files and folders.

Syntax
XCACLS filename [options]

XCACLS filename

Key
If no options are specified XCACLS will display the ACLs for the file(s)

options can be any combination of:

/T Traverse all subfolders and change all matching files found.

/E Edit ACL instead of replacing it.

/x Edit ACL instead of replacing it; affect only ACEs that this user already owns*

/R user Revoke all access rights from the given user.

/D user Deny specified user access, this will over-ride
all other permissions the user has.

/C Continue on access denied errors.
/Y Replace user's rights without verify

/P user:permision[;FolderSpec]
Replace user's rights. see /G option below

/G user:permision[;FolderSpec]
Grant specified user access rights, permision can be:
r Read
c Change (write)
f Full control
p Change Permissions (Special access)
o Take Ownership (Special access)
x EXecute (Special access)
e REad (Special access)
w Write (Special access)
d Delete (Special access)
t Used only by FolderSpec. see below

* Option only valid in Windows 2003

FolderSpec is a permission applied to a folder. If FolderSpec is not specified then permission will apply to both files and folders.
This allows you to set different permissions that will apply (through inheritance) when new files are added to the folder.

FolderSpec = ;T@ where @ is one of the rights above, when this is specified new files will inherit FolderSpec instead of permission. At least one folder access right must follow the T For example ;TF will apply full control (but ;FT is not valid)

Wildcards can be used to specify more that one file in a command. You can specify more than one user in a command. You can combine access rights.

Although taking ownership is listed as an option it does not work, use SUBINACL for this.

Inheritance Errors

"Permissions incorrectly ordered" - the quickest way to resolve or avoid these errors is to use the newer iCACLS command instead of XCACLS.

Inherited folder permissions are displayed as:

OI - Object inherit - This folder and files. (no inheritance to subfolders)
CI - Container inherit - This folder and subfolders.
IO - Inherit only - The ACE does not apply to the current file/directory

These can be combined as folllows:
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
(OI) (IO) Files only.

So BUILTIN\Administrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F' (Fullcontrol)
similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)

When xcacls is applied to the current folder only there is no inheritance and so no output.

Versions:
NTFS standards have changed with different versions of Windows and XCACLS has been updated to suit, early versions of Xcacls may give unpredictable results against an NTFS v5 partition.

xcacls.vbs is described in Q825751 and can be downloaded here - xcacls.vbs is an unsupported utility that addresses a limitation with the original xcacls.exe, specifically the inability to append permissions to a folder whose child objects have the inheritance flag set. The .vbs version does not suppport unc paths and is very slow to update multiple ACLs.

Examples:

:: Allow guests the right to read and execute in MyFolder
XCACLS MyFolder /E /G guests:rx

:: Allow guests the Full Control permission in MyFolder and all subfolders
XCACLS MyFolder /T /E /G guests:f

:: Grant guests only read access to all files in and below MyFolder,
:: new folders created will be Read Access only, new files will not inherit any rights.
XCACLS MyFolder /T /P guests:R;Tr

:: Grant guests only execute access to all files in and below MyFolder
XCACLS MyFolder /T /P guests:x
Please Leave Your Comment

206). XCOPY = Copy files and folders...
(EXPLAIN - XCOPY )
Copy files and/or directory trees to another folder. XCOPY is similar to the COPY command except that it has additional switches to specify both the source and destination in detail.

NOTE: Xcopy is now deprecated under Vista and Windows 2008 - use Robocopy instead

XCOPY is particularly useful when copying files from CDROM to a hard drive, as it will automatically remove the read-only attribute.

Syntax
XCOPY source [destination] [options]

Key
source : Pathname for the file(s) to be copied.

destination : Pathname for the new file(s).

[options] can be any combination of the following:

Source Options

/A Copy files with the archive attribute set (default=Y)

/M Copy files with the archive attribute set and
turn off the archive attribute, use this option
when making regular Backups (default=Y)

/H Copy hidden and system files and folders (default=N)

/D:mm-dd-yyyy
Copy files changed on or after the specified date.
If no date is given, copy only files whose
source date/time is newer than the destination time.

/U Copy only files that already exist in destination.

/S Copy folders and subfolders

/E Copy folders and subfolders, including Empty folders.
May be used to modify /T.

/EXCLUDE:file1[+file2][+file3]...

(Windows 2000 only) The files can each contain one
or more full or partial pathnames to be excluded.
When any of these match any part of the absolute path
of a SOURCE file, then that file will be excluded.
For example, specifying a string like \obj\ or .obj will exclude
all files underneath the directory obj or all files with the
.obj extension respectively.

Copy Options

/W Prompt you to press a key before starting to copy.
/P Prompt before creating each file.

/Y (Windows 2000 only) Suppress prompt to confirm overwriting a file.
may be preset in the COPYCMD env variable.
/-Y (Windows 2000 only) Prompt to confirm overwriting a file.

/V Verify that the new files were written correctly.
/C Continue copying even if an error occurs.

/I If in doubt always assume the destination is a folder
e.g. when the destination does not exist.

/Z Copy files in restartable mode. If the copy is interrupted part
way through, it will restart if possible. (use on slow networks)

/Q Do not display file names while copying.
/F Display full source and destination file names while copying.
/L List only - Display files that would be copied.

Destination Options

/R Overwrite read-only files.

/T Create folder structure, but do not copy files. Do not
include empty folders or subfolders.
/T /E will include empty folders and subfolders.

/K Copy attributes. XCOPY will otherwise reset read-only attributes.

/N If at all possible, use only a short filename (8.3) when creating
a destination file. This may be nececcary when copying between disks
that are formatted differently e.g NTFS and VFAT, or when archiving
data to an ISO9660 CDROM.

/O (Windows 2000 only) copy file Ownership and ACL information.

/X Copy file audit settings (implies /O).

XCOPY will accept UNC pathnames

Examples:

To copy a file:

XCOPY C:\utils\MyFile D:\Backup\CopyFile

To copy a folder:

XCOPY C:\utils D:\Backup\utils /i

To copy a folder including all subfolders.

XCOPY C:\utils\* D:\Backup\utils /s /i

The /i defines the destination as a folder.

Notes

In many cases the functionality of XCOPY is superseded by ROBOCOPY.

To force the overwriting of destination files under both NT4 and Windows2000 use the COPYCMD environment variable:
SET COPYCMD=/Y
This will turn off the prompt in Win2000 and will be ignored by NT4 (which overwrites by default).

When comparing Dates/Times the granularity (the finest increment of the timestamp) is 2 seconds for a FAT volume and 0.1 microsecond for an NTFS volume.

The WinXP version of XCOPY will accept wildcards for the source e.g. *.txt
It is also more forgiving with trailing backslashes
Please Leave Your Comment

207).:: = Comment / Remark...
(EXPLAIN - REM)
In a batch file REM at the start of a line signifies a comment or REMARK
alternatively adding :: at the start of a line has a similar effect

For example:

@ECHO OFF
::
:: First comment
::
REM Second comment
REM
::
Although you can use rem without a comment to add vertical spacing to a batch file, you can also use completely blank lines. The blank lines are ignored when processing the batch program.

The double-colon is not documented as a comment command, it is a special case of a CALL label that acts like a comment. The pro's and cons of each method are listed below.

Bugs
There are problems using a :: comment within an IF or FOR code bracket
e.g.
@echo off
FOR /L %%i IN (1,1,10) Do (
Echo before comment
:: Some comment
Echo after comment
)

The above will return the error :: was unexpected at this time.

In Windows 2000 and XP a comment like
::%~
or
REM %~ will be interpreted giving the error:
The following usage of the path operator in batch-parameter substitution is invalid: %~

In Windows NT 4 the REM command would incorrectly reset the %errorlevel% to 0

The bottom line on this is that you must test your comments to be sure they will be ignored as you expect.

Registry Comments

Within a registry file comments can be preceded by "; "
e.g.
;
; Turn the NUMLOCK on at login
;
[HKEY_CURRENT_USER\Control Panel\Keyboard]
"InitialKeyboardIndicators"="2"

FTP Comments

There is no valid comment character for FTP but you can cheat by escaping to the shell and running REM
e.g.

C:\WORK>type ftpscript
!REM This is a remark
bye

C:\WORK>ftp -s:ftpscript
ftp> !REM This is a remark
ftp> bye

C:\WORK>

#Now stand in the place where you work, Now face West
Think about the place where you live, Wonder why you haven't before# - REM 'Stand'
Please Leave Your Comment

Dos Syntax 10

To Know The Contents And Purpose Of This BLOG Go To ABOUT Page !

DOS COMMANDS SYNTAX 10, TREASURE--> DOWNLOAD
181). TASKKILL = Remove a running process from memory...
(EXPLAIN - TASKLIST)
End one or more processes (by process id or image name).

Syntax
TASKKILL [/S system [/U username [/P [password]]]]
{ [/FI filter] [/PID processid | /IM imagename] } [/F] [/T]

Options
/S system The remote system to connect to.

/U [domain\]user The user context under which
the command should execute.

/P [password] The password. Prompts for input if omitted.

/F Forcefully terminate the process(es).

/FI filter Display a set of tasks that match a
given criteria specified by the filter.

/PID process id The PID of the process to be terminated.

/IM image name The image name of the process to be terminated.
Wildcard '*' can be used to specify all image names.

/T Tree kill: terminates the specified process
and any child processes which were started by it.

Filters Apply one of the Filters below:

Imagename eq, ne String
PID eq, ne, gt, lt, ge, le Positive integer.
Session eq, ne, gt, lt, ge, le Any valid session number.
Status eq, ne RUNNING | NOT RESPONDING
CPUTime eq, ne, gt, lt, ge, le Time hh:mm:ss
MemUsage eq, ne, gt, lt, ge, le Any valid integer.
Username eq, ne User name ([Domain\]User).
Services eq, ne String The service name
Windowtitle eq, ne String
Modules eq, ne String The DLL name

Examples:

Examples:
TASKKILL /S system /F /IM notepad.exe /T
TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
TASKKILL /F /IM notepad.exe /IM mspaint.exe
TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"
TASKKILL /F /FI "USERNAME eq NT AUTHORITY\SYSTEM" /IM notepad.exe
TASKKILL /S system /U domain\username /FI "USERNAME ne NT*" /IM *
TASKKILL /S system /U username /P password /FI "IMAGENAME eq note*"
Please Leave Your Comment

182). TIME = Display or set the system time...
(EXPLAIN - TIME)
Display or set the system time.

Syntax
TIME [new_time]

TIME

TIME /T

key
new_time : The time as HH:MM

TIME with no parameters will display the current time and prompt
for a new value. Pressing ENTER will keep the same time.

/T : Just display the time, formatted according to the current Regional settings.

Time Formatting

In Control Panel, Regional settings a Time Appearance can be set. This can be used to change the separator, and the number of characters used to display hours and minutes.

To display the time including Seconds:

ECHO.| TIME will display the time, including seconds and hundredths of a second

The time separator and the Country Code are user settings in the registry:

The time separator can be read using REG as follows

@echo off
FOR /F "TOKENS=3" %%D IN ('REG QUERY ^"HKEY_CURRENT_USER\Control Panel\International^" /v sTime ^| find ^"REG_SZ^"') DO (
SET _time_sep=%%D)
echo %_time_sep%

To read the Country Code replace sTime in the above with iCountry.

The time formats for different country codes are as follows:

Country or language CountryCode Date format Time format

United States 001 01/03/1994 5:35:00.00p

Czechoslovakia 042 03.01.1994 17:35:00
France 033 03.01.1994 17:35:00
Germany 049 03.01.1994 17:35:00
Latin America 003 03/01/1994 5:35:00.00p
International English 061 03/01/1994 17:35:00.00
Portugal 351 03-01-1994 17:35:00
Finland 358 3.1.1994 17.35.00
Switzerland 041 03.01.94 17 35.00
Norway 047 03.01.94 17:35:00
Belgium 032 03/01/94 17:35:00
Brazil 055 03/01/94 17:35:00
Italy 039 03/01/94 17.35.00
United Kingdom 044 03/01/94 17:35:00.00
Denmark 045 03-01-94 17.35.00
Netherlands 031 03-01-94 17:35:00
Spain 034 3/01/94 17:35:00
Hungary 036 1994.01.03 17:35:00
Canadian-French 002 1994-01-03 17:35:00
Poland 048 1994-01-03 17:35:00
Sweden 046 1994-01-03 17.35.00

If Command Extensions are disabled TIME will not support the /T switch
Please Leave Your Comment

183). TIMEOUT = Delay processing of a batch file...
(EXPLAIN - TIMEOUT.exe)
Delay execution of a batch file.

Syntax
TIMEOUT delay

Key
delay :Delay in seconds (between -1 and 100000) to wait before continuing.
The value -1 causes the computer to wait indefinitely for a keystroke
(like the PAUSE command)

Timeout will pause command execution for a number of seconds, after which it continues without requiring a user keystroke. If the user does press a key at any point, execution will resume immediately.
Timeout.exe seems to consume less processor time time than Sleep.exe
Please Leave Your Comment

184). TITLE = Set the window title for a CMD.EXE session...
(EXPLAIN - TITLE )
Change the title displayed above the CMD window.

Syntax
TITLE [string]

Key
string : The title for the command prompt window.


The default title is %comspec% however, since the title can also be defined in a program shortcut, the title is usually set to "Command Prompt"

To change the title for the duration of a command use:

TITLE This is the initial title text
CMD /c MyBatchFile.cmd
...

If MyBatchFile.cmd contains a different TITLE command it will revert when the second command session ends.

The START command, used to start a program in a separate window also has an option to specify a title for the new Window.
Please Leave Your Comment

185). TLIST = Task list with full path...
(EXPLAIN - TLIST & Windows 2000 support tools)
Task List.

Show the command, command line, working directory, memory usage and DLLs for each running task. This command is no longer supplied with recent versions of the Windows resource kit, having been replaced by TASKLIST, however if you can find a copy Tlist does have the advantage of showing the full path of the process.

Syntax
TLIST
TLIST -t
TLIST pid
TLIST -t pid
TLIST pattern
TLIST -t pattern

Key
-t : Show Task dependencies in Tree form

pid : List module information for this task
if no PID is given - all Tasks are listed

pattern : A complete task name or expression pattern (e.g. CMD.*)
if a pattern is given it will match against
task names or window titles.

Example:

The following batch file will show the full path of all running programs.

@ECHO off
FOR /f "tokens=1" %%G in ('tlist') DO (call :s_item %%G)
GOTO :eof

:s_item
tlist %1 | find "CmdLine"
Please Leave Your Comment

186). TOUCH = Change file timestamps...
(EXPLAIN - TOUCH)
Change file timestamps

Syntax
TOUCH [option]... files ...

Key
/t year month day hour minute second

This is a POSIX utility.

Use the optional argument /t to specify a date other than the current time.
( four-digit years, two-digit months, days, hours, minutes, seconds)

Example

To set the date to 7:30 am 1st October 2015

TOUCH /t 2015 10 01 07 30 00 MyFile.txt
Please Leave Your Comment

187). TRACERT = Trace route to a remote host...
(EXPLAIN - TRACER)
Trace Route - Find the IP address of any remote host. TRACERT is useful for troubleshooting large networks where several paths can be taken to arrive at the same point, or where many intermediate systems (routers or bridges) are involved.

Syntax
TRACERT [options] target_name

Key
target_name The HTTP or UNC name of the host

Options:
-d Do not resolve addresses to hostnames.
(avoids performing a DNS lookup)

-h max_hops Maximum number of hops to search for target.(default=30)

-j host-list Trace route along given host-list.
up to 9 hosts in dotted decimal notation, separated by spaces.

-w timeout Wait timeout milliseconds for each reply.

The functionality of TRACERT is the same under all versions of windows but the output is cosmetically improved under XP.

Tracert uses the IP TTL field and ICMP error messages to determine the route from one host to another through a network.

Care must be taken with tracert as it shows the optimal route, not necessarily the actual route. To be accurate, it is possible to ping from a UNIX machine back to the PC using the -R option to record the route taken - but only if the particular network devices support it.

This diagnostic tool determines the path taken to a destination by sending ICMP Echo Request messages with varying Time to Live (TTL) values to the destination.

TTL (Time to Live) calculation
TTL is effectively a count of the (maximum) number of links to the destination host. Each router along the path decrements the TTL in an IP packet by at least 1 before forwarding it.

When the TTL on a packet reaches 0, the router is expected to return an ICMP Time Exceeded message to the source computer.

Tracert determines the path by sending the first Echo Request message with a TTL of 1 and incrementing the TTL by 1 on each subsequent transmission until either the target host responds or the maximum number of hops is reached.

This process relys on intermediate routers to return ICMP Time Exceeded messages. However, some routers do not return Time Exceeded messages for packets with expired TTL values and are invisible to the tracert command. In this case, a row of asterisks (*) is displayed for that hop.

Firewalls
Many firewalls will block ICMP traffic by default. If an attacker is able to forge ICMP redirect packets, he or she can alter the routing tables on the host and possibly subvert the security of the host by causing traffic to flow via a path you didn't intend.

Examples

TRACERT www.doubleclick.net

TRACERT 123.45.67.89

TRACERT local_server
Please Leave Your Comment

189). TSSHUTDN = Remotely shut down or reboot a terminal server...
(EXPLAIN - TsShutDn)
Remotely shut down or reboot a terminal server. If the computer supports software control of AC power this command may be used to power off the server.

Syntax
TSSHUTDN [WaitTime] [/server:ServerName] [/reboot] [/powerdown]
[/delay:LogOffDelay] [/v]

Key
WaitTime An amount of time (in seconds) to wait after notifying users before logging off
all users from their sessions. Default = 60 seconds.

/server The terminal server to shut down.
If unspecified, the current terminal server is shut down.

/reboot Reboot the terminal server after user sessions are ended.

/powerdown Turn off the terminal server if the computer supports software control of AC power.

/delay The amount of time to wait after logging off users from their sessions,
before ending all processes and shutting down the terminal server.
Default = 30 seconds.

/v Display verbose information about the actions being performed.

/? Display help.

You must have administrative privileges run tsshutdn.

Using Start Menu | ShutDown is not recommended for shutting down a terminal server as that method does not notify users before ending their sessions.

All connected sessions are notified. Sessions that have applications with open files will prompt the user to save the files. After initiating the logoff command, tsshutdn waits a specified interval, before ending all processes.

Tsshutdn does not reboot the terminal server unless the /reboot option is specified.

Examples

End all client sessions 60 seconds after notification, and then 30 seconds after all the users are logged off, shutdown the current terminal server:

TSSHUTDN /v

End all client sessions 5 minutes after notification, and then 1 minute after all the users are logged off, shutdown and restart the terminal server:

TSSHUTDN 300 /reboot /delay:60 /v

On the terminal server named "Server64", end all client sessions 2 minutes after notification, and then 20 seconds after all the users are logged off, shutdown and restart the terminal server:

TSSHUTDN 120 /server:server64 /delay:20 /v
Please Leave Your Comment

190). TYPE = Display the contents of a text file...
(EXPLAIN - TYPE)
Display the contents of one or more text files, convert Unicode to ANSI.

Syntax
TYPE [drive:]pathname(s)

If more than one file is specified the filenames are included in the output.
If a wildcard is used the filenames are not displayed.

Output can be redirected into a new file:

TYPE file.txt > Newfile.txt

Output can be appended to an existing file:

TYPE file.txt >> ExistingFile.txt

To do the same with user console input :

TYPE CON > Newfile.txt

This will require typing a CTRL-Z to indicate the end of file.

When using redirection to SORT a file the TYPE command is used implicitly
For example:

SORT < MyFile.txt Create an empty (zero byte) file: TYPE nul >filename.log

If you TYPE a Unicode text file, the output will be Ascii (Windows1252). This behaviour is more a limitation of the CMD shell than a designed feature, any extended characters will be discarded. To work with Unicode files use PowerShell.
eg:
TYPE UnicodeFile.txt > Ascii.txt
Please Leave Your Comment

191). TypePerf = Write performance data to a log file...
(EXPLAIN - TypePerf.exe)
Write performance data to the command window or to a log file.To stop Typeperf, press CTRL+C.

Syntax
typeperf counter [counter ...] [options]

typeperf -cf filename [options]

typeperf -q [object] [options]

typeperf -qx [object] [options]

Key
counter The Performance counters to monitor.
-f {CSV|TSV|BIN|SQL} Output file format. Default is CSV.
-cf filename File containing performance counters to monitor, one per line.
-si [[hh:]mm:]ss Time between samples. Default is 1 second.
-o filename Path of output file or SQL database.
Default is STDOUT.
-q [object] List installed counters (no instances).
To list counters for one object,
include the object name, such as Processor.
-qx [object] List installed counters with instances.
To list counters for one object,
include the object name, such as Processor.
-sc samples Number of samples to collect. Default is
to sample until CTRL+C.
-config filename Settings file containing command options.
-s computer_name Server to monitor if no server is specified in the counter path.
-y Answer yes to all questions without prompting.
-? Display context sensitive help.

Counter is the full name of a performance counter in the format:"\\Computer\Object(Instance)\Counter"
e.g. "\\Server1\Processor(0)\% User Time".

Examples

Display % Processor time until interrupted:

C:\> typeperf "\Processor(_Total)\% Processor Time"

Gather 600 samples of % Processor time on the local computer (this will take 10 minutes):

C:\> typeperf "\processor(_Total)\% Processor Time" -O C:\SS64demo1.csv -SC 600

Gather samples of all the counters listed in counters.txt :

C:\> typeperf -cf counters.txt -si 5 -sc 50 -o C:\SS64demo2.csv
Please Leave Your Comment

192). USRSTAT = List domain usernames and last login...
(EXPLAIN - USRSTAT- )
Please Leave Your Comment

193). VER = Display version information...
(EXPLAIN - VER)
Display the current operating system version.

Syntax

VER

Use ver to find specific operating systems like this:

@Echo off
Setlocal
:: Get windows Version numbers
For /f "tokens=2 delims=[]" %%G in ('ver') Do (set _version=%%G)

For /f "tokens=2,3,4 delims=. " %%G in ('echo %_version%') Do (set _major=%%G& set _minor=%%H& set _build=%%I)

Echo Major version: %_major% Minor Version: %_minor%.%_build%

if "%_major%"=="5" goto sub5
if "%_major%"=="6" goto sub6

Echo unsupported version
goto:eof

:sub5
::Winxp or 2003
if "%_minor%"=="2" goto sub_2003
Echo Windows XP [%PROCESSOR_ARCHITECTURE%]
goto:eof

:sub_2003
Echo Windows 2003 or XP 64 bit [%PROCESSOR_ARCHITECTURE%]
goto:eof

:sub6
if "%_minor%"=="1" goto sub7
Echo Windows Vista or Windows 2008 [%PROCESSOR_ARCHITECTURE%]
goto:eof

:sub7
Echo Windows 7 or Windows 2008 R2 [%PROCESSOR_ARCHITECTURE%]
goto:eof

Service Pack Version

This Batch script will give the Service Pack level.
Works for NT, Win2K or WinXP
Please Leave Your Comment

194). VERIFY = Verify that files have been saved...
(EXPLAIN - VERIFY)
To check that files are saved to disk correctly; the system can re-read the disk when saving and verify (compare) with the data in memory.

Syntax
VERIFY [ON | OFF]

By default the CMD shell has verify OFF
Windows Explorer will always copy with verify ON

Copying files can be up to twice as fast with verify OFF.

VERIFY without a parameter will display the current setting.

"VERIFY dummy_text" will set %ERRORLEVEL% to 1
Please Leave Your Comment

195). VOL = Display a disk label...
EXPLAIN - VOL)
Display the volume label of a disk.

Syntax
VOL [drive:]

If the drive exists, VOL will display it's disk label and serial number and will return an %ERRORLEVEL% of 0.

If the drive does not exist VOL will return an %ERRORLEVEL% of 1.

If the drive is a CD/DVD drive with no disk loaded then VOL will return "The device is not ready" and will return an %ERRORLEVEL% of 1.
Please Leave Your Comment

196). WHERE = Locate and display files in a directory tree...
(EXPLAIN - WHERE = Windows 2003)
Locate and display files in a directory tree.

The WHERE command is roughly equivalent to the UNIX 'which' command. By default, the search is done in the current directory and in the PATH.

Syntax
WHERE [/r Dir] [/q] [/f] [/t] Pattern ...

key
/r A recursive search, starting with the specified Dir directory.

/q Don't display the files but return either an exit code of 0 for success
or 1 for failure.

/f Display the output file name in quotation marks.

/t Display the size, time stamp, and date stamp of the file.

/e Report the executable type.

pattern The name of a folder, file, or set of files to be found.
you can use wildcard characters ( ? * ) and UNC paths.

As an alternative to this command you can use this 90-character batch file:

@for %%e in (%PATHEXT%) do @for %%i in (%1%%e) do @if NOT "%%~$PATH:i"=="" echo %%~$PATH:i

(from the OldNewthing blog)

Examples

Find all files named 'Zappa' in drive C: (including subdirectories)
WHERE /r c:\ Zappa

Find all files named 'Zappa' on the remote computer 'Server1' searching its subdirectories, and reporting the executable type for executable files

WHERE /r \\Server1\Share1 /e Zappa.*
Please Leave Your Comment

197). WHOAMI = Output the current UserName and domain...
(EXPLAIN - WHOAMI.exe)
Displays the username and domain for the currently logged in user.

The whoami output is the same as the 2 environment variables %USERDOMAIN% and %USERNAME%.

So the same output can usually be achieved with

ECHO %USERDOMAIN%\%USERNAME%

One exception to this is when using RUNAS /env , e.g. if my username is Simon:

c:>RunAs /env /user:JDoe cmd.exe
c:>ECHO %USERDOMAIN%\%USERNAME%
ss64\Simon

c:>whoami
ss64\JDoe

WHOAMI /all - shows all permissions and group memberships.
Please Leave Your Comment

198). WINDIFF = Compare the contents of two files or sets of files...
EXPLAIN - WinDiff (Windows SDK)
Compare the contents of two files or sets of files with a graphical interface.

Syntax
windiff [path1] [path2]

Key
path Individual files to compare
or a directory of files to compare

If either path is not specified it will default to the current directory (or a matching file in the current directory)

If nothing is specified, the GUI will appear - select files to compare with the menus.

White background = parts common to both files.
Red background = parts that belong to the file listed on the left .
Yellow background = parts that belong to the file listed on the right .

Registry files (exported with regedit) can also be compared. Also see the help file Windiff.hlp.
Please Leave Your Comment

199). WINMSD = Windows system diagnostics...
(EXPLAIN - WINMSD.exe)
Microsoft Windows diagnostics
Reports: Memory use, Services, Devices, IRQ's Ports, Environment variables,
Network (rights, transport, stats), Hardware including Display adapter.

Syntax
WINMSD [\\computername] options

Options:
/a All details
/s Summary details only
/f Send output to a file in the current directory
/p Send output to a printer

WINMSD with no switches will open the GUI with details of the computer you are logged into.

When a remote computername is specified then less info will be reported
e.g. Diskspace and Memory won't be listed

Hot keys within the GUI:

SHIFT - F2 copies the current tab to the clipboard,
F2 copies a summary of the current tab to the clipboard

Winmsd in Windows 2000 will actually run Msinfo32 -
mmc.exe /s "C:\Program Files\Common Files\Microsoft Shared\MSInfo\MSInfo32.msc"

It is advisable to have the SERVER service running, if not - winmsd will show a warning dialogue.

Spooling output to file - if you have the resource kit WINMSDP allows more control over this.
Please Leave Your Comment

200). WINMSDP = Windows system diagnostics II...
(EXPLAIN - WINMSDP.exe)
Windows NT diagnostics II
Reports: Memory use, Services, Devices, IRQ's Ports, Environment variables,
Network (rights, transport, stats), Hardware including Display adapter.

Syntax
WINMSDP option

Key (only one option can be used)

/a : ALL prints everything

/e : environment
/d : drives
/i : interrupt resources
/m : memory
/n : network
/o : OS version
/p : port resources
/r : drivers
/s : services
/u : DMA resources
/w : hardware
/y : memory resources

The output is very similar to WINMSD if a little more detailed.

The output will appear in a text file called msdrpt.TXT
Please Leave Your Comment

Dos Syntax 9

To Know The Contents And Purpose Of This BLOG Go To ABOUT Page !

DOS COMMANDS SYNTAX 9, TREASURE--> DOWNLOAD
161). SET = Display, set, or remove environment variables...
(EXPLAIN - 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
string : A text string to assign to the variable.
expression: : Arithmetic Sum

Also see SetX, VarSearch and VarSubstring for more advanced variable manipulation.

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

The number one problem people run into with SET is having extra spaces around either the variable name or the string, SET is not forgiving of extra spaces like many other scripting languages.

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

To display current variables:

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

Type SET with a variable name to display that variable SET _department
or use ECHO: ECHO [%_department%]

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

Display variables that begin with 'P': SET p
Display variables that begin with an underscore SET _

Examples

Storing a text string:

C:\>SET _dept=Sales and Marketing
C:\>set _
_dept=Sales and Marketing

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

C:\>set xx=fish
C:\>set msg=%xx% chips
C:\>set msg
msg=fish chips

C:\>set xx=sausage
C:\>set msg
msg=fish chips

C:\>set msg=%xx% chips
C:\>set msg
msg=sausage chips

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

To display undocumented system variables:

SET "

Prompt for user input

@echo off
Set /P _dept=Please enter Department:
If "%_dept%"=="" goto :sub_error
If /i "%_dept%"=="finance" goto sub_finance
If /i "%_dept%"=="hr" goto sub_hr
goto:eof

:sub_finance
echo You chose the finance dept
goto:eof

:sub_hr
echo You chose the hr dept

The /P switch allows you to set a variable equal to a line of input entered by the user.
The PromptString is displayed before the user input is read. The PromptString can be empty.
The CHOICE command is an alternative to SET /P

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

Set /P _MyVar=<myfilename.txt "="" "_department="

Variable names can include Spaces

A variable can contain spaces and also the variable name itself may contain spaces, therefore the following assignment:
SET my var=MyText
will create a variable called " "_var="" %="" &="" (%substring%)="" (set="" *="" +="" -="" 1="" <<="" ^="" _department="Better" _var="MyText" a)="" a="" actually="" add="" after="" allowing="" alternatively="" an="" and="" appearing="" arithmetic="" avoid="" be="" bracket="" brown="" call="" called="" can="" character.="" command="" create="" current="" deleting="" detected="" divide="" do="" dog="" echo="" environment.="" environment="" equals="" errorlevel="" escape="" evaluated:="" evaluated="" expression="" expressions="" extra="" following="" found="" fox="" if="" in="" include="" is="" issue="" jumps="" just="" lazy="" length="9" like="" lsh="" modulus="" multiply="" my="" name="" need="" no="" not="" note:="" note="" operators:="" or="" output,="" over="" parentheses,="" problems="" quick="" rsh="" set="" sign:="" similarly="" space="" spaces="" start="10" statements="" still,="" string="The" substring="" subtract="" sure="" text"="" text)="" the="" there="" this="" to="" trailing="" type="" use="" using="" var"="" variable="" wanted="" will="" with="" xor="" you="" your="" |="">>
Multiply Variable *=
Divide Variable /=
Add Variable +=
Subtract Variable -=
AND Variable &=
OR Variable |=
XOR Variable ^=
LSH Variable <<= RSH Variable <<= SET /a calculations Enclose any logical expressions in "quotes" Several calculations can be put on one line if separated with commas. Warning: 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 } Modulus operator - note that in a batch script, (as opposed to on the command-line), you need to double up the % to %% SET /A will treat any character string in the expression as an environment variable name. This allows you to do arithmetic with environment variable values without having to type any % signs to get the values. SET /A _result=5 + _MyVar Leading Zero will specify Octal Numeric values are decimal numbers, unless prefixed by 0x for hexadecimal numbers, 0 for octal numbers. So 0x12 = 022 = 18 decimal The octal notation can be confusing - all numeric values that start with zeros are treated as octal but 08 and 09 are not valid numbers because 8 and 9 are not valid octal digits. This is often a cause of error when performing date arithmetic. For example SET /a _day=07 will return the value=7, but SET /a _day=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 in 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, but neither SET or SetX will affect other CMD sessions that are already running. When you think about it - this is a good thing. It is also possible (although undocumented) to add permanent env variables to the registry [HKEY_CURRENT_USER\Environment] (using REGEDIT) System Environment variables can also be found in [HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment] Autoexec.bat Any SET statement in c:\autoexec.bat may 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. If Command Extensions are disabled all SET commands are disabled other than simple assignments like: _variable=MyText
Please Leave Your Comment

162). SETLOCAL = Control the visibility of environment variables...
(EXPLAIN - SETLOCAL)
Set options to control the visibility of environment variables in a batch file.

Syntax
SETLOCAL

SETLOCAL EnableDelayedExpansion

SETLOCAL EnableExtensions | DisableExtensions

Key
EnableDelayedExpansion Expand variables at execution time rather than at parse time.

EnableExtensions Attempt to enable Command extensions.

DisableExtensions Attempt to disable Command extensions.

SETLOCAL on it's own, usually at the start of a batch file, will begin localisation of Environment Variables.

Issuing a SETLOCAL command, the batch script will inherit all current variables from the master environment/session.

Issuing an ENDLOCAL command will restore any environment variables present before the SETLOCAL was issued.

If a batch script does not use SETLOCAL and ENDLOCAL then all variables will be Global, i.e. visible and modifiable by other scripts.

Although global variables are easy to work with they are not good practice - for example if you have several batch scripts dealing with filenames (and these scripts may be CALLing one another), the first script may have a variable called _filename, the second script a different variable called file-name (a different name to avoid conflicting with the first script) a third script now needs something like file_name this quickly becomes very difficult to manage.

With local variables you are free to use the same variable names in multiple batch scripts - there is no conflict because the local variables are not visible to any other script.
Local Variables can be passed from one batch routine to another with the ENDLOCAL command.

EnableDelayedExpansion

Setting EnabledDelayedExpansion will cause each variable to be expanded at execution time rather than at parse time.
EnableDelayedExpansion is Disabled by default.

Overloading a variable

SETLOCAL can be used more than once in the same batch file so that multiple values can be stored in the same Environment Variable. To keep track of variable definitions, SETLOCAL and ENDLOCAL statements should be paired.

@echo off
SETLOCAL
::Standard commission
SET _Commission=20
echo %_Commission%

::Premium commission
SETLOCAL
set _Commission=30
echo %_Commission%

::back to Standard commission
ENDLOCAL
echo %_Commission%

DISABLEEXTENSIONS

Command Extensions are enabled by default, there is rarely any need to disable them.

If Command Extensions are permanently disabled or if a script is running under the Windows 95 command processor command.com then SETLOCAL ENABLEEXTENSIONS will not be able to restore them.

A batch file to warn if command extensions are not available:

VERIFY errors 2>nul
SETLOCAL ENABLEEXTENSIONS
IF ERRORLEVEL 1 echo Unable to enable extensions

Errors

SETLOCAL will set an ERRORLEVEL if given an argument: It will be zero if one of the two valid arguments is given and one otherwise.
Please Leave Your Comment

163). SETX = Set environment variables permanently...
(EXPLAIN - SETX.exe(WINDOWS 7)
Set environment variables permanently

SETX can be used to set Environment Variables for the machine or currently logged on user:

SETX Variable Value

SETX Variable Value -m

Key:
-m Set the value in the Machine environment (HKLM)
Default is User (HKCU)

SetX can also be used in modes to edit the Registry or edit CR-LF text files, (like win.ini) for most purposes these tasks are better done with other tools in the resource kit, e.g. the REG command.

Because SetX writes variables to the master environment in the registry. Edits will only take effect when a new command window is opened - they do not affect the current command session.

Deleting variables
A value of "" (empty quotes) will appear to delete the variable - it's not shown by SET but the variable name will remain in the registry. Either use the GUI (recommended) or delete the value from the registry with REG

REG delete HKCU\Environment /V _myvar

Deleting a variable with REG does not take effect until next logon due to caching of registry data. The type is REG_EXPAND_SZ.

Examples:

Set the variable _mypc to be COMPAQ in the users permanent environment:

SetX _mypc COMPAQ

Delete the variable _mypc in the users permanent environment:

REG delete HKCU\Environment /V _mypc

Set the variable _myTimeZone in both the immediate user session and the permanent environment:

SET _myTimeZone=GMT
SetX _myTimeZone GMT


Store the value of %my_important_var% in a second environment variable.
SetX _mybackupvar %my_important_var%

Sets the value of _mypath to be equal to the value of the %PATH% environment variable, _mypath will then remain the same even if the PATH variable changes in the future:
SetX _mypath ~PATH~

Machine variables

These are stored on the machine and won't follow a users roaming profile.
To set a machine variable (-m) requires Administrator rights.

Create a machine variable:

SetX _myvar COMPAQ -m

Delete a machine variable:

REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /V _myvar
Please Leave Your Comment

164). SFC = System File Checker...
(EXPLAIN - SFC (Windows XP, Server 2003, Win 7)
System File Checker

Syntax
Sfc [/Scannow] [/Scanonce] [/Scanboot] [/Revert] [/Purgecache] [/Cachesize=x]
Key
/Scannow Scan all protected system files immediately and replace
incorrect versions with correct Microsoft versions.
May require access to the Windows installation source files.

/Scanonce Scan all protected system files one time when you restart your computer.
May require access to the Windows installation source
files when you restart the computer.
The SfcScan DWORD value is set to 2 in the following registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon

/Scanboot Scan all protected system files every time you start your computer.
May require access to the Windows installation source files every
time you start the computer.
The SfcScan DWORD value is set to 1 in the following registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon

/Revert Return scan to the default setting
(do not scan protected files when you start the computer).
The default cache size is not reset when you run this command.

/Purgecache Purge the file cache and scan all protected system files immediately.
May require access to the Windows installation source files.

/Cachesize=x Set the file cache size to x megabytes (MB).
The default size of the cache is 50 MB.
This command requires you to restart the computer, and then run
the /purgecache command to adjust the size of the on-disk cache.
This command sets the SfcQuota DWORD value to x in the following registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon

Under Windows 7, SFC must be run from an elevated command prompt.
Please Leave Your Comment

165). SHARE = List or edit a file share or print share...
(EXPLAIN - Share.vbs)
List or edit a file share or print share (on any computer)

Although missing from recent Resource Kits, this VBS script does still work under recent versions of Windows. The preferred method for creating shares is the RMTShare command, which can also grant permissions.

Syntax:
List Shares
Share.vbs /L [/S ] [/U ] [/W ] [/O ]

Create a Share
Share.vbs /C /N /P [/T ] [/V ]
[/S ] [/U ] [/W ] [/O ]
Delete a Share
Share.vbs /D /N
[/S ] [/U ] [/W ] [/O ]

Key:

/L List
/C Create
/D Delete
/N name Name of the share to be created or deleted.
/P path Path of the share to be created.
/v description A description for the share.
/T type Type of the share to be created. (Disk, Printer, IPC or Special)
/S server A machine name.
/U username The current user's name.
/W password Password of the current user.
/O outputfile Output file name.

Examples:

List the shares on the machine \\Frodo

cscript Share.vbs /L /s Frodo

Create a file share called "scratch" on the local machine:

cscript Share.vbs /c /n scratch /p "c:\my shared files" /t Disk /v "project files"

Delete the share named "scratch" on the machine \\Frodo

cscript Share.vbs /d /n scratch /s Frodo
Please Leave Your Comment

166). SHIFT = Shift the position of replaceable parameters in a batch file...
(EXPLAIN - SHIFT)
Change the position of command line parameters in a batch file.

Syntax
SHIFT [/n]

Key
/n Start at the nth argument, where n may be between zero and eight.



Relative pathnames

Examples:

Given %1=the, %2=quick, %3=brown
SHIFT
will result in %1=quick, %2=brown
A second
SHIFT
will result in %1=brown

Given %1=the, %2=quick, %3=brown, %4=fox
SHIFT /2
will result in %1=the, %2=brown, %3=fox

Parse Command Line Arguments

:start
if "%1"=="" (goto :main)
:: Do whatever with token %1
Echo [%1]
:: Shift %2 into %1
SHIFT
goto :start

:main
::

The parameter %0 will initially refer to the path that was used to execute the batch - this could be MyBatch.cmd if in the current directory or a full path like C:\apps\myBatch.cmd

If SHIFT is used to move a text parameter into %0 then any references to %0 will refer instead to the current working directory, unless the new parameter value happens to contain a valid path.

For example:

%0\..\MyExecutable.exe

will run the MyExecutable from the same directory as the Batch file.

If the following parameter is passed to myBatch.cmd

myBatch.cmd D:\utils\

Then the following commands in myBatch will run MyExecutable.exe from the directory D:\utils\

SHIFT
%0\..\MyExecutable.exe

If Command Extensions are disabled, the SHIFT command will not support the /n switch
Please Leave Your Comment

167). SHORTCUT = Create a windows shortcut (.LNK file)...
(EXPLAIN - SHORTCUT.exe)
Create a windows shortcut (.LNK file)

Syntax
SHORTCUT [options]

Key
Source options
-t target : The path and file name of the application/document to open.
-a arguments : The arguments passed when the shortcut is used.
-d directory : The folder to start the application in.
-i iconfile : The file the icon is in.
-x index : The index into the icon file.

options for the shortcut file to be created

-n name : The path and file name (.LNK) of the shortcut file.
-c : Change existing shortcut.
-r : Resolve broken shortcut.
-f : Force overwrite of an existing short cut.
-s : Make shortcut simple (don't use LinkResolve)

Export options
-u [spec] : ECHO the contents of an existing shortcut.
'all' is the same as 'natdix' but the letters
of 'natdix' specify the options to be exported
(the same option can be specified more than once
e.g. -u natn)
-l logfile : Save any error messages in the specified file

If shortcut.exe fails to create a new shortcut, it does NOT set an errorlevel.

Example

@ECHO off
MD %userprofile%"\start menu\programs\MY APP"
SHORTCUT -f -t C:\MyApp.exe -n %userprofile%"\start menu\programs\MY APP\MY APP"

For Windows XP and more recent systems, you are better off using a little .vbs script, as WSH is built-in from XP onwards, call the script like so:
CSCRIPT C:\myshortcut.vbs

Optional sections in the VBscript below are commented out:

Set oWS = WScript.CreateObject("WScript.Shell")
sLinkFile = "C:\MyShortcut.LNK"
Set oLink = oWS.CreateShortcut(sLinkFile)

oLink.TargetPath = "C:\Program Files\MyApp\MyProgram.EXE"
' oLink.Arguments = ""
' oLink.Description = "MyProgram"
' oLink.HotKey = "ALT+CTRL+F"
' oLink.IconLocation = "C:\Program Files\MyApp\MyProgram.EXE, 2"
' oLink.WindowStyle = "1"
' oLink.WorkingDirectory = "C:\Program Files\MyApp"
oLink.Save

Shortcut: NTFS file system tracking

If a shortcut to a file breaks because the destination file has moved, then by default Windows will attempt to automatically locate the shortcut destination by performing a search (this only applies to NTFS partitions). To turn this off - add a DWORD value of 1 to the registry:

HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
NoResolveTrack=1

Shortcut: Auto LinkResolve

By default shortcuts will include the destination machine, even for a target like C:\MyFile.doc
This is not immediately visible until the shortcut.LNK file is copied to another machine, the shortcut target will then be automatically updated to point back to \\Machine1\c$\MyFile.doc
To turn this behaviour off use shortcut.exe -s or add a DWORD value of 1 to the registry (before creating the shortcut):

HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
"LinkResolveIgnoreLinkInfo"=1

Favourites
Often confused with shortcuts, Internet Explorer Favourite (.URL) files are simple text files which you can create with a few ECHO statements.
Please Leave Your Comment

168). SHOWGRPS = List the NT Workgroups a user has joined...
(EXPLAIN - SHOWGRPS)
List the Workgroups a user has joined.

Syntax
SHOWGRPS domain\username

SHOWGRPS username

If no username is specified SHOWGRPS will list the workgroups for the currently logged in user.

Example

SHOWGRPS ss64domain\user05
Please Leave Your Comment

169). SHOWMBRS = List the Users who are members of a Workgroup...
(EXPLAIN - SHOWMBRS)
List all the users who are members of a Workgroup.

Syntax
SHOWMBRS domain\Workgroup

SHOWMBRS Workgroup

A workgroup must be specified.

Example:

SHOWMBRS wg_finance
Please Leave Your Comment

170). SHUTDOWN = Shutdown the computer...
(EXPLAIN - SHUTDOWN.exe)
Shutdown the computer

Syntax
SHUTDOWN [logoff_option] [/m \\Computer] [options]

logoff_options:
/i Display the GUI (must be the first option)
/l Log off. This cannot be used with /m or /d option
/s Shutdown
/r Shutdown and Restart
/a Abort a system shutdown.
(only during the time-out period)
/p Turn off the local computer with no time-out or warning
(only with /d)
/h Hibernate the local computer (only with /f )
/e Document the reason for an unexpected shutdown of a computer

Options:

/m \\Computer : A remote computer to shutdown.

/t:xxx : Time until system shutdown in seconds.
The valid range is xxx=0-600 seconds. [default=30]
/c "Msg" : An optional shutdown message [Max 127 chars]

/f : Force running applications to close.
This will not prompt for File-Save in any open applications.
so will result in a loss of all unsaved data!!!

/d u:xx:yy : List a USER (unplanned) reason code for the shutdown.
/d P:xx:yy : List a PLANNED reason code for the shutdown.
xx Specifies the major reason code (0-255)
yy Specifies the minor reason code (0-65536)

Options in bold are for Windows 2003 and later

When using this command to reboot a server, the shutdown process will normally allow 30 seconds to ensure each running service has time to stop. Services are shutdown in alphabetical order. The shutdown may be done made faster if the services are first halted in a specific order using NET STOP or SC.

Reason codes:
E = Expected
U = Unexpected
P = Planned (C = customer defined)

Type Major Minor Title
U 0 0 Other (Unplanned)
E 0 0 Other (Unplanned)
E P 0 0 Other (Planned)
U 0 5 Other Failure: System Unresponsive
E 1 1 Hardware: Maintenance (Unplanned)
E P 1 1 Hardware: Maintenance (Planned)
E 1 2 Hardware: Installation (Unplanned)
E P 1 2 Hardware: Installation (Planned)
P 2 3 Operating System: Upgrade (Planned)
E 2 4 Operating System: Reconfiguration (Unplanned)
E P 2 4 Operating System: Reconfiguration (Planned)
P 2 16 Operating System: Service pack (Planned)
2 17 Operating System: Hot fix (Unplanned)
P 2 17 Operating System: Hot fix (Planned)
2 18 Operating System: Security fix (Unplanned)
P 2 18 Operating System: Security fix (Planned)
E 4 1 Application: Maintenance (Unplanned)
E P 4 1 Application: Maintenance (Planned)
E P 4 2 Application: Installation (Planned)
E 4 5 Application: Unresponsive
E 4 6 Application: Unstable
U 5 15 System Failure: Stop error
E 5 19 Security issue
U 5 19 Security issue
E P 5 19 Security issue
E 5 20 Loss of network connectivity (Unplanned)
U 6 11 Power Failure: Cord Unplugged
U 6 12 Power Failure: Environment
P 7 0 Legacy API shutdown

Examples

Shutdown the local system immediately:

SHUTDOWN /s

Restart the local system in 60 seconds time and specify the reason "Application: Installation (Planned)" :

SHUTDOWN /r /t:60 /d P:4:2

Restart the remote system server64 and specify the reason "Security Fix, Planned"

SHUTDOWN /r /m \\server64 /d P:2:17
Please Leave Your Comment

171). SLEEP = Wait for x seconds...
(EXPLAIN - SLEEP.exe)
Add a fixed delay to a batch file

Syntax
SLEEP time
Key
time : the number of seconds to pause

For example:
To pause for an hour before running the next command in a batch file:

SLEEP 3600

Alternative
A fixed delay can also be produced by the PING command with a loopback address:

e.g. for a delay of 60 seconds:
PING -n 61 127.0.0.1>nul
Please Leave Your Comment

172). SLMGR = Software Licensing Management (Vista/2008)...
(EXPLAIN - slmgr.vbs (Vista and Server 2008)
Software Licensing Management Tool (C:\windows\system32\slmgr.vbs)

Syntax
slmgr [MachineName [Username Password]] [Option]

Key
-dli Display the current license information with activation
status and partial product key.

-dlv Verbose, similar to -dli but with more information.

-dti Display Installation ID for offline activation

-ipk Key Enter a new product key supplied as xxxxx-xxxxx-xxxxx-xxxxx-xxxxx

-xpr Show the expiry date of current license (if not permanently activated)

-upk Uninstall current installed product key and return license status back to trial state.

-ato Activate Windows license and product key against Microsoft's server.

-atp Confirmation_ID Activate Windows with user-provided Confirmation ID

-skms activationservername
or
-skms port
or
-skms activationservername:port
Set the KMS server and the port used for KMS activation
(where supported by your Windows edition)

-rearm Reset the evaluation period/licensing status and activation state of the machine

-ckms Clear the name of KMS server used to default and port to default.

-cpky Clear product key from the registry (prevents disclosure attacks)

-ilc License_file Install license

-rilc Re-install system license files

machinename The machine to administer, by default the current local machine.

username An administrator equivalent user account for the computer.

password The password for the user account.

Running slmgr.vbs requires elevated administrator privileges.

Examples

C:\windows\system32\slmgr.vbs wkstn0064 administrator password1 -dli
slmgr.vbs -skms 192.168.10.1:8090
slmgr.vbs -skms KMSServer:8090
Please Leave Your Comment

173). SOON = Schedule a command to run in the near future...
(EXPLAIN - SOON.exe)
Schedule a command to run in the near future (calls the AT command)

Syntax
SOON [\\computername] delay [/interactive] "command"
SOON /i:[on|off]

Key
delay : When the command should run, in SECONDS from now.
default=5

/interactive : Allows any user to see the job as it runs,
this allows testing and monitoring of the
command.
You can specify /interactive as just /i

computername : the UNC name of a remote machine

/i:on : Make /interactive the default behaviour
use SOON /i:off to restore normal behaviour

SOON schedules jobs to run at a time relative to the current time in "seconds from now"
It is otherwise identical to the AT command but saves calculating an exact start time.

As with all AT jobs you should test your SOON scripts by using the /INTERACTIVE option.

In many cases SCHTASKS may be a better option.
Please Leave Your Comment

174). SORT = Sort input...
(EXPLAIN - SORT)
Sort will accept a redirected or piped file input and TYPE the file, sorted line by line.

Syntax
SORT [options]

Options
/R : Reverse sort order (Z to A, 9 to 0)

/+n : Sort the file ignoring the first 'n' characters in each row.
The default is to sort using all the chars in each row.

/L[OCALE] locale

Override the system default locale with
The "C" locale yields a faster
collating sequence.
The sort is always case insensitive.

/M[EMORY] kilobytes

The amount of RAM to use for the sort.
The best performance is usually achieved by
not specifying a memory size.

SORT will only create a temporary file
when required by limitations in available memory.

/REC[ORD_MAXIMUM] characters

The maximum number of characters in a row or record
(default 4096, maximum 65535)

[drive:][pathname]

The file to be sorted.
If not specified, the standard input is sorted.
Specifying an input file is faster than
redirecting the same file as standard input.

/T[EMPORARY] [drive:][path]

The path of the directory to hold
SORT's working storage, in case the data
does not fit in RAM. The default is %temp%

/O[UTPUT] [drive:][pathname]

The file where the sorted input is to be stored.
If not specified, the data is written to standard output.
Specifying an output file is faster than redirecting
standard output to a file.

Redirecting a file into SORT

SORT < pathname Piping a command into SORT command | SORT Piping the output from SORT into a file command | SORT > pathname2
SORT < pathname > pathname2

Piping the output from SORT and appending to an existing file

command | SORT >> pathname2
SORT < pathname >> pathname2
Please Leave Your Comment

175). START = Start a program or command in a separate window...
(EXPLAIN - START)
Start a specified program or command in a separate window.

Syntax
START "title" [/Dpath] [options] "command" [parameters]

Key:
title : Text for the CMD window title bar (required)
path : Starting directory
command : The command, batch file or executable program to run
parameters : The parameters passed to the command

Options:
/MIN : Minimized
/MAX : Maximized
/WAIT : Start application and wait for it to terminate
/LOW : Use IDLE priority class
/NORMAL : Use NORMAL priority class
/HIGH : Use HIGH priority class
/REALTIME : Use REALTIME priority class

/B : Start application without creating a new window. In this case
^C will be ignored - leaving ^Break as the only way to
interrupt the application
/I : Ignore any changes to the current environment.

Options for 16-bit WINDOWS programs only

/SEPARATE Start in separate memory space (more robust)
/SHARED Start in shared memory space (default)

Notes:

Always include a TITLE this can be a simple string like "My Script" or just a pair of empty quotes ""
According to the Microsoft documentation, the title is optional, but you may have problems if it is omitted.

Document files may be invoked through their file association just by typing the name of the file as a command.
e.g. START "" WORD.DOC would launch the application associated with the .DOC file extension

Examples

START "My Login Script" /Min Login.cmd

START "" /wait MySlowProgram.exe

Printers
A new printer can be installed very quickly (and the driver downloaded) with the command:

START \\print_server\printer_name

Setting a Working Directory
To start an application and specify where files will be saved:

START /Dc:\Documents\ /MAX "Maximised Notes" notepad.exe

Forcing a Sequence of Programs
If you require your users to run a sequence of 32 bit GUI programs to complete a task, create a batch file that uses the start command:

@echo off
start /wait /b First.exe
start /wait /b Second.exe
start /wait /b Third.exe

Create a shortcut to this batch file and place it on the Start menu or desktop. Set it to run minimized.
When the user double-clicks the shortcut, runs.
When terminates, runs
When terminates, runs

An alternative method is to run a .BAT batch file under command.com (16 bit)

If Command Extensions are disabled, the START command will no longer recognise file Associations, and will not automatically evaluate the COMSPEC variable when starting a second CMD session.

Missing file extensions
When executing a command line whose first token does NOT contain an extension, then CMD.EXE uses the value of the PATHEXT environment variable to determine which extensions to look for and in what order. The default value for the PATHEXT variable is:

.COM;.EXE;.BAT;.CMD

Notice the syntax is the same as the PATH variable, with semicolons separating the different elements.

When executing a command, if there is no match on any extension, then Windows will look to see if the name, without any extension, matches a directory name and if it does, the START command will launch Explorer on that path.
Please Leave Your Comment

176). SU Switch User...
(EXPLAIN - SU)
Switch User.

Syntax
SU "[cmdline]" [domain] [[Winsta\]Desktop] [options]

Key
cmdline The command to run (default =%comspec%)
domain The domain for the user account ('.' = local m/c)
Winsta\Desktop The profile to load (default = current)

Options

-cb console bypass
-dn do not switch to new desktop
-g GUI option
-l load the .Default user registry hive
-w use current registry hive
-e Inherit parent environment
-b batch logon
-i interactive logon
-s service logon
-n network logon
-v verbose

All LogOn Types require specific User Rights to be granted...
SeNetworkLogonRight, SeServiceLogonRight, SeInteractiveLogonRight, SeBatchLogonRight

The RUNAS command is a lot easier to use!
Please Leave Your Comment

177). SUBINACL = Edit file and folder Permissions, Ownership and Domain...
(EXPLAIN - SUBINACL.exe)
Display or modify Access Control Entries (ACEs) for file and folder Permissions, Ownership and Domain.

Access Control Lists apply only to files stored on an NTFS formatted drive, each ACL determines which users (or groups of users) can read or edit the file. When a new file is created it normally inherits ACL's from the folder where it was created.

Syntax
SUBINACL [/noverbose] /object_type object_name [/action=parameter] [/help]

Key
object_type: service e.g. /service Messenger \\ServerName\Messenger
keyreg e.g. /keyreg HKEY_CURRENT_USER\Software
/keyreg \\Srv\HKEY_LOCAL_MACHINE\KeyPath
file e.g. /file *.obj /file c:\test.txt
/file \\ServerName\Share\Path
subdirectories manipulate files in specified directory and all subdirectories

object_name : This will vary according to the object_type - see the examples above

action : setowner=owner
will change the owner of the object e.g. /setowner=MyDomain\Administrators

replace=SamName\OldAccount=DomainName\New_Account
will replace all ACE (Audit and Permissions) in the object
e.g. /replace=MyOldDomain\Finance=NEWDOM\Finance

changedomain=OldDomainName=NewDomainName
will replace all ACEs with a Sid from OldDomainName
with the equivalent Sid found in NewSamServer
e.g. /changedomain=MyOldDomain=NEWDOMAIN
This option requires a trust relationship with the server containing the object.

Examples:

subinacl can do everything that cacls and xcacls can do and more besides.

List permissions to log file:
subinacl /noverbose /nostatistic /outputlog=my.log /subdirectories "C:\Program Files\My Folder" /display

Restore Permissions:
subinacl /nostatistic /playfile my.log

Change owner :
subinacl /file C:\demofile.doc /setowner=MYDOMAIN\BillG

Bugs

Running subinacl against a subfolder, as in the example above will affect just that folder and it's contents. However if you run subinacl against a folder in the root of the drive it will scan the entire drive for folders matching that name (which can take some time).
e.g.
subinacl /subdirectories "C:\Spud"
Will also match
C:\Program Files\Spud
C:\Documents and Settings\Spud etc
Please Leave Your Comment

178). SUBST = Associate a path with a drive letter...
(EXPLAIN - SUBST)
Substitute a drive letter for a network or local path.

Syntax
SUBST drive_letter: path

SUBST

SUBST drive_letter: /D

Key
SUBST with no parameters will display current SUBST drives

/D : Delete the drive_letter substitution.

Compared to mapping a drive with NET USE the SUBST command allows mapping to a subfolder of a drive share - for the storage of user profiles this reduces the number of shares you need to create on the server.

Notes
Under NT 4 SUBST'ed drives could be disconnected using the Explorer GUI - this was fixed in Windows 2000.

In Windows 2000 (and above) you may have problems creating, accessing and deleting drive mappings with SUBST.

However under Win 2K/XP the functionality of the NET USE command is improved so you can now do
NET USE g: \\server\share\folder1\folder2

If the network resource is unavailable (ie the server is down) SUBST will continually retry - unlike NET USE which will try to connect once and fail - depending on your application this may be a good or a bad thing - a subst drive that is not available will badly impact performance of most applications.

Notice that when SUBST is used against a local shared folder, it will create a RECYCLER for that drive. The RECYCLER is not removed when the drive substitution is removed, but can be deleted manually.
Please Leave Your Comment

179). SYSTEMINFO = List system configuration...
(EXPLAIN - SYSTEMINFO)
List system configuration

Syntax
SYSTEMINFO [/S system [/U username [/P [password]]] ]
[/FO format] [/NH]

Key:
/S system Remote system to connect to.
/U [domain\]user User context under which to execute.
/P [password] Password for the given user (will prompt if omitted)
/FO format Output format: TABLE, LIST or CSV
/NH No "Column Header" in the Table/CSV output

The output includes OS configuration, security info, product ID, RAM, disk space, and network cards.

Examples

SYSTEMINFO
SYSTEMINFO |find "Total Physical Memory:"
SYSTEMINFO /S wkstn6324
SYSTEMINFO /S wkstn6325 /FO CSV /NH >>pcaudit.csv
Please Leave Your Comment

180). TASKLIST = List running applications and services...
(EXPLAIN - TASKLIST)
TaskList displays all running applications and services with their Process ID (PID) This can be run on either a local or a remote computer.

Syntax
tasklist options

Options:

/s computer Name or IP address of a remote computer
don't use backslashes. Default = local computer.

/u domain\user [/p password]]
Run under a different account

/svc List information for each process without truncation.
Valid when /fo=TABLE. Cannot be used with /m or /v

/m [ModuleName]
Show the processes that include the given module.

/v Verbose task information

/fo {TABLE|LIST|CSV}]
Output format, the default is TABLE.

/nh No Headers in the output (does not apply to LIST output)

/fi FilterName [/fi FilterName2 [ ... ]]
Apply one of the Filters below:

Imagename eq, ne String
PID eq, ne, gt, lt, ge, le Positive integer.
Session eq, ne, gt, lt, ge, le Any valid session number.
SessionName eq, ne String
Status eq, ne RUNNING | NOT RESPONDING
CPUTime eq, ne, gt, lt, ge, le Time hh:mm:ss
MemUsage eq, ne, gt, lt, ge, le Any valid integer.
Username eq, ne User name ([Domain\]User).
Services eq, ne String
Windowtitle eq, ne String
Modules eq, ne String

Examples:

List the services running under each process:

TASKLIST /svc

List the services running under each SvcHost process:

TASKLIST /FI "imagename eq svchost.exe" /svc

List the services running now:

TASKLIST /v /fi "STATUS eq running"

List the services running under a specific user account:

TASKLIST /v /fi "username eq SERVICE_ACCT05"
Please Leave Your Comment

FaceBook