WindowsXP Command Line - Teguh W

80
An A-Z Index of the Windows XP command line By : Ir. Teguh W. a ADDUSERS Add or list users to/from a CSV file ARP Address Resolution Protocol ASSOC Change file extension associations ASSOCIAT One step file association ATTRIB Change file attributes b BOOTCFG Edit Windows boot settings BROWSTAT Get domain, browser and PDC info c CACLS Change file permissions CALL Call one batch program from another CD Change Directory - move to a specific Folder CHANGE Change Terminal Server Session properties CHKDSK Check Disk - check and repair disk problems CHKNTFS Check the NTFS file system CHOICE Accept keyboard input to a batch file CIPHER Encrypt or Decrypt files/folders CleanMgr Automated cleanup of Temp files, recycle bin CLEARMEM Clear memory leaks CLIP Copy STDIN to the Windows clipboard. CLS Clear the screen CLUSTER Windows Clustering CMD Start a new CMD shell COLOR Change colors of the CMD window COMP Compare the contents of two files or sets of files COMPACT Compress files or folders on an NTFS partition COMPRESS Compress individual files on an NTFS partition CON2PRT Connect or disconnect a Printer CONVERT Convert a FAT drive to NTFS. COPY Copy one or more files to another location CSCcmd Client-side caching (Offline Files) CSVDE Import or Export Active Directory data d DATE Display or set the date DEFRAG Defragment hard drive DEL Delete one or more files DELPROF Delete NT user profiles DELTREE Delete a folder and all subfolders DevCon Device Manager Command Line Utility DIR Display a list of files and folders DIRUSE Display disk usage DISKCOMP Compare the contents of two floppy disks DISKCOPY Copy the contents of one floppy disk to another DISKPART Disk Administration DNSSTAT DNS Statistics DOSKEY Edit command line, recall commands, and create macros DSADD Add user (computer, group..) to active directory DSQUERY List items in active directory DSMOD Modify user (computer, group..) in active directory DSRM Remove items from Active Directory e ECHO Display message on screen ENDLOCAL End localisation of environment changes in a batch file

description

Command Line Interface for windows is the basic command on DOS

Transcript of WindowsXP Command Line - Teguh W

An A-Z Index of the Windows XP command lineBy : Ir. Teguh W.

a ADDUSERS Add or list users to/from a CSV file

ARP Address Resolution Protocol ASSOC Change file extension associations ASSOCIAT One step file association ATTRIB Change file attributesb BOOTCFG Edit Windows boot settings BROWSTAT Get domain, browser and PDC infoc CACLS Change file permissions CALL Call one batch program from another CD Change Directory - move to a specific Folder CHANGE Change Terminal Server Session properties CHKDSK Check Disk - check and repair disk problems CHKNTFS Check the NTFS file system CHOICE Accept keyboard input to a batch file CIPHER Encrypt or Decrypt files/folders CleanMgr Automated cleanup of Temp files, recycle bin CLEARMEM Clear memory leaks CLIP Copy STDIN to the Windows clipboard. CLS Clear the screen CLUSTER Windows Clustering CMD Start a new CMD shell COLOR Change colors of the CMD window COMP Compare the contents of two files or sets of files COMPACT Compress files or folders on an NTFS partition COMPRESS Compress individual files on an NTFS partition CON2PRT Connect or disconnect a Printer CONVERT Convert a FAT drive to NTFS. COPY Copy one or more files to another location CSCcmd Client-side caching (Offline Files) CSVDE Import or Export Active Directory data d DATE Display or set the date DEFRAG Defragment hard drive DEL Delete one or more files DELPROF Delete NT user profiles DELTREE Delete a folder and all subfolders DevCon Device Manager Command Line Utility DIR Display a list of files and folders DIRUSE Display disk usage DISKCOMP Compare the contents of two floppy disks DISKCOPY Copy the contents of one floppy disk to another DISKPART Disk Administration DNSSTAT DNS Statistics DOSKEY Edit command line, recall commands, and create macros DSADD Add user (computer, group..) to active directory DSQUERY List items in active directory DSMOD Modify user (computer, group..) in active directory DSRM Remove items from Active Directorye ECHO Display message on screen ENDLOCAL End localisation of environment changes in a batch file ERASE Delete one or more files EVENTCREATE Add a message to the Windows event log EXIT Quit the current script/routine and set an errorlevel EXPAND Uncompress files EXTRACT Uncompress CAB filesf FC Compare two files FIND Search for a text string in a file FINDSTR Search for strings in files FOR /F Loop command: against a set of files FOR /F Loop command: against the results of another command FOR Loop command: all options Files, Directory, List

FORFILES Batch process multiple files FORMAT Format a disk FREEDISK Check free disk space (in bytes) FSUTIL File and Volume utilities FTP File Transfer Protocol FTYPE Display or modify file types used in file extension

associationsg GLOBAL Display membership of global groups GOTO Direct a batch program to jump to a labelled line GPUPDATE Update Group Policy settingsh HELP Online Helpi iCACLS Change file and folder permissions IF Conditionally perform a command IFMEMBER Is the current user in an NT Workgroup IPCONFIG Configure IPk KILL Remove a program from memoryl LABEL Edit a disk label LOCAL Display membership of local groups LOGEVENT Write text to the NT event viewer LOGOFF Log a user off LOGTIME Log the date and time in a filem MAPISEND Send email from the command line MBSAcli Baseline Security Analyzer. MEM Display memory usage MD Create new folders MKLINK Create a symbolic link (linkd) MODE Configure a system device MORE Display output, one screen at a time MOUNTVOL Manage a volume mount point MOVE Move files from one folder to another MOVEUSER Move a user from one domain to another MSG Send a message MSIEXEC Microsoft Windows Installer MSINFO Windows NT diagnostics MSTSC Terminal Server Connection (Remote Desktop Protocol) MUNGE Find and Replace text within file(s) MV Copy in-use filesn NET Manage network resources NETDOM Domain Manager NETSH Configure Network Interfaces, Windows Firewall & Remote access NETSVC Command-line Service Controller NBTSTAT Display networking statistics (NetBIOS over TCP/IP) NETSTAT Display networking statistics (TCP/IP) NOW Display the current Date and Time NSLOOKUP Name server lookup NTBACKUP Backup folders to tape NTRIGHTS Edit user account rightsp PATH Display or set a search path for executable files PATHPING Trace route plus network latency and packet loss PAUSE Suspend processing of a batch file and display a message PERMS Show permissions for a user PERFMON Performance Monitor PING Test a network connection POPD Restore the previous value of the current directory saved by

PUSHD PORTQRY Display the status of ports and services POWERCFG Configure power settings PRINT Print a text file PRNCNFG Display, configure or rename a printer PRNMNGR Add, delete, list printers set the default printer PROMPT Change the command prompt PsExec Execute process remotely

PsFile Show files opened remotely PsGetSid Display the SID of a computer or a user PsInfo List information about a system PsKill Kill processes by name or process ID PsList List detailed information about processes PsLoggedOn Who's logged on (locally or via resource sharing) PsLogList Event log records PsPasswd Change account password PsService View and control services PsShutdown Shutdown or reboot a computer PsSuspend Suspend processes PUSHD Save and then change the current directoryq QGREP Search file(s) for lines that match a given pattern.r RASDIAL Manage RAS connections RASPHONE Manage RAS connections RECOVER Recover a damaged file from a defective disk. REG Registry: Read, Set, Export, Delete keys and values REGEDIT Import or export registry settings REGSVR32 Register or unregister a DLL REGINI Change Registry Permissions REM Record comments (remarks) in a batch file REN Rename a file or files REPLACE Replace or update one file with another RD Delete folder(s) RMTSHARE Share a folder or a printer ROBOCOPY Robust File and Folder Copy ROUTE Manipulate network routing tables RUNAS Execute a program under a different user account RUNDLL32 Run a DLL command (add/remove print connections)s SC Service Control SCHTASKS Schedule a command to run at a specific time SCLIST Display NT Services SET Display, set, or remove environment variables SETLOCAL Control the visibility of environment variables SETX Set environment variables permanently SFC System File Checker SHARE List or edit a file share or print share SHIFT Shift the position of replaceable parameters in a batch file SHORTCUT Create a windows shortcut (.LNK file) SHOWGRPS List the NT Workgroups a user has joined SHOWMBRS List the Users who are members of a Workgroup SHUTDOWN Shutdown the computer SLEEP Wait for x seconds SLMGR Software Licensing Management (Vista/2008) SOON Schedule a command to run in the near future SORT Sort input START Start a program or command in a separate window SU Switch User SUBINACL Edit file and folder Permissions, Ownership and Domain SUBST Associate a path with a drive letter SYSTEMINFO List system configurationt TASKLIST List running applications and services TASKKILL Remove a running process from memory TIME Display or set the system time TIMEOUT Delay processing of a batch file TITLE Set the window title for a CMD.EXE session TLIST Task list with full path TOUCH Change file timestamps TRACERT Trace route to a remote host TREE Graphical display of folder structure TYPE Display the contents of a text fileu USRSTAT List domain usernames and last loginv VER Display version information VERIFY Verify that files have been saved

VOL Display a disk labelw WHERE Locate and display files in a directory tree WHOAMI Output the current UserName and domain WINDIFF Compare the contents of two files or sets of files WINMSD Windows system diagnostics WINMSDP Windows system diagnostics II WMIC WMI Commandsx XCACLS Change file and folder permissions XCOPY Copy files and folders :: Comment / Remark

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

ADDUSERS Tambah atau daftar pengguna untuk / dari file CSV ARP Address Resolution Protocol Assoc Ubah ekstensi file asosiasi ASSOCIAT Salah satu langkah asosiasi file attrib Ubah atribut berkas

bootcfg Edit pengaturan boot Windows BROWSTAT Dapatkan domain, browser dan PDC info

CACLS Ubah file permissions CALL panggilan satu program batch yang lain • CD Change Directory - pindah ke folder tertentu • Change Change Terminal Server Session properties CHKDSK Check Disk - memeriksa dan memperbaiki masalah disk CHKNTFS Periksa sistem file NTFS CHOICE Accept keyboard input ke sebuah file batch cipher Encrypt atau Decrypt file / folder CleanMgr Automated cleanup of Temp file, recycle bin CLEARMEM Clear memory leaks CLIP Copy STDIN ke Windows clipboard. CLS Menghapus layar • CLUSTER Windows Clustering CMD Start a new CMD shell COLOR Mengubah warna dari jendela CMD • COMP Membandingkan isi dari dua file atau set file COMPACT Compress file atau folder pada partisi NTFS individu Compress Compress file pada partisi NTFS CON2PRT Menghubungkan atau memutuskan sambungan Printer CONVERT Convert FAT drive NTFS. COPY Menyalin satu atau lebih file ke lokasi lain • CSCcmd Klien -side caching (Offline Files) CSVDE Impor atau Ekspor Active Directory data

DATE Tampilan atau mengatur tanggal • Defrag Defragment hard drive DEL Menghapus satu atau lebih file • DELPROF Hapus profil pengguna NT DELTREE Menghapus folder dan semua subfolder DevCon Device Manager Command Line Utility DIR Menampilkan daftar file dan folder • DIRUSE Tampilkan penggunaan disk DISKCOMP Bandingkan isi dua disket diskcopy Menyalin isi dari satu floppy disk untuk lain DISKPART Administrasi DNSSTAT DNS Disk Statistik DOSKEY Edit baris perintah, ingat perintah, dan membuat macro DSADD menambah pengguna (komputer, group ..) ke direktori aktif DSQUERY item dalam direktori aktif DSMOD Ubah user (computer, group ..) di direktori aktif DSRM Hapus item dari Active Directory

ECHO Menampilkan pesan di layar •

ENDLOCAL Akhir lokalisasi dari perubahan lingkungan dalam sebuah filebatch

ERASE Menghapus satu atau lebih file • EVENTCREATE Tambahkan pesan ke Windows event log EXIT Keluar dari skrip arus / rutin dan menetapkan errorlevel • EXPAND uncompress file “BUKA”ekstrak file CAB uncompress

FC Bandingkan dua file FIND Mencari string teks dalam sebuah file FINDSTR Mencari string dalam file FOR / F Loop command: terhadap satu set file • FOR / F Loop command: terhadap hasil perintah lain • FOR Loop command: all options Files, Directory, List • FORFILES proses Batch beberapa file FORMAT Format disk Periksa FREEDISK free disk space ( dalam bytes) FSUTIL File dan Volume utilities FTP File Transfer Protocol FTYPE Tampilkan atau mengubah tipe file yang digunakan dalam

Asosiasi ekstensi file

GLOBAL Display keanggotaan kelompok global GOTO langsung sebuah program batch untuk melompat ke baris

berlabelGPUPDATE pengaturan Kebijakan Grup Update HELP Bantuan Online

iCACLS Ubah hak akses file dan folder IF kondisional melakukan perintah IFMEMBER Apakah pengguna saat ini dalam sebuah NT Workgroup IPCONFIG Configure IP

KILL Remove program dari memori l LABEL Edit a disk label LOCAL Display keanggotaan kelompok-kelompok lokal LOGEVENT Menulis teks untuk penampil acara PB logoff user log off LOGTIME log tanggal dan waktu pada file MAPISEND Kirim email dari baris perintah MBSAcli Baseline Security Analyzer. MEM Display penggunaan memori MD Buat folder baru MKLINK Buat link simbolik (linkd) MODE Configure perangkat sistem MORE Display output, satu layar pada satu waktu MOUNTVOL Mengatur volume mount point MOVE Move file dari satu folder ke yang lain MOVEUSER Pindah pengguna dari satu domain ke domain lain MSG Send a message MSIEXEC Microsoft Windows Installer MSINFO Windows NT diagnostics MSTSC Terminal Server Connection (Remote Desktop Protocol) MUNGE Cari dan Ganti teks dalam file (s) MV Copy in-menggunakan file

NET Mengelola sumber daya jaringan NETDOM Domain Manager netsh Configure Network Interfaces, Windows Firewall & Remote

aksesNETSVC Command-line Service Controller NBTSTAT jaringan Tampilan statistics (NetBIOS over TCP / IP) NETSTAT Display networking statistics (TCP / IP) NOW Display the current Tanggal dan Waktu nslookup Name server lookup NTBACKUP Backup folder ke tapeNTRIGHTS hak akun Edit

PATH Menampilkan atau mengatur search path untuk executable filesPATHPING Trace route plus latensi jaringan dan packet loss PAUSE Suspend pemrosesan dari sebuah batch file dan menampilkan

pesanperms Show izin untuk pengguna PERFMON Monitor Kinerja PING Menguji koneksi jaringan POPD Mengembalikan nilai sebelumnya dari direktori sekarang yang

disimpan oleh PUSHD•PORTQRY Tampilan status pelabuhan dan jasa powercfg Mengkonfigurasi pengaturan daya PRINT Mencetak file teks PRNCNFG Display, mengkonfigurasi atau mengubah nama printer PRNMNGR Tambah, menghapus, daftar printer menetapkan printer

standar PROMPT Mengubah command prompt • PsExec proses Execute remote PsFile Tampilkan file yang dibuka dari jarak jauh PsGetSid Menampilkan SID sebuah komputer atau pengguna PsInfo List informasi tentang sebuah sistem PsKill proses Membunuh proses berdasarkan nama atau ID PsList Daftar informasi rinci tentang proses-proses PsLoggedOn Who's logged on (lokal atau melalui resource sharing) PsLogList Event catatan log PsPasswd Ubah sandi account PsService View dan mengatur layanan PsShutdown Shutdown atau reboot komputer PsSuspend proses Suspend PUSHD Simpan dan kemudian mengubah direktori sekarang •

QGREP Cari file (s) untuk baris yang cocok dengan pola tertentu.

RASDIAL Mengelola koneksi RAS RASPHONE Mengelola koneksi RAS Recover Recover file yang rusak dari disk yang rusak. REG Registry: Read, Set, Export, dan nilai-nilai kunci Hapus REGEDIT Impor atau ekspor pengaturan registri regsvr32 Register or unregister DLL REGINI Change Registry Permissions REM Record komentar (komentar) dalam sebuah file batch • REN Mengganti nama file atau file • REPLACE Ganti atau memperbarui satu file dengan yang lain RD Hapus folder (s) • RMTSHARE Share folder atau printer yang Robocopy Robust File dan Folder Copy ROUTE Memanipulasi tabel routing jaringan RUNAS Jalankan program di bawah account pengguna yang berbeda RUNDLL32 Jalankan perintah DLL ( add / remove print connections)

SC Control Layanan SCHTASKS Jadwal untuk menjalankan perintah pada waktu tertentu SCLIST Tampilan NT Layanan SET Display, set, atau menghapus variabel lingkungan • SETLOCAL Pengendalian lingkungan visibilitas variabel • SETX Set variabel lingkungan secara permanen SFC Sistem File checker SAHAM Daftar atau mengedit file atau mencetak berbagi berbagi SHIFT Shift posisi digantikan parameter dalam sebuah file batch SHORTCUT jendela Buat shortcut (. LNK file) “Pintas”SHOWGRPS Daftar NT Workgroups seorang pengguna telah bergabung SHOWMBRS Daftar Pengguna yang menjadi anggota sebuah Workgroup SHUTDOWN Shutdown komputer Sleep Tunggu untuk x detik SLMGR Software Licensing Management (Vista/2008) SOON Jadwal perintah untuk menjalankan dalam waktu dekat SORT Sort input START Start a program atau perintah dalam jendela terpisah • SU Switch User SUBINACL Edit file dan folder Permissions, Kepemilikan dan Domain SUBST Associate path dengan huruf drive

systeminfo konfigurasi sistem Daftar

TASKLIST Daftar menjalankan aplikasi dan layanan yang berjalan TASKKILL Hapus proses dari memori TIME Tampilan atau mengatur waktu sistem • TIMEOUT Delay pemrosesan dari sebuah batch file TITLE Set judul jendela untuk sesi cmd.exe • TLIST daftar Tugas dengan path lengkap TOUCH Change file timestamps tracert Trace route to a remote host TREE Graphical tampilan struktur folder TYPE Menampilkan isi dari sebuah file teks •

USRSTAT Daftar domain nama pengguna dan login terakhir

VER informasi versi Tampilan • VERIFY verifikasi bahwa berkas telah disimpan • VOL Display a disk label •

WHERE Cari dan menampilkan file dalam pohon direktori whoami Keluaran UserName saat ini dan manajemen domain WINDIFF Membandingkan isi dua file atau set file WINMSD Windows diagnostik sistem WINMSDP sistem Windows diagnostik II WMIC WMI Commands x XCACLS Ubah hak akses file dan folder XCOPY Menyalin file dan folder:: Komentar / Catatan

Disadur dari : http://ss64.com/nt/

ADDUSERS.exe ( Resource Kit )

Automate the creation of a large number of users

Syntax Create Users: AddUsers /c filename [/s:x] [/?] Domain Password_options Dump to file: AddUsers /d{:u} filename [/s:x] [/?] Domain Password_options Erase Users: AddUsers /e filename [/s:x] [/?] Domain Password_options

key Filename - The comma-delimited file that AddUsers uses for data.

/s:x - Change the delimiter character used in filename to x. e.g. /s:~ would make the delimiter "~"

Domain - Query the Primary Domain Controller (PDC) of domain.

You can also use \\Servername to specify the machine where user accounts are created or read. AddUsers will use the local computer by default (if you do not specify Domain)

/c - Create user accounts, local groups, and global groups as specified by filename.

/d{:u} - Dump user accounts, local groups, and global groups to filename.The (:u) is an optional switch that causes current accounts to be written to the specified file in Unicode text format. Choosing to dump current user accounts does not save the account's passwords or any security information for the accounts.Note: Password information is not saved in a user account dump and if you use the same file to create accounts, all passwords of newly created accounts will be empty. To back up security information for accounts, use a Tape Backup.

/e - Erase the user accounts specified in the file name. CAUTION: Be careful when erasing user accounts, as it is not possible to recreate an account

with the same SID. This option will not erase built-in accounts. Password_options

/p: - Set account creation options, used along with any combination of the following:

* l - Users do not have to change passwords at next logon. * c - Users cannot change passwords. * e - Passwords never expire. (implies l option) * d - Accounts disabled. By default, all created users are required to change their password at logon.

Create a comma-delimited text file, which contains the new users to be created. Following the Syntax as follows: [Users]User Name,Full name, Password, Description, HomeDrive, Homepath, Profile, ScriptSave the file as C:\Users.txt and execute the commandAddUsers MyDomain /c c:\Users.txt /p:e

ATTRIB.exe

Display or change file attributes. Find Filenames.

Syntax ATTRIB [ + attribute | - attribute ] [pathname] [/S [/D]]

Key + : Turn an attribute ON - : Clear an attribute OFF

pathname : Drive and/or filename e.g. C:\*.txt /S : Search the pathname including all subfolders. /D : Process folders as well

attributes:

R Read-only (1) H Hidden (2) A Archive (32) S System (4)

extended attributes: E Encrypted C Compressed (128:read-only) I Not content-indexed L Symbolic link/Junction (64:read-only) N Normal (0: cannot be used for file selection) O Offline P Sparse file T Temporary

The numeric values may be used when changing attributes with VBS/WSH If no attribute is specified attrib will return the current attribute settings. Used with just the /S option ATTRIB will quickly search for a particular filename.

Hidden and System attributes take priority.

If a file has both the Hidden and System attributes set, you can clear both attributes only with a single ATTRIB command. For example, to clear the Hidden and System attributes for the RECORD.TXT file, you would type: ATTRIB -S -H RECORD.TXT

File Attributes

You can use wildcards (? and *) with the filename parameter to display or change the attributes for a group of files. Remember that, if a file has the System or Hidden attribute set, you must clear that attribute before you can change any other attributes.

Directory Attributes

You can display or change the attributes for a directory/folder. To use ATTRIB with a directory, you must explicitly specify the directory name; you cannot use wildcards to work with directories.

For example, to hide the directory C:\SECRET, you would type the following:

ATTRIB +H C:\SECRET

The following command would affect only files, not directories: ATTRIB +H C:*.*

The Read-only attribute for a folder is generally ignored by applications, however the Read-only and System attributes are used by Windows Explorer to determine whether the folder is a special folder, such as My Documents, Favorites, Fonts, etc. Setting the Read-Only attribute on a folder can affect performance, particularly on shared drives because Windows Explorer will be forced to request the Desktop.ini of every sub-folder to see if any special folder settings need to be set.

Viewing archive attributes

The Archive attribute (A) is used to mark files that have changed since they were previously backed up. The (A) flag is automatically updated by Windows as the file is saved.

If the (A) flag is present - the file is new or has been changed since the last backup.

The MSBACKUP, RESTORE, and XCOPY commands use these Archive attributes, as do many (but not all) 3rd party backup solutions.

Constants - the following attribute values are returned by the GetFileAttributes function:

FILE_ATTRIBUTE_READONLY = 1FILE_ATTRIBUTE_HIDDEN = 2FILE_ATTRIBUTE_SYSTEM = 4FILE_ATTRIBUTE_DIRECTORY = 16FILE_ATTRIBUTE_ARCHIVE = 32FILE_ATTRIBUTE_ENCRYPTED = 64FILE_ATTRIBUTE_NORMAL = 128FILE_ATTRIBUTE_TEMPORARY = 256FILE_ATTRIBUTE_SPARSE_FILE = 512FILE_ATTRIBUTE_REPARSE_POINT = 1024FILE_ATTRIBUTE_COMPRESSED = 2048FILE_ATTRIBUTE_OFFLINE = 4096FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192

"The moral sense of conscience is by far the most important.. it is the most noble of all the attributes of man" - Charles Darwin

BOOTCFG.exe

Edit the Windows boot settings stored in Boot.ini

Syntax BOOTCFG /addsw Add OS load options for an OS entry in boot.ini BOOTCFG /copy Duplicate the entries for an OS instance. BOOTCFG /dbg1394 Configure 1394 port debugging BOOTCFG /debug Edit the debug settings for an OS. BOOTCFG /default Specify the default OS BOOTCFG /delete Delete an OS entry [operating systems] section of Boot.ini BOOTCFG /ems Redirect the EMS console to a remote computer (server only). (Emergency Management Services) BOOTCFG /list List entries in boot.ini BOOTCFG /query Display section entries from Boot.ini BOOTCFG /raw Add OS load options, specified as a string BOOTCFG /rebuild Totally rebuild boot.ini (use when Windows won't start) BOOTCFG /rmsw Remove OS load options for an OS BOOTCFG /timeout Change the OS time-out value.

Detailed options for all the above are available from BOOTCFG /? Items in bold are only available from the recovery console

Default identification strings:

OS Load Options = /FastdetectLoad Identifier = Microsoft Windows XP Professional

If you intend to rebuild the boot.ini file, delete it first - boot into the recovery console then:

ATTRIB -H -R -S C:\Boot.ini DEL C:\Boot.ini Bootcfg /Rebuild

Fixboot

CHKDSK.EXE

Check Disk - check and repair disk problems

Syntax CHKDSK [drive:][[path]filename] [/F] [/V] [/R] [/L[:size]]

Key [drive:] The drive to check. filename File(s) to check for fragmentation (FAT only). /F Automatically Fix file system errors on the disk. /X Fix file system errors on the disk, (Win2003 and above) dismounts the volume first, closing all

open file handles. /R Scan for and attempt Recovery of bad sectors. /V Display the full path and name of every file on the disk. /L:size NTFS only: change the log file size to the specified number of kilobytes. If size is not specified,

displays the current log size and the drive type (FAT or NTFS). /C Skip directory corruption checks. /I Skip corruption checks that compare directory entries to the file record segment (FRS) in the

volume's master file table (MFT)

Example:

CHKDSK C: /F

Fixing Errors /F

If the drive is the boot partition, you will be prompted to run the check during the next boot If you specify the /f switch, chkdsk will show an error if open files are found on the disk.

Chkdsk /f will lock the volume, making data unavailable until chkdsk is finished. If you use chkdsk /f on a disk with a very large number of files (millions), chkdsk may take a long time to complete.

When you delete a file or folder that has 'custom' permissions, the ACL is not deleted, it is cached. Chkdsk /f will remove ACLs that are no longer used. This is often the cause of the rather worrying message: "Windows found problems with the file system. Run chkdsk with the /F (fix) option to correct these."

It is normal for chkdsk /F to remove unused index entries and unused security descriptors every time you run it, these do not indicate a problem with the file system.

Scan only (without /f switch)

If a file needs to be fixed chkdsk will alert you with a message but will not fix the error(s).

chkdsk may report lost allocation units on the disk - it will produce this report even if the files are in-use (open). If corruption is found, consider closing all files and repairing the disk with /F.

Running chkdsk on a data volume that is in use by another program or process may incorrectly report errors when none are present. To avoid this, close all programs or processes that have open handles to the volume.

On computers running Windows 2003 SP1, chkdsk automatically creates a shadow copy, so you can check volumes that are 'in use' by another program or process. This enables an accurate report against a live file server. On earlier versions of Windows, chkdsk would always lock the volume, making data unavailable.

Run at Bootup

Running at bootup is often the easiest way to close all open file handles.

Use the GUI, chkntfs or the FSUTIL dirty commands to set or query the volumes 'dirty' bit so that Windows will run chkdsk when the computer is restarted.

Event Logs

Chkdsk will log error messages in the Event Viewer - System Log. Chkdsk /f removes ACLs that are no longer used and reports this in the Event Viewer - Application Log.

Cluster (or block) Size

CHKDSK produces a report that shows the the block /cluster sizetypically: "4096 bytes in each allocation unit." When the cluster size is greater than 4 KB on an NTFS volume, none of the NTFS compression functions are available.

Exit codes

0 No errors were found1 Errors were found and fixed.2 Could not check the disk, did not or could not fix errors.

Notes:Consider the time required to run Chkdsk to repair any errors that occur. Chkdsk times are determined by the number of files on the volume and by the number of files in the largest folder. Chkdsk performance under Windows 2003 is around 30% faster than previous versions.

To issue chkdsk on a hard drive you must be a member of the Administrators group.

When CHKDSK is set to run at boot-up there is a delay to allow the check to be cancelled - this can be configured in the registry:

HKLM\System\CurrentControlSet\Control\Session ManagerREG_DWORD:AutoChkTimeOutDataThe value is the time in seconds that you want CHKDSK to wait (0 = no delay) default is 10 seconds.

"The file system structure on the disk is corrupt and unusable"

"I either want less corruption, or more chance to participate in it" - Ashleigh Brilliant

CHKNTFS.exe

Check the NTFS file system with CHKDSK

Syntax CHKNTFS drive: [...] CHKNTFS /C drive: [...] CHKNTFS /X drive: [...] CHKNTFS /t[:Time] CHKNTFS /D

Key drive : Specifies a drive letter.

/C : Check - schedules chkdsk to be run at the next reboot /X : Exclude a drive from the default boot-time check. Excluded drives are not accumulated between

command invocations. /T : Change the Autochk.exe initiation countdown time (time in seconds) If you don't specify Time:

displays the current countdown time. /D : Restore the machine to the default behavior; all drives are checked at boot time and chkdsk is run

on those that are dirty. This undoes the effect of the /X option.

If no switches are specified, CHKNTFS will display the status of the dirty bit for each drive. /T option is new in Win XP

"I don't make no dirty movements" - Elvis

CMD.exe

Start a new CMD shell

Syntax CMD [charset] [options] [My_Command]

Options /C Carries out My_Command and then terminates /K Carries out My_Command but remains

My_Command : The NT command, program or batch script to be run. This can even be several commands separated with '&&' (the whole should also be surrounded by "quotes")

/T:fg Sets the foreground/background colours /X Enable extensions to CMD.EXE under Windows 2000 you can also use /E:ON /Y Disable extensions to CMD.EXE under Windows 2000 you can also use /E:OFF /A Output ANSI Characters /U Output UNICODE Characters These 2 swiches are useful when piping or redirecting to a file Most common text files under

WinNT are ANSI, use these switches when you need to convert the character set.

more below

Win2K / XP switches

The CMD switches below were first introduced with Windows 2000

/D Ignore registry AutoRun commands HKLM | HKCU \Software\Microsoft\Command Processor\AutoRun /F:ON Enable auto-completion of pathnames entered at the CMD prompt /F:OFF Disable auto-completion of pathnames entered at the CMD prompt (default)

At the command prompt Ctrl-D gives folder name completion and Ctrl-F gives file and folder name completion.

These ctrl keys build up a list of paths that match and display the first matching path. Thereafter, repeated pressing of the same control key will cycle through the list of matching paths. Pressing SHIFT with the control key will move through the list backwards.

/Q Turn echo off

/S Strip quote characters from the command_line

/V:ON Enable delayed environment variable expansion this allows a FOR loop to specify !variable! instead of %variable% expanding the variable at execution time instead of at input time.

/V:OFF Disable delayed environment expansion.

Environment expansion preference can be set permanently in the registry HKLM | HKCU \Software\Microsoft\Command Processor\DelayedExpansion Set to either 0x1 or 0x0

/knetdiag /debug /knetdiag /fix

The knetdiag switches are undocumented and work in XP only they list and (may) fix these networking issues. If /C or /K is specified, then the remainder of the command line is processed as an immediate command in the new shell. Multiple commands separated by the command separator '&&' are accepted if surrounded by quotes.

The following logic is used to process quote (") characters:

1. If all of the following conditions are met, then quote characters on the command line are preserved:

- no /S switch - exactly two quote characters - no special characters between the two quote characters, where special is one of: &<>()@^| - there are one or more whitespace characters between the the two quote characters - the string between the two quote characters is the name of an executable file.

2. Otherwise, old behavior is to see if the first character is a quote character and if so, strip the leading character and remove the last quote character on the command line, preserving any text after the last quote character.

Command.com vs cmd.exe

All the commands on these pages assume you are running the 32 bit command line (cmd.exe)

CMD.exe is the NT/XP equivalent of Command.com in previous operating systems. The older 16 bit command processor command.com is supplied to provide backward compatibility for 16 bit DOS applications. e.g. command.com will fail to set %errorlevel% after certain commands.

To ensure that a batch file will not run if accidentally copied to a Windows 95/98 machine you should use the extension .CMD rather than .BAT

The COMSPEC environment variable will show if you are running CMD.EXE or command.com

Subject to licensing issues, it is possible to run the Windows 2000 or Win XP version of CMD.EXE under NT. This is not true of all commands, e.g. any command that involves NTFS disk access (such as cacls) should not be moved between OS versions.

Opening CMD from Windows Explorer

You can open a new CMD prompt by choosing START, RUN, cmd, OK

Registry Keys:

;Allow UNC paths at command prompt[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]"DisableUNCCheck"=dword:00000001

; Run a command when CMD.exe starts[HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor]"AutoRun"=-

; Activate Automatic Completion[HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor]"CompletionChar"=0x9

Previous Commands

Pressing the UP arrow will list previous commands entered at the command prompt. Other DOSKEY function keys are loaded by default (F7, F8, F9)

Copy and Paste

To simplify the use of cut and paste at the Command Prompt, enable QuickEdit mode as follows:

Activate the control menu at the top left of the current cmd window, go to Properties, Options tab and then tick against QuickEdit Mode.

Now you can select text with the mouse and hit Enter (or right click) to copy it to the clipboard. Paste anywhere using Control+V (or Right Click) or via the menu.

ESC will cancel any selection and return to editing mode. When copying between windows, you may need one click to select the window and a second click to paste.

Using CMD in a batch script

In a batch script CMD will start a new instance of CMD.exe which will appear in the same window. The EXIT command will close the second CMD instance and return to the previous shell.A method of calling one Batch script from another is to run a command like

CMD /c C:\docs\myscript.cmd

The output of CMD can be redirected into a text file. Notice that where 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

Pausing a batch scriptExecution of any batch script can be paused by pressing CTRL-SThis also works for pausing a single command such as a DIR listingPressing any key will resume the operation.

Stopping a batch script from runningExecution of any batch script can be stopped by pressing CTRL-C

If one batch file CALLs another batch file CTRL-C will exit both batch scripts.If CMD /c is used to call one batch file from another then CTRL-C will cause only one of the batch scripts to terminate. (see also EXIT)

Long CommandsUnder Windows NT, the command line is limited to 256 characters.Under Windows 2000, the command line is limited to 2046 characters. Under Windows XP, the command line is limited to 8190 characters.

For all OS's NTFS and FAT allows pathnames of up to 260 characters.

A workaround for the limited pathname length is to prefix \\?\ for example:\\?\C:\TEMP\Long_Directory\Long_Filename.txt

The above limits are often encountered when using long share names or drag and dropping files onto a batch script.

Full ScreenThe key combination ALT and ENTER will switch a CMD window to full screen mode. press ALT and ENTER again to return to a normal Window.

Command Extensions

Much of the functionality of CMD.exe can be disabled - this will affect all the internal commands, Command Extensions are enabled by default. This is controlled by setting a value in the registry: HKCU\Software\Microsoft\Command Processor\EnableExtensions Alternatively under Win XP you can run CMD /e:on or CMD /e:off

"Those who can command themselves, command others" - Hazlitt

COPY

Copy one or more files to another location

Syntax COPY source destination [options]

COPY source1 + source2.. destination [options]

Key source : Pathname for the file or files to be copied.

/A : ASCII text file (default) /B : Binary file copy - will copy extended characters.

destination : Pathname for the new file(s).

V : Verify that the new files were written correctly /N : If at all possible, use only a short filename (8.3) when creating a destination file. This may be

necessary when copying between disks that are formatted differently e.g NTFS and VFAT, or when archiving data to an ISO9660 CDROM

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

/Y : Suppress confirmation prompt (Windows 2000 only) /-Y : Enable confirmation prompt (Windows 2000 only)

Prompt to overwrite destination file

NT 4 will overwrite destination files without any prompt, Windows 2000 and above will prompt unless the COPY command is being executed from within a batch script.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)

Binary copies"COPY /B ... " will copy all the files in binary mode , you can also put /B after any one file to copy just that file in binary.

Combine files To combine files, specify a single file for the destination, but multiple files as the source. To specify more than one file use wildcards or list the files with a + in between each (file1+file2+file3)When copying multiple files in this way the first file must exist or else the copy will fail, a workaround for this is COPY null + file1 + file2 dest1

COPY will accept UNC pathnames

Copy from the console (accept user input)

COPY CON filename.txt Then type the input text followed by ^Z (Control key & Z)

To do this in Powershell use the following function:

function copycon {[system.console]::in.readtoend()}

Examples:

In the current folderCOPY oldfile.doc newfile.doc

Copy from a different folder/directory: COPY "C:\my work\some file.doc" "D:\New docs\newfile.doc"

Specify the source only, with a wildcard will copy all the files into the current directory:COPY "C:\my work\*.doc"

Specify the source with a wildcard and the destination as a single file, this is generally only useful with plain text files. COPY "C:\my work\*.txt" "D:\New docs\combined.txt"

Quiet copy (no feedback on screen)COPY oldfile.doc newfile.doc >nul

"Success seems to be connected with action. Successful men keep moving. They make mistakes, but they don't quit" - Conrad Hilton

DEFRAG (Windows XP)

Defragment hard drive.

Syntax DEFRAG <volume> [-a] [-f] [-v] [-?]

Options volume drive letter or mount point (d: or d:\vol\mountpoint) -a Analyze only -f Force defragmentation even if free space is low -v Verbose output

Example:DEFRAG c: -f

DEL

Delete one or more files.

Syntax DEL [options] [/A:file_attributes] files_to_delete

Key files_to_delete : This may be a filename, a list of files or a Wildcard

options /P Give a Yes/No Prompt before deleting. /F Ignore read-only setting and delete anyway (FORCE) /S Delete from all Subfolders (DELTREE) /Q Quiet mode, do not give a Yes/No Prompt before deleting.

/A Select files to delete based on file_attributes

file_attributes: R Read-only -R NOT Read-only S System -S NOT System H Hidden -H NOT Hidden A Archive -A NOT Archive

Wildcards: These can be combined with part of a filename

* Match any characters ? Match any ONE character

Examples:

To delete HelloWorld.TXTDEL HelloWorld.TXT

To delete "Hello Big World.TXT"DEL "Hello Big World.TXT"

To delete all files that start with the letter ADEL A*

To delete all files that end with the letter ADEL *A.*

To delete all files with a .DOC extensionDEL *.DOC

To delete all read only filesDEL /a:R *

To delete all files including any that are read onlyDEL /F *

FoldersIf a folder name is given instead of a file, all files in the folder will be deleted, but the folder itself will not be removed.

Temporary FilesYou should clear out TEMP files on a regular basis - this is best done at startup when no applications are running. To delete all files in all subfolders of C:\temp\ but leave the folder structure intact:

DEL /F /S /Q %TEMP%

When clearing out the TEMP directory it is not generally worthwhile removing the subfolders too - they don't use much space and constantly deleting and recreating them can potentially increase fragmentation within the Master File Table.

Deleting a file will not prevent third party utilities from un-deleting it again, however you can turn any file into a zero-byte file to destroy the file allocation chain like this:

TYPE nul > C:\examples\MyFile.txtDEL C:\examples\MyFile.txt

Undeletable Files

Files are sometimes created with the very long filenames or reserved names: CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, NUL To delete these use the syntax: DEL \\.\C:\somedir\LPT1Alternatively SUBST a drive letter to the folder containing the file.

If a file (or folder) still appears to be 'undeletable' this is often caused by the indexing service. Right click the file you need to delete, choose properties, advanced and untick "allow indexing" you will then be able to delete the file. To cure the problem permanently - Control Panel, Add/Remove programs, Win Accessories, indexing service.

DIR

Display a list of files and subfolders

Syntax DIR [pathname(s)] [display_format] [file_attributes] [sorted] [time] [options]

Key [pathname] The drive, folder, and/or files to display, this can include wildcards:

* Match any characters ? Match any ONE character

[display_format] /P Pause after each screen of data. /W Wide List format, sorted horizontally. /D Wide List format, sorted by vertical column.

[file_attributes] /A:

/A:D Folder /A:-D NOT Folder /A:R Read-only /A:-R NOT Read-only /A:H Hidden /A:-H NOT Hidden /A:A Archive /A:-A NOT Archive /A Show all files several attributes may be combined e.g. /A:HD-R

[sorted] Sorted by /O:

/O:N Name /O:-N Name /O:S file Size /O:-S file Size

/O:E file Extension /O:-E file Extension /O:D Date & time /O:-D Date & time /O:G Group folders first /O:-G Group folders last several attributes may be combined e.g. /O:GEN

[time] /T: the time field to display & use for sorting

/T:C Creation /T:A Last Access /T:W Last Written (default)

[options] /S include all subfolders. /R Display alternate data streams. (Vista only) /B Bare format (no heading, file sizes or summary). /L use Lowercase. /Q Display the owner of the file. /N long list format where filenames are on the far right. /X As for /N but with the short filenames included. /C Include thousand separator in file sizes. /-C don't include thousand separator in file sizes. /4 Display four-digit years

The switches above may be preset by adding them to an environment variable called DIRCMD. For example: SET DIRCMD=/O:N /S

Override any preset DIRCMD switches by prefixing the switch with - For example: DIR *.* /-S

Upper and Lower Case filenames: Filenames longer than 8 characters - will always display the filename with mixed case as entered.Filenames shorter than 8 characters - may display the filename in upper or lower case - this may vary from one client to another (registry setting)

To obtain a bare DIR format (no heading or footer info) but retain all the details, pipe the output of DIR into FIND, this assumes that your date separator is /

DIR c:\temp\*.* | FIND "/"

FOR /f "tokens=*" %%G IN ('dir c:\temp\*.* ^| find "/"') DO echo %%G

Normally DIR /b will return just the filename, however when displaying subfolders with DIR /b /s the command will return a full pathname. Checking filesize during a download (to monitor progress of a large download)

TYPE file_being_downloaded >NUL DIR file_being_downloaded

Since TYPE won't lock the file_being_downloaded in any way, this doesn't pose a threat to the download itself.

"There it was, hidden in alphabetical order" - Rita Holt

DISKCOPY.com

Copy the content of one floppy disk to another.

Syntax DISKCOPY flopppy_drive1: floppy_drive2: [/V]

Key /V Verify that the information was copied correctly.

The two disks must be the same type, e.g. both 1.44 Mb or both 720 K

If you specify the same drive letter for floppy_drive1 and floppy_drive2 - you will be prompted to enter each disk.DISKCOMP A: A:

"The great secret that all old people share is that you really haven't changed in seventy or eighty years. Your body changes, but you don't change at all. And that, of course, causes great confusion." - Doris Lessing

EXIT

Quit the current batch script, quit the current subroutine or quit the command processor (CMD.EXE) optionally setting an errorlevel code.

Syntax EXIT [/B] [exitCode]

Key/B When used in a batch script, this option will exit only the script (or subroutine) but not

CMD.EXE

exitCode Sets the %ERRORLEVEL% to a numeric number. If quitting CMD.EXE, set the process exit code no.

You should never attempt to directly write to the %errorlevel% variable, (i.e. don't try anything like SET errorlevel...) using the EXIT command provides a safe way to alter the value of the built-in errorlevel variable.

EXPAND

Uncompress one or more compressed files.

Syntax EXTRACT [options] CAB_file [filenames]

Key CAB_file : Cabinet file

filenames : Name of the file to extract from the cabinet Wild cards (*.*) (.) and multiple files are valid

options

/A Process ALL cabinets. (where CABs are linked) /C If the CAB contains one file then /C will copy from DMF disks /D Display CAB directory /E Extract all (use instead of *.* to extract all files) /L dir Location to place extracted files (default is current folder) /Y Overwrite files without any prompt

FC.exe

Compare the contents of two files or sets of files. Display any lines which do NOT match.

Syntax FC /B pathname1 pathname2 FC [options] pathname1 pathname2

Key /B : Perform a binary comparison.

options /C : Do a case insensitive string comparison

/A : Displays only first and last lines for each set of differences./U : Compare files as UNICODE text files./L : Compares files as ASCII text. (default)/N : Display line numbers (ASCII only)/LBn : Limit the number of lines that will be read, "n" sets a maximum number of mismatches

after which the File Comparison will abort (resync failed) When FC aborts (resync failed) then "n" number of mismatches will be shown.

/nnnn : Specify a number of consecutive lines that must match after a mismatch. This can be used to prevent the display of the two files from getting too out of sync

/T : Do not expand tabs to spaces./W : Compress white space (tabs and spaces) for comparison.

To compare sets of files, use wildcards in pathname1 and pathname2 parameters.

Powershell also has an Alias FC for the Format-Custom command, therefore to run the 'old' FC under powershell you need to explicitly run C:\windows\system32\fc.exe

To identify 2 identical files use this syntax:

FC file1.txt file2.txt | FIND "FC: no dif" > nul IF ERRORLEVEL 1 goto :s_files_are_different

FORMAT.com

Format a disk for use with Windows.

Syntax FORMAT drive: [/FS:file-system] [/V:label] [/Q] [size] [/C]

Key /FS:file-system The file system (FAT or NTFS). The NTFS file system does not function on

floppy disks. /V:label The volume label. /Q Quick format. /C Compression - files added to the new disk will be compressed.

[size] may be defined either with /F:size or /A:size

/F:size size is the size of the floppy disk (720, 1.2, 1.44, 2.88, or 20.8).

/A:size Allocation unit size. Default settings (via /F) are strongly recommended for general use. NTFS supports 512, 1024, 2048, 4096, 8192, 16K, 32K, 64K. FAT supports 8192, 16K, 32K, 64K, 128K, 256K. NTFS compression is not supported for allocation units above 4096.

Example

@echo offEcho Warning this will reformat the entire D: disk!PAUSEformat D: /FS:NTFS /x

"The disks had a recording density of 1,100 bits per inch, and could move data out of the drive at 77 kilobytes per second" - Early hard drive specs.

FTP

File Transfer Protocol

Syntax FTP [-options] [-s:filename] [-w:buffer] [host]

key -s:filename Run a text file containing FTP commands. host Host name or IP address of the remote host. -g Disable filename wildcards. -n No auto-login. -i No interactive prompts during ftp. -v Hide remote server responses. -w:buffer Set buffer size to buffer (default=4096) -d Debug -a Use any local interface when binding data connection.

Commands to run at the FTP: prompt

append local-file [remote-file] Append a local file to a file on the remote computer.

ascii Set the file transfer type to ASCII, the default. In ASCII text mode, character-set and end-of-line characters are converted as necessary.

bell Toggle a bell to ring after each command. By default, the bell is off.

binary Set the file transfer type to binary. Use `Binary' for transferring executable program files or binary data files e.g. Oracle

bye End the FTP session and exit ftp

cd Change the working directory on the remote host.

close End the FTP session and return to the cmd prompt.

debug Toggle debugging. When debug is on, FTP will display every command.

delete remote-file Delete file on remote host.

dir [remote-directory] [local-file] List a remote directory's files and subdirectories. (or save the listing to local-file)

disconnect Disconnect from the remote host, retaining the ftp prompt.

get remote-file [local-file] Copy a remote file to the local PC.

glob Toggle the use of wildcard characters in local pathnames. By default, globbing is on.

hash Toggle printing a hash (#) for each 2K data block transferred. By default, hash mark printing is off.

help [command] Display help for ftp command.

lcd [directory] Change the working directory on the local PC. By default, the working directory is the directory in which ftp was started.

literal argument [ ...] Send arguments, as-is, to the remote FTP host.

ls [remote-directory] [local-file] List a remote directory's files and folders. (short format)

mdelete remote-files [ ...] Delete files on remote host.

mdir remote-files [ ...] local-file Display a list of a remote directory's files and subdirectories. (or save the listing to local-file) Mdir allows you to specify multiple files.

mget remote-files [ ...] Copy multiple remote files to the local PC.

mkdir directory Create a directory on the remote host.

mls remote-files [ ...] local-file List a remote directory's files and folders. (short format)

mput local-files [ ...] Copy multiple local files to the remote host.

open computer [port] Connects to the specified FTP server.

prompt Toggle prompting. Ftp prompts during multiple file transfers to allow you to selectively retrieve or store files; mget and mput transfer all files if prompting is turned off. By default, prompting is on.

put local-file [remote-file] Copy a local file to the remote host.

Pwd Print Working Directory (current directory on the remote host)

quit End the FTP session with the remote host and exit ftp.

quote argument [ ...] Send arguments, as-is, to the remote FTP host.

recv remote-file [local-file] Copy a remote file to the local PC.

remotehelp [command] Display help for remote commands.

rename filename newfilename Rename remote files.

rmdir directory Delete a remote directory.

send local-file [remote-file] Copy a local file to the remote host.

status Display the current status of FTP connections and toggles.

trace Toggles packet tracing; trace displays the route of each packet

type [type-name] Set or display the file transfer type: `binary' or `ASCII' (the default)If type-name is not specified, the current type is displayed. ASCII should be used when transferring text files. In ASCII text mode, character-set and end-of-line characters are converted as necessary. Use `Binary' for transferring executable files.

user user-name [password] [account] Specifes a user to the remote host.

verbose Toggle verbose mode. By default, verbose is on.

! command Run command on the local PC.

? [command] Display help for ftp command.

Examplesan example FTP Script to retrieve files in binary and then ascii mode:

::GetFiles.ftp

[User_id] [ftp_password] binary get /usr/file1.exe get file2.html mget *.jpeg ascii mget *.txt quit

To run the above script:FTP -s:GetFiles.ftp [hostname]This will connect as the user:User_id with password:ftp_password

An FTP Script to publish files in binary mode:

::PutFiles.ftp

[User_id] [ftp_password] binary mput *.html cd images mput *.gif quit

To run the above script:FTP -s:PutFiles.ftp [hostname]This will connect as the user:User_id with password:ftp_password

Using the Windows GUI for FTP

Windows Explorer (not Internet Explorer) also has a built in FTP client. Type in the address bar: ftp://[email protected] you will be prompted for the password.

You can also do ftp://username:[email protected] is not recommended as anyone can read the password.

Secure FTP

Standard FTP does not encrypt passwords - they are sent across the network in plain text. A more secure method is to use SecureFTP (SFTP) or SecureCopy (SCP) Freeware clients are available e.g. WinSCP

"Only wimps use tape backup: _real_ men just upload their important stuff on ftp, and let the rest of the world mirror it" - Linus Torvalds

GOTO

Direct a batch program to jump to a labelled line.

Syntax GOTO label

Keylabel : a predefined label in the batch program. Each label must be on a line by itself, beginning

with a colon.

To exit a batch script file or exit a subroutine specify GOTO:eof this will transfer control to the end of the current batch file, or the end of the current subroutine.

Examples:

IF %1==12 GOTO MySubroutine Echo the input was NOT 12goto:eof

:MySubroutineEcho the input was 12goto:eof

Use a variable as a label

CHOICE /C:01 /m choose [Y]yes or [N]No goto s_routine_%ERRORLEVEL%

:s_routine_0 Echo You typed Y for yesgoto:eof

:s_routine_1Echo You typed N for nogoto:eof

IF

Conditionally perform a command.

File syntax IF [NOT] EXIST filename command IF [NOT] EXIST filename (command) ELSE (command)

String syntax IF [/I] [NOT] item1==item2 command IF [/I] item1 compare-op item2 command IF [/I] item1 compare-op item2 (command) ELSE (command)

Error Check Syntax IF [NOT] DEFINED variable command IF [NOT] ERRORLEVEL number command IF CMDEXTVERSION number command

key

item : May be a text string or an environment variable a variable may be modified using either Substring syntax or Search syntax

command : The command to perform NOT : perform the command if the condition is false. == : perform the command if the two strings are equal. /I : Do a case Insensitive string comparison.

compare-op : may be one of EQU : equal NEQ : not equal

LSS : less than < LEQ : less than or equal <=

GTR : greater than > GEQ : greater than or equal >=

This 3 digit syntax is necessary because the > and < are recognised as redirection symbols

IF EXIST filename will return true if the file exists (this is not case sensitive). IF ERRORLEVEL statements should be read as IF Errorlevel >= number i.e.IF ERRORLEVEL 0 will return TRUE when the errorlevel is 64 IF ERRORLEVEL 1 will return TRUE when the errorlevel is 2 IF ERRORLEVEL 1 will return FALSE when the errorlevel is 0

Examples:

IF EXIST C:\install.log (echo complete) ELSE (echo failed) IF DEFINED _department ECHO Got the department variableIF DEFINED _commission SET /A _salary=%_salary% + %_commission% IF CMDEXTVERSION 1 GOTO start_processIF ERRORLEVEL EQU 2 goto sub_problem2

Does %1 exist?

To test for the existence of a command line parameter - use empty brackets like this

IF [%1]==[] ECHO Value MissingorIF [%1] EQU [] ECHO Value Missing

In the case of a variable that may be NULL - a null variable will remove the variable definition altogether, so testing for NULLs becomes easy:

IF NOT DEFINED _example ECHO Value MissingIF DEFINED will return true if the variable contains any value (even if the value is just a space)

Test the existence of files and folders

IF EXIST name - will detect the existence of a file or a folder - the script empty.cmd will show if the folder is empty or not.

Brackets

You can improve the readability of a batch script by writing a complex IF...ELSE command over several lines using brackets e.g. :

IF EXIST filename (del filename) ELSE ( echo The file was not found.)

The IF statement does not use any great intelligence when evaluating Brackets, so for example the command below will fail:

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

This version will work:

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

Testing Numeric values

Do not use brackets or quotes when comparing numeric values e.g. IF (2) GEQ (15) echo "bigger" orIF "2" GEQ "15" echo "bigger"These will perform a character comparison and will always echo "bigger" however the commandIF 2 GEQ 15 echo "bigger" Will perform a numeric comparison and works as expected - notice that this behaviour is exactly opposite to the SET /a command where quotes are required.

Any test made using the compare-op syntax will always be a "string" comparison,so when comparing numbers note that "026" > "26"

Wildcards

Simple wildcards are not supported by IF, so ==SS6* will not match SS64

The workaround is to spoof a wildcard using SET to retrieve the substring SET _part_name=%COMPUTERNAME:~0,3% IF NOT %_part_name%==SS6 GOTO they_matched

Pipes

When piping commands, the expression is evaluated from left to right, so

IF... | ... is equivalent to (IF ... ) | ...

you can also use the explicit syntax IF (... | ...)

ERRORLEVEL

To deliberately raise an ERRORLEVEL in a batch script use the EXIT /B command.

It is possible (though not a good idea) to create a string variable called %ERRORLEVEL% (user variable)if present such a variable will prevent the real ERRORLEVEL (a system variable) from being used by commands such as ECHO and IF.

To test for the existence of a user variable use SET errorlevel, or IF DEFINED ERRORLEVEL

If Command Extensions are disabled IF will only support direct comparisons: IF ==, IF EXIST, IF ERRORLEVEL also the system variable CMDEXTVERSION will be disabled.

You see things; and you say 'Why?' But I dream things that never were; and I say 'why not?' - George Bernard Shaw

IPCONFIG

Configure IP (internet protocol configuration)

Syntax IPCONFIG /all Display full configuration information. IPCONFIG /release [adapter] Release the IP address for the specified adapter.

IPCONFIG /renew [adapter] Renew the IP address for the specified adapter. IPCONFIG /flushdns Purge the DNS Resolver cache. IPCONFIG /registerdns Refresh all DHCP leases and re-register DNS names. IPCONFIG /displaydns Display the contents of the DNS Resolver Cache. IPCONFIG /showclassid adapter Display all the DHCP class IDs allowed for adapter.

IPCONFIG /setclassid adapter [classid] Modify the dhcp class id.

If the Adapter name contains spaces, use quotes: "Adapter Name" wildcard characters * and ? allowed, see the examples belowThe default is to display only the IP address, subnet mask and default gateway for each adapter bound to TCP/IP.For Release and Renew, if no adapter name is specified, then the IP address leases for all adapters bound to TCP/IP will be released or renewed.

For Setclassid, if no ClassId is specified, then the ClassId is removed.

Examples: > ipconfig ... Show information. > ipconfig /all ... Show detailed information > ipconfig /renew ... renew all adapters > ipconfig /renew EL* ... renew any connection that has its name starting with EL > ipconfig /release *Con* ... release all matching connections,

eg. "Local Area Connection 1" or "Local Area Connection 2"

> ipconfig /setclassid "Local Area Connection" TEST ... set the DHCP class ID for the named adapter to = TEST

"Life is a grand adventure - or it is nothing." - Helen Keller

KILL ( Resource kit )

Remove a running process from memory.

Syntax KILL [option] process_id KILL [option] task_name KILL [option] window_title

Option -f Force process kill

Note:

Kill -f basically just nukes the process from existence, potentially leaking a lot of memory and losing any data that the process hadn't committed to disk yet. It is there for worst case scenarios - when you absolutely must end the process now, and don't care whether proper cleanup gets done or not.In WindowsXP, KILL is replaced with the superior TASKKILL - Allowing you to specify a remote computer, different user account etc - for more details run TASKKILL /?

If you're going to tell people the truth, you'd better make them laugh. Otherwise they'll kill you. - George Bernard Shaw

LABEL

Edit a disk label.

Syntax LABEL [drive:][label]

The disk label is never referred to by other batch commands, it's just for human recognition.

LOGOFF.exe ( Resource Kit )

Log a user off.

Syntax LOGOFF [/f] [/n]

Key /f Force running processes to close, but will ask for user confirmation. The user will not be

asked to save unsaved data.

/n Force running processes to close without confirmation. The user will be prompted to save unsaved data.

By default LOGOFF will ask for user confirmation and prompt to save unsaved data.

Windows security log events

Logon Event IDs 528 and 540 = successful logon

Logoff Event ID 538 = logoff

Logon and logoff events also specify a Logon Type code:

Logon Type 2 – Interactive - Log on at the local keyboard / screen (see the event description for a computer name).

Logon Type 3 – Network - connections to shared folders or printers, over-the-network logons, IIS logons( but not basic authentication)Logon Type 4 – Batch - The Scheduled Task service creates a new logon session for each task.

Logon Type 5 – Service - Each service is configured to run as a specified user account.

Logon Type 7 – Unlock- a password protected screen saver.

Logon Type 8 – NetworkCleartext - a network logon like logon type 3 but where the password was sent over the network in clear text.

Logon Type 9 – NewCredentials - If you use RunAs /netonly and records the logon event with logon type 2.

Logon Type 10 – RemoteInteractive - Terminal Services, Remote Desktop or Remote Assistance.

Logon Type 11 – CachedInteractive - mobile users not connected to the network connecting with cached credentials.

"The man who is tired of London is tired of looking for a parking space" - Paul Theroux

MEM

Display memory usage.

Syntax MEM MEM /C MEM /D MEM /P

Key /P List programs in memory with the memory address and size of each /D List Programs(as /P) and also Devices /C List programs in conventional memory and list programs in upper memory

MEM will only display details about the current CMD shell environment, programs running in a separate shell (or WIN32 programs) will not be listed - so it won't tell you anything about total memory usage.

MD

Make Directory - Creates a new folder.

Syntax MD [drive:]path

Key The path can consist of any valid characters up to the maximum path length available, You should avoid using the following characters in folder names - they are known to cause problems

© ® " - & ' ^ ( ) and @

also many extended characters may not be recognised by older 16 bit windows applications.The maximum length of a full pathname (folders and filename) under NTFS or FAT is 260 characters. Folder names are not case sensitive, but only folder names longer than 8 characters will always retain their case, as typed.

For ExampleC:\temp> MD MyFolder

Make several folders with one command

C:\temp> MD Alpha Beta Gamma

will create

C:\temp\Alpha\C:\temp\Beta\C:\temp\Gamma\

Make an entire path MD creates any intermediate directories in the path, if needed. For example, assuming \utils does not exist then:

MD \utils\downloads\Editor is the same as: md \utils cd \utils md downloads cd downloads md Editor

for long filenames include quotes

MD "\utils\downloads\Super New Editor"

You cannot create a folder with the same name as any of the following devices: CON, PRN, LPT1, LPT2 ..LPT9, COM1, COM2 ..COM9 This limitation ensures that redirection to these devices will always work.If you plan to copy data onto CDROM avoid folder trees more than 8 folders deep

MKDIR is a synonym for MD

"We are American at puberty. We die French" - Evelyn Waugh

MORE

Display output one screen at a time. MORE can be used to run any executable command (or batch file) and pause the screen output one screen at a time. MORE can also be used to TYPE the contents of any file to the screen.

Syntax command | MORE [/E [/C] [/P] [/S] [/Tn] [+n]]

MORE [/E [/C] [/P] [/S] [/Tn] [+n]] < Pathname MORE /E [/C] [/P] [/S] [/Tn] [+n] [Pathname(s)]

Key command : Any executable command or batch file Pathname : The file to be displayed. (if more than one separate with spaces) /E : Enable extended features /E /C : Clear screen before displaying page /E /P : Expand FormFeed characters /E /S : Squeeze multiple blank lines into a single line /E /Tn : Expand tabs to n spaces (default 8) /E +n : Start displaying the first file at line n

You can create an environment variable called %MORE% and use this to supply any of the above switches.When MORE is used without any redirection symbols it will display the % complete e.g.:

MORE /E myfile.txt--More (17%) --

If extended features are enabled, (/E) the following keystrokes can be used at the -- More -- prompt:

<space> Display next page <return> Display next line Q Quit P n Display next n lines S n Skip next n lines F Display next file = Show line number ? Show help line

"less is more" - Ludwig Mies van der Rohe

MOVE

Move a file from one folder to another

Syntax MOVE [options] [Source] [Target]

Key source : The path and filename of the file(s) to move. target : The path and filename to move file(s) to.

options: (Windows 2000 only) /Y Suppress confirmation prompt. /-Y Enable confirmation prompt.

Both Source and Target may be either a folder or a single file.

The source may include wildcards (but not the destination).

Under Windows 2000 the default action is to prompt on overwrites unless the command is being executed from within a batch script. To force the overwriting of destination files under both NT4 and Windows2000 use the COPYCMD environment variable:SET COPYCMD=/YThis will turn off the prompt in Win2000 and will be ignored by NT4 (which overwrites by default).

MOVEUSER.exe ( Resource Kit )

Move a local user account into a domain or move a user account between machines.

Syntax MOVEUSER [DOMAIN/]user1 [DOMAIN/]user2 [/c:computer] [/k] [/y]

Key:

user1 The existing user (who has a local profile) Specify domain users in 'DOMAIN/user' format or just 'user' for a local account.

user2 The user acount that will inherit the user1 profile. This account must already exist. Specify domain users in DOMAIN/user format specify only user for

local accounts.

/c:computer The computer on which to make the changes. /k Keep user account user1 (only applies to local users) /y Overwrite an existing profile for user2.

To use MOVEUSER, you must be logged in with admin rights to create and modify user accounts on both the source and target machine.

Examples

MOVEUSER fred MyDomain\newfred

Or if the account 'fred' is on the remote PC called 'wks0123'

MOVEUSER fred MyDomain\newfred /c:\\wks0123

MSG.exe

Send a pop-up message to a user. The 'Home' editions of Windows don’t include MSG.

Syntax MSG username [options] [message] MSG sessionname [options] [message] MSG sessionid [options] [message] MSG @filename [options] [message] MSG * [options] [message]

Options

/SERVER:servername The server to contact (default is current). /TIME:seconds Time delay to wait for receiver to acknowledge msg. /V Verbose, display extra information. /W Wait for response from user, useful with /V.

If no message text to send is specified, MSG will prompt for it (also reads from stdin)

@filename identifies a file containing a list of usernames, sessionnames or sessionids to send the message to. * will send the message to all sessions on the server. e.g. use this for Terminal Server/Citrix shutdown messages.

MSTSC

Terminal Server Connection, RDP (Remote Desktop Protocol)

Syntax MSTSC option MSTSC /Edit"ConnectionFile" MSTSC /migrate

Options ConnectionFile The name of an RDP file for connection /v:<server[:port]> The remote computer to connect to /console Connect to the console of a server (NT/XP) /Admin Connect to a session for administering the server(Vista/2008) /f Start in Full Screen mode /w:width Width of the RDP screen /h:height Height of the RDP screen /span Match the Remote Desktop width and height with the local virtual desktop,

spanning across multiple monitors if necessary.(Vista/2008) /public Run Remote Desktop in public mode. (Vista/2008) In public mode, passwords

and bitmaps are not cached. /edit Open the RDP file for editing. /migrate Convert a legacy Client connection file into an .RDP file

The /console option only works when connecting to an Windows XP Professional or Windows Server 2003 computer.

When connected to a remote desktop, the key combination Ctrl-Alt-END will send Ctrl-Alt-Del to the remote client.

Examples:

MSTSC /v:MyServer /f /console

MSTSC /v:127.0.0.1 /w:1024 /h:768MSTSC /v:MyServer /w:800 /h:600MSTSC /edit filename.rdp

On the Windows XP CD, under \SUPPORT\TOOLS you'll find MSRDPCLI.exe. This is the setup for use with 9.x/2000 machines.

"Ignorance is preferable to error; and he is less remote from the truth who believes nothing, than he who believes what is wrong" - Thomas Jefferson

MSIEXEC

Microsoft Windows Installer.

Syntax Install MSIEXEC /i package options Uninstall MSIEXEC /x package options Advertise to current user MSIEXEC /ju package options [/t Transform_List | /g LanguageID] Advertise to all users MSIEXEC /jm package options [/t Transform_List | /g LanguageID] Administrative install - install on the network. MSIEXEC /a package Apply a patch to an installed Admin image MSIEXEC /p patchPKG /a package

Options: /fp fix - replace missing files /fo fix - replace Older files /fe fix - replace older or Equal date files /fd fix - replace Different version files /fc fix - replace files based on Checksum differences /fa fix - replace All files /fu fix - rewrite HKCU registry /fm fix - rewrite HKLM registry /fs fix - recreate shortcuts /fv fix - rewrite local cache from source /l* Logfile Log Everything (not Verbose) /l*v Logfile Log Everything Verbose /lv Logfile Log Verbose /le Logfile Log All error messages /lw Logfile Log Non-fatal warnings /li Logfile Log Status messages /la Logfile Log Startup actions /lr Logfile Log Actions /lu Logfile Log User requests /lc Logfile Log User Interface (UI) parameters /lm Logfile Log memory use /lp Logfile Log Terminal properties /l+ Logfile Append to an existing log file. /l! Logfile Clear an existing log file. /q , /qn No UI. /qb Basic UI. /qb! Basic UI with no cancel button. /qr Reduced UI. A modal dialog box is displayed at the end of the install. /qf Full UI. A modal dialog box is displayed at the end of the install. /qn+ No UI. However, a modal dialog box is displayed at the end of the installation. /qb+ Basic UI. A modal dialog box is displayed at the end of the installation. If you cancel the

installation, a modal dialog box is not displayed. /qb- Basic UI with no modal dialog boxes. /y module Register a DLL - only use for registry information that cannot be added using the

registry tables of the .msi file. /z module UnRegister a DLL - only use for registry information that cannot be removed using the

registry tables of the .msi file.

Windows installer versions

Windows NT can support version 1.1 or version 1.2Windows 2K includes version 1.1Windows XP Sp1 /Server 2003 include version 2.0Windows XP SP2 includes version 3.0

"People don't resist change. They resist being changed!" - Peter Senge.

NETSTAT.exe

Display current TCP/IP network connections and protocol statistics.

Syntax NETSTAT [options] [-p protocol] [interval]

Key -a Display All connections and listening ports. -e Display Ethernet statistics. (may be combined with -s) -n Display addresses and port numbers in Numerical form. -r Display the Routing table. -o Display the Owning process ID associated with each connection. -b Display the exe involved in creating each connection or listening port.* -v Verbose - use in conjunction with -b, to display the sequence of components involved for all executables. -p protocol Show only connections for the protocol specified; maybe any of: TCP, UDP, TCPv6 or

UDPv6. If used with the -s option then the following protocols may also be specified: IP, IPv6,

ICMP,or ICMPv6.

-s Display per-protocol statistics. By default, statistics are shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPv6; (The v6 protocols are not available under 2k and NT4) The -p option may be used to display just a subset of these.

interval Redisplay statistics, pausing interval seconds between each display. (default=once only) Press CTRL+C to stop.

PATH

Display or set a search path for executable files

Syntax PATH pathname [;pathname] [;pathname] [;pathname]... PATH PATH ;

Key pathname : drive letter and/or folder; : the command 'PATH ;' will clear the path

PATH without parameters will display the current path.

The %PATH% environment variable contains a list of folders. When a command is issued at the CMD prompt, the operating system will first look for an executable file in the current folder, if not found it will scan %PATH% to find it.

Use the PATH command to display or change the list of folders stored in the %PATH% environment variable.To view each item on a single line use this:

for %G in ("%path:;=" "%") do @echo %G

Or in a batch file:

for %%G in ("%path:;=" "%") do @echo %%G

To add items to the current path, include %PATH% in your new setting. For Example:

PATH=%PATH%;C:\Program Files\My Application

Note you do not need to surround each part of the path with double quotes, PATH will always treat spaces as part of the filename.

Permanent Changes

Changes made using the PATH command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed.

T o permanently change the PATH use

Control Panel, System, Environment, System VariablesControl Panel, System, Environment, User Variables

The %PATH% variable is set as both a system and user variable, the 2 values are combined to give the PATH for the currently logged in user. This is explained in full by MS Product Support Article Q100843

Be wary of using commands like SETX to modify the PATH - the User path can be edited, but the System path remains read-only for most users. If you try to delete an old value and add a new one it is very common for the 'delete' to fail and the 'add' to succeed, resulting in duplicate values being added to the path.

If you are trying to modify the path to add settings for a single application, a reasonably safe method is to use a second variable: e.g.

SetX MYAPP "C:\Program Files\My App" -m

Now include your new variable in the path like so ...C:\Windows\system32;%MYAPP%

You can now easily change that one variable %MYAPP% at any time in the future and the PATH will reflect the new value.

Changing a variable in the Control Panel will not affect any CMD prompt that is already open, only new CMD prompts will get the new setting.

To change a system variable you must have administrator rights

If your system has an AUTOEXEC.BAT file then any PATH setting in AUTOEXEC.BAT will also be appended to the %PATH% environment variable. This is to provide compatibility with old installation routines which need to set the PATH. All other commands in AUTOEXEC.BAT are ignored.

Terminology

For a file stored as:C:\Program Files\Adobe\Acrobat.exeThe Drive is:C:The Filename is:Acrobat.exeThe Path is:Program Files\Adobe\

The Pathname is:\Program Files\Adobe\Acrobat.exeThe Full Pathname isC:\Program Files\Adobe\Acrobat.exe

"If you do not love your job, change it. Instead of pushing paper, push ideas. Instead of sitting down, stand up and be heard. Instead of complaining, contribute. Don't get stuck in a job description" - Microsoft job advert

PING

Test a network connection - if successful, ping returns the ip address.

Syntax

PING [options] destination_host

Options -w timeout Timeout in milliseconds to wait for each reply. -i TTL Time To Live. -v TOS Type Of Service. -a Resolve addresses to hostnames. -n count Number of echo requests to send. -t Ping the destination host until interrupted. -l size Send buffer size. -f Set Don't Fragment flag in packet. -r count Record route for count hops. -s count Timestamp for count hops. -j host_list Loose source route along host_list. -k host_list Strict source route along host_list.destination_host The name of the remote host

A response of "Request timed out" means there was no response to the ping attempt in the default time period of one second. If the latency of the response is more than one second. Use the -w option on the ping command to increase the time-out. For example, to allow responses within five seconds, use ping -w 5000.

A successful PING does NOT always return an %errorlevel% == 0Therefore to reliably detect a successful ping - pipe the output into FIND and look for the text "TTL"

Note that "Reply" in the output of PING does not always indicate a positive response. You may receive a message from a router such as: Reply from 192.168.1.254: Destination Net Unreachable.

Four steps to test an IP connection with ping:

1) Ping the loopback address to verify that TCP/IP is installed and configured correctly on the local computer. PING 127.0.0.1

2) Ping the IP address of the local computer to verify that it was added to the network correctly. PING IP_address_of_local_host

3) Ping the IP address of the default gateway to verify that the default gateway is functioning and that you can communicate with a local host on the local network. PING IP_address_of_default_gateway

4) Ping the IP address of a remote host to verify that you can communicate through a router. PING IP_address_of_remote_host

Examples

PING -n 1 -w 7500 Server_06PING -w 7500 MyHost |find "TTL=" && ECHO MyHost foundPING -w 7500 MyHost |find "TTL=" || ECHO MyHost not foundPING -n 5 -w 7500 www.microsoft.comPING -n 5 -w 7500 microsoft.com

PING is named after the sound that a sonar makes.

Ping times below 10 milliseconds often have low accuracy.

A time of 10 milliseconds is roughly equal to a distance of 930 Miles, travelling a straight line route at the speed of light.

"And now I see with eye serene The very pulse of the machine." - William Wordsworth, (She Was a Phantom of Delight)

PROMPT

Change the cmd.exe command prompt.

Syntax

PROMPT [text] Key text : a text string.

The prompt text can be made up of normal characters and the following special codes:

$A & (Ampersand) $B | (pipe) $C ( (Left parenthesis) $D Current date $E Escape code (ASCII code 27) $F ) (Right parenthesis) $G > (greater-than sign) $H Backspace (erases previous character) $L < (less-than sign) $M Display the remote name for Network drives $N Current drive $P Current drive and path $Q = (equal sign) $S (space) $T Current time $V Windows NT version number $_ Carriage return and linefeed $$ $ (dollar sign) $+ Will display plus signs (+) one for each level of the PUSHD directory stack

Examples

Display the UNC path whenever you are using a network drive (mapped with NET USE)PROMPT $M$_$P$G

Simulate an HP-UX style prompt with the computername and the current folder on separate lines:PROMPT=$p$_%username%@%computername%:.

Restore the default prompt:PROMPT $P$G

PROMPT is implemented as a hidden environment variable called PROMPT: ECHO %prompt% Knowing this you can force a permanent change in the CMD prompt for all sessions by setting a permanent environment variable with the appropriate prompt text. e.g.

SETX PROMPT $M$_$P$G

You can also create a shortcut to the command prompt like this:CMD /K PROMPT $M$_$P$G

If Command Extensions are disabled the commands $M and $+ are not supported.

PsKill (part of PsTools - download PsKill )

Kill processes by name or process ID

Syntax pskill [- ] [-t] [\\computer [-u user] [-p passwd]] <process name | process id>

Options:

computer The computer on which the process is running. Default=local system -p passwd Specify a password for user (optional). Passed as clear text. If omitted, you will

be prompted to enter a hidden password. -u user Specify a user name for login to remote computer(optional). -t Kill the process and its descendants.

process id/name The process or processes to be killed. - Help, display the supported options.

To kill a process on a remote system requires administrative privileges on the remote system.

Examples:Kill all instances of notepad.exe running on \\workstation64:

pskill \\workstation64 notepad

PsExec (part of PsTools - download PsExec )

Execute a command-line process on a remote machine.

Syntax psexec \\computer[,computer[,..] [options] command [arguments] psexec @run_file [options] command [arguments]

Options:

computer The computer on which psexec will run command. Default = local system To run against all computers in the current domain enter "\\*" @run_file Run command on every computer listed in the text file specified. command Name of the program to execute

arguments Arguments to pass (file paths must be absolute paths on the target system)

-a n,n,... Set processor affinity to n. Processors are numbered as 1,2,3,4 etc so to run the application on CPU 2 and CPU 4, enter: "-a 2,4"

-c Copy the program (command)to the remote system for execution. -c -f Copy even if the file already exists on the remote system. -c -v Copy only if the file is a higher version or is newer than the remote copy.

If you omit the -c option then the application must be in the system path on the remote system.

-d Don't wait for the application to terminate. Only use for non-interactive applications. -e Load the user account's profile, don't use with the system account (-s) -i Interactive - Run the program so that it interacts with the desktop on the remote system. -l Limited - Run process as limited user. Only allow privs assigned to the Users group. -n s Specify a timeout s seconds for connecting to the remote computer. -p psswd Specify a password for user (optional). Passed as clear text. If omitted, you will be

prompted to enter a hidden password. -s Run remote process in the System account. -u user Specify a user name for login to remote computer(optional). -w directory Set the working directory of the process (relative to the remote computer). -x Display the UI on the Winlogon desktop (local system only). -low, -belownormal, -abovenormal, -high or -realtime These options will run the process at a

different priority.

Psexec can also be used to start GUI applications, but in that case the GUI will appear on the remote machine. Input is passed to the remote system when you press the enter key - typing Ctrl-C will terminate the remote process.When you specify a username the remote process will execute in that account, and will have access to that account's network resources. If you omit username the remote process will run in the same account from which you execute PsExec, but because the remote process is impersonating it will not have access to network resources on the remote system. PsExec does not require you to be an administrator of the local filesystem this can allow UserA to run commands as UserB - a Runas replacement.Surround any long filenames "with quotation marks"

Examples:

Launch an interactive command prompt on \\workstation64:psexec \\workstation64 cmd

Execute IpConfig on the remote system, and display the output locally:psexec \\workstation64 ipconfig /all

Copy the program test.exe to the remote system and execute it interactively:psexec \\workstation64 -c test.exe

Execute a program that is already installed on the remote system:

psexec \\workstation64 "c:\Program Files\test.exe"Run Internet Explorer on the local machine but with limited-user privileges:

psexec -l -d "c:\program files\internet explorer\iexplore.exe"

PsShutdown (part of PsTools - download )

Initiate a shutdown/reboot of a local or remote computer, logoff a user, lock a system.

Syntax psshutdown [[\\computer[,computer[,..] | @file [-u user [-p passwd]]] -s|-r|-h|-d|-k|-a|-l|-o [-f] [-c] [-t nn|h:m] [-n s] [-v nn] [-e [u|p]:xx:yy] [-m "message"]Options:

computer The computer on which the user account resides. Default=local system a wildcard (\\*), will affect all computers in the current domain. -p passwd Specify a password for user (optional). Passed as clear text. If omitted, you will be

prompted to enter a hidden password. -u user Specify a user name for login to remote computer(optional). @file Execute the command on each of the computers listed in the file. -a Abort a shutdown (only possible while a countdown is in progress) -c Allow the shutdown to be aborted by the interactive user -d Suspend the computer -e [u|p]:xx:yy Shutdown reason code, 'u' = user, 'p'= planned shutdown. xx is the major reason code (must be less than 256) yy is the minor reason code (must be less than 65536) -f Force all running applications to exit during the shutdown instead of giving them a chance to gracefully save their data. -h Hibernate the computer -k Poweroff the computer (reboot if poweroff is not supported) -l Lock the computer -m "message" Specify a message to logged-on users when a shutdown countdown commences -n Timeout in seconds connecting to remote computers -o Logoff the console user -r Reboot after shutdown -s Shutdown without poweroff -t Countdown in seconds until the shutdown (default: 20 seconds) or the time of shutdown (in 24

hour notation) -v Display message for the specified number of seconds before the shutdown. default= display a shutdown notification dialog, specifying a value of 0 results in no dialog. - Help, display the supported options.

This tool allows administrators to create a batch file that will run against multiple computers to perform a mass change of the administrator password.

Examples:

Reboot \\workstation64 as part of an OS upgrade

psshutdown \\workstation64 -r -e p:2:3

PUSHD

Change the current directory/folder and store the previous folder/path for use by the POPD command.

Syntax PUSHD pathname Key pathname - the folder to make 'current' (UNC names accepted)

Example

@Echo OffSetlocalSet _folder=%1Pushd %_folder%:: Now verify we really moved to the new folderIf /i not "%cd%"=="%_folder% (Echo folder not found &goto :eof)Echo We are at %cd%PopdEcho We are back at %cd%

Networks When a UNC path is specified, PUSHD will create a temporary drive map and will then use that new drive. Temporary drive letters are allocated in reverse alphabetical orderso if Z: is free it will be used.If Command Extensions are disabled the PUSHD command will not accept a network (UNC) path.

#Ah, push it - push it goodAh, push it - p-push it real good# - Salt 'N' Pepa

REG.exe

Read, Set or Delete registry keys and values, save and restore from a .REG file.

Syntax: REG QUERY [ROOT\]RegKey /v ValueName [/s] REG QUERY [ROOT\]RegKey /ve - -This returns the (default) value REG ADD [ROOT\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f] REG ADD [ROOT\]RegKey /ve [/d Data] [/f] -- Set the (default) value

REG DELETE [ROOT\]RegKey /v ValueName [/f] REG DELETE [ROOT\]RegKey /ve [/f] -- Remove the (default) value REG DELETE [ROOT\]RegKey /va [/f] -- Delete all values under this key

REG COPY [\\SourceMachine\][ROOT\]RegKey [\\DestMachine\][ROOT\]RegKey

REG EXPORT [ROOT\]RegKey FileName.reg REG IMPORT FileName.reg REG SAVE [ROOT\]RegKey FileName.hiv REG RESTORE \\MachineName\[ROOT]\KeyName FileName.hiv REG LOAD FileName KeyName REG UNLOAD KeyName REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/v ValueName] [Output] [/s] REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/ve] [Output] [/s]

Key: ROOT : HKLM = HKey_Local_machine (default) HKCU = HKey_current_user HKU = HKey_users HKCR = HKey_classes_root

ValueName : The value, under the selected RegKey, to edit. (default is all keys and values) /d Data : The actual data to store as a "String", integer etc /f : Force an update without prompting "Value exists, overwrite Y/N" \\ Machine : Name of remote machine - omitting defaults to current machine. Only HKLM

and HKU are available on remote machines. FileName : The filename to save or restore a registry hive. KeyName : A key name to load a hive file into. (Creating a new key) /S : Query all subkeys and values. /S Separator : Character to use as the separator in REG_MULTI_SZ values the default is "\0" /t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ Output : /od (only differences) /os (only matches) /oa (all) /on (no output)

Notes: Any of the above commands can be run against a remote machine by adding \\MachineName to the command line, assuming the Remote Registry Service is running.Registry data stored under HKCU will be visible and writable by the currently logged in user.Registry data stored under HKLM will be visible to all users and writable by administrators.To include a quote mark (") in the data, prefix it with the escape character (\) e.g. "Here is \" a quote"Enclose ValueNames that contain the \ character in single quotes.REG RESTORE has a tendency not to work, possibly due to firewall issues, Export and Import are much more reliable.

Examples

REG QUERY HKCU\Console\REG QUERY HKCU\Console /v ScreenBufferSizeREG ADD HKCU\Software\SS64 /v Sample /d "some test data"REG QUERY HKCU\Software\SS64 /v Sample

REG ADD HKLM\Software\DiLithium /v WarpSpeed /t REG_BINARY /d ffffffffREG QUERY HKLM\Software\DiLithium /v WarpSpeed

REG COPY \\Wks580\HKCU\Software\SS64 HKCU\Software\SS64REG COPY HKCU\Software\SS64 HKCU\Software\SS64Copy

REG EXPORT HKCU\Software\SS64 C:\MyReg.REGREG IMPORT C:\MyReg.REGREG SAVE HKCU\Software\SS64 C:\MyRegHive.hivREG RESTORE \\Wks580\HKCU\Software\SS64 C:\MyRegHive.hiv

Change the default user profile: (temporarily load it as ZZZ)

REG LOAD HKU\ZZZ "C:\Documents and Settings\Default User\NTUSER.DAT"REG ADD HKU\ZZZ\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce /v newUserProfile /t REG_EXPAND_SZ /d "D:\setup.cmd" /fREG UNLOAD HKU\ZZZ

More examples are available via: REG QUERY /? REG ADD /? etc

"The way to a mans heart is through his stomach" - Fanny Fern (writer)

REGEDIT

Import, export or delete registry settings from a text (.REG) file

Syntax Export the Registry (all HKLM plus current user) REGEDIT /E pathname Export part of the Registry REGEDIT /E pathname "RegPath" Import a reg script REGEDIT pathname Silent import REGEDIT /S pathname Start the regedit GUI REGEDIT        Open multiple copies of GUI (XP and 2003 only)       REGEDIT -m

Key /E : Export

/S : Silent Import

How to add keys and values from the registry:

Create a text file like this:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\SomeKey]"SomeStringValue"="Hello"

When double clicking this .reg file the key and value will be added. Alternatively run REGEDIT MYKEY.REG from the command line.

How to delete keys and values from the registry:

Create a reg file like this, notice the hyphen inside the first bracket

Windows Registry Editor Version 5.00 [-HKEY_CURRENT_USER\SomeKey]

When double clicking this .reg file the key "SomeKey" will be deleted along with all string, binary or Dword values in that key.

If you want to just delete values, leaving the key in place, set the value you want to delete = to a hyphen e.g.

Windows Registry Editor Version 5.00 [HKEY_CURRENT_USER\SomeKey]"SomeStringValue"=-

Again double clicking this .reg file will delete the values specified, or you can use REGEDIT /s MyDeleteScript.REG

Compare the Registry of two machines

Windiff is your friend, this simple GUI utility from the resource kit will list all the differences.

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"

Under Windows NT 4 all registry scripts start with: REGEDIT4 (This version string will also work in XP and later versions of Windows.)

"I never make stupid mistakes. Only very, very clever ones" - John Peel

RunDLL32.exe

Run a DLL program. This command is available on all version of Windows from Win95 onwards, but the DLL's and options available do vary considerably. Many options are case sensitive.

Syntax RUNDLL32.EXE dll_name,EntryPoint [options]

Examples

Un-install MS Java Virtual Machine (JVM): RUNDLL32 advpack.dll,LaunchINFSection java.inf,UnInstall Copy a floppy disk RUNDLL32 diskcopy,DiskCopyRunDll

Lock workstation RUNDLL32.exe user32.dll, LockWorkStation

Add a Network Printer RUNDLL32 printui.dll,PrintUIEntry /ia /c\\server /m "AGFA-AccuSet v52.3"/h "Intel" /v

"Windows 2000" /f %windir%\inf\ntprint.inf Add a Local Printer

RUNDLL32 printui.dll,PrintUIEntry /if /b "Test Printer" /c\\SERVER/f "%windir%\inf\ntprint.inf" /r "lpt1:" /m "AGFA-AccuSet v52.3"

Add a printer connection that's available to anyone who logs on: Rundll32 printui.dll,PrintUIEntry /ga /n\\Server\PrintShare Display all the available commands for PRINTUI.DLL RUNDLL32 printui.dll,PrintUIEntry /?

(add/remove print drivers, print queues, preferences, properties etc)

"If you're rich you can buy books. If you're poor, you need a library" - John Kenneth Galbraith

REN

Rename a file or files.

REN [drive:][path]old_filename new_filename

RENAME is a synonym for REN

You cannot specify a different drive or path for `new_filename` - use the MOVE command instead. Both the source and/or destination may include wildcards.

e.g. REN *.txt *.xyz REN c:\MyFile.txt *.xyz REN c:\MyFile.txt ????.xyz

RD

Delete folder(s)

Syntax RD pathname RD /S pathname RD /S /Q pathname Key /S : Delete all files and subfolders in addition to the folder itself. Use this to remove an

entire folder tree. /Q : Quiet - do not display YN confirmation

Place any long pathnames in double quotes.

RD does not support wildcards but you can remove several folders in one command by listing the pathname to each. e.g.

RD c:\docs\Jan c:\docs\Feb "c:\My Documents\Mar"RMDIR is a synonym for RD

"Dying is the most embarrassing thing that can happen to you, because someones got to take care of all your details". - Andy Warhol

ROUTE.exe

Manipulate network routing tables. Route packets of network traffic from one subnet to another by modifying the route table.

Syntax

Display route details: ROUTE [-f] PRINT [destination_host] [MASK subnet_mask_value] [gateway] [METRIC metric] [IF interface_no.]

Add a route: ROUTE [-f] [-p] ADD [destination_host] [MASK subnet_mask_value] [gateway] [METRIC metric] [IF interface_no.]

Change a route: ROUTE [-f] CHANGE [destination_host] [MASK subnet_mask_value] [gateway] [METRIC metric] [IF interface_no.]

Delete a route: ROUTE [-f] DELETE [destination_host] [MASK subnet_mask_value] [gateway] [METRIC metric] [IF interface_no.]

Key-f Clear (flush) the routing tables of all gateway entries. If this is used in conjunction with one of the

commands, the tables are cleared prior to running the command.

destination_host The address (or set of addresses) that you want to reach. -p Create a persistent route - survives system reboots. (not supported in Windows 95)

subnet_mask_value The subnet mask value for this route entry. This defines how many addresses are there. If not specified, it defaults to 255.255.255.255.

gateway The gateway.

interface The interface number (1,2,...) for the specified route. the best interface available.

metric The metric, ie. cost for the destination.

Note that routes added to the table are not made persistent unless the -p switch is specified. Non-persistent routes only last until the computer is rebooted.

Symbolic names used for Destination_Host are looked up in the network database file NETWORKS. The symbolic names for gateway are looked up in the host name database file HOSTS.

If the command is PRINT or DELETE. Destination or gateway can be a wildcard ('*'), or the gateway argument may be omitted.

An IP address mask of 0.0.0.0 means everything. (rather like the *.* wildcard). In other words it says: When matching this pattern, don't worry about matching any of the bits - everything matches.

If Destination_Host contains a * or ?, it is treated as a shell pattern, and only matching destination routes are printed. The '*' matches any string, and '?' matches any one char.

Examples:157.*.1157.*127.*

*224*

RMTSHARE.exe ( Resource kit )

Manage File and Printer shares, local or on a remote server. Although missing from the Windows 2000 Resource kit, the NT version works fine under Windows 2000/2003.

Syntax Display all shares RMTSHARE \\server Display details of a specific share RMTSHARE \\server\sharename Share a Folder RMTSHARE \\server\sharename=drive:path [options] Share a Printer RMTSHARE \\server\sharename=printername /PRINTER [options] Edit an existing SHARE RMTSHARE \\server\sharename [options] Delete a SHARE RMTSHARE \\server\sharename /DELETEOptions

/USERS:number /UNLIMITED /REMARK:"text" /GRANT user:perm /REMOVE user

Notes: Either specify /Users to restrict the number of connections that can be made OR specify /UNLIMITEDYou can include several /GRANTs in a single command line. Enclose paths that include spaces like this\\server\"long share name"="c:\long file name"

"How to be green? consume less, share more, enjoy life" - Penny Kemp

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.

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 variablesDisplay variables that begin with 'P': SET pDisplay variables that begin with an underscore SET _

Examples

Storing a text string:

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

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

C:\>set xx=fishC:\>set msg=%xx% chipsC:\>set msgmsg=fish chips

C:\>set xx=sausageC:\>set msgmsg=fish chips

C:\>set msg=%xx% chipsC:\>set msgmsg=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 offSet /P _dept=Please enter Department:If "%_dept%"=="" goto :sub_errorIf /i "%_dept%"=="finance" goto sub_financeIf /i "%_dept%"=="hr" goto sub_hrgoto:eof

:sub_financeecho You chose the finance deptgoto:eof

:sub_hrecho 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

CALL SETSET can be CALLed allowing a variable substring to be evaluated:

SET start=10 SET length=9 SET string=The quick brown fox jumps over the lazy dog CALL SET substring=%%string:~%start%,%length%%% ECHO (%substring%)

Deleting an environment 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 = use:(SET _department=)  or SET "_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=MyTextwill create a variable called "my var"

SimilarlySET _var =MyTextwill create a variable called "_var " - note trailing space

To avoid problems with extra spaces appearing in your output, issue SET statements in parentheses, like this

(SET _department=Some Text) Alternatively you can doSET "_department=Some Text"

Note: if you wanted to actually include a bracket in the variable you need to use an escape character.

The SET command will set ERRORLEVEL to 1 if the variable name is not found in the current environment.This can be detected using the IF ERRORLEVEL command

Arithmetic expressions (SET /a)

The expression to be evaluated can include the following operators:

Multiply * Divide / Add + Subtract - Modulus % AND & OR | XOR ^ LSH << RSH >> 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 SetXor 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 timeVariables 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

# I got my mind set on you # I got my mind set on you... - George Harrison

SETX.exe ( Resource Kit )

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 in this way 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 "_myvar" 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=GMTSetX _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 ALWAYS be equal to the value of the %PATH% environment variable even in the event that the PATH variable changes: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

Share.vbs ( Resource Kit )

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 2K/XP. The preferred method for creating shares is the RMTShare command, which can also grant permissions.

Syntax: List Shares Share.vbs /L [/S <server>] [/U <username>] [/W <password>] [/O <outputfile>] Create a Share

Share.vbs /C /N <name> /P <path> [/T <type>] [/V <description>][/S <server>] [/U <username>] [/W <password>] [/O <outputfile>]

Delete a ShareShare.vbs /D /N <name>[/S <server>] [/U <username>] [/W <password>] [/O <outputfile>]

Options:

/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 \\Frodocscript Share.vbs /L /s FrodoCreate 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 \\Frodocscript Share.vbs /d /n scratch /s Frodo

"The inherent vice of capitalism is the unequal sharing of blessings,the inherent vice of Socialism is the equal sharing of miseries." - Winston Churchill

SHUTDOWN.exe (for Terminal Services use: TsShutDn )

Shutdown the computer

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

logoff_option: /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 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 only

Example:

To create a desktop shortcut that will immediately shutdown your system, set the shortcut Target Properties to: C:\Windows\System32\shutdown.exe -s

When using this command to reboot a server, the shutdown process will normally allow about 30 seconds to ensure each running service has time to stop. The shutdown can be made faster if all the services are first halted using NET STOP

e.g.net stop "Microsoft Exchange Internet Mail Service"net stop "Microsoft FTP Service"net stop "Some other Service"SHUTDOWN /t:25 /r

Typical 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 UnresponsiveE 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: UnresponsiveE 4 6 Application: Unstable U 5 15 System Failure: Stop errorE 5 19 Security issue U 5 19 Security issueE P 5 19 Security issueE 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

e.g. SHUTDOWN /r /d P:2:17

SLEEP.exe ( Resource Kit )

Add a fixed delay to a batch file

Syntax SLEEP timeKey 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

AlternativeA 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

See Clay Calvert's newsgroup posting for a full explanation of this technique.

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.

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.

"A man should never be ashamed to own he has been in the wrong, which is saying in other words, that he is wiser today than he was yesterday" - Alexander Pope (thoughts on various subjects)

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:

tasklist /svctasklist /v /fi "STATUS eq running"tasklist /v /fi "username eq ORACLE_SERVICE_ACCOUNT"

WMIC can also list running processes and parameters:

WMIC /OUTPUT:C:\ProcList.txt PROCESS get Caption,Commandline,Processid

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 offFOR /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

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

TIMEOUT.exe ( Resource Kit )

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

"It is awful work this love and prevents all a mans projects of good or glory" - Lord Byron

TRACERT

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.

FirewallsMany 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

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.txtOutput can be appended to an existing file: TYPE file.txt >> ExistingFile.txtTo do the same with user console input : TYPE CON > Newfile.txtThis will require a CTRL - Z to indicate end of file.When using redirection to SORT a file the TYPE command is used implicitlyFor 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 ANSI (note any extended characters will be lost) eg: TYPE UnicodeFile.txt > ANSIFile.txt

To convert multiple Unicode files to ASCII try this script

@echo offren *.txt *.txxfor %%G in (*.txx) do (TYPE %%G >%%~nG.txt)echo del *.txx

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.

VER

Display the current operating system version.

Syntax

VER

Use ver to find specific operating systems like this:

@Echo offSetlocal:: Get windows Version numbersFor /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 sub5if "%_major%"=="6" goto sub6

Echo unsupported versiongoto:eof

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

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

:sub6if "%_minor%"=="1" goto sub7Echo Windows Vista or Windows 2008 [%PROCESSOR_ARCHITECTURE%]goto:eof

:sub7Echo 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

WHERE ( 2K Resource Kit / 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.*

"Who never walks, save where he sees men's tracks, makes no discoveries" - Josiah Gilbert Holland

WHOAMI.exe ( Resource kit )

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.exec:>ECHO %USERDOMAIN%\%USERNAME%ss64\Simon

c:>whoamiss64\JDoe

WHOAMI /all - shows all permissions and group memberships.

"We can now manipulate images to such an extrodinary extent that there's no lie you cannot tell" - Sir David Attenborough

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.

Downloads

Microsoft Windows 2003 SDK (large download) Microsoft Windows 2008 SDK (large download) WinDiff - Grigsoft (3rd party) download 75 Kb

"Shall I compare thee to a summer's day? Thou art more lovely and more temperate.Rough winds do shake the darling buds of May, And summer's lease hath all too short a date" - Shakespeare

WINMSD.exe

Microsoft Windows diagnosticsReports: 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 <computername.txt> 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 reportede.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.

WINMSDP.exe ( Resource Kit )

Windows NT diagnostics IIReports: 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

"The best is the enemy of the good" - Voltaire

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 <Alias>: WMIC [global_switches] [/locale:ms_409] <alias> [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: 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 BRIEFWMIC OS GET csname, locale, bootdeviceWMIC /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.tsvWMIC SERVICE where caption='TELNET' CALL STARTSERVICEWMIC PRINTER LIST STATUSWMIC PRINTER where PortName="LPT1:" GET PortName, Name, ShareNameWMIC /INTERACTIVE:ON PRINTER where PortName="LPT1:" DELETEWMIC PROCESS where name='evil.exe' deleteWMIC /output:"%computername%.txt" MEMORYCHIP where "memorytype=17" get CapacityWMIC /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, for older machines download & install: WMI core for Win 9x / NT 4The availability of WMI information does vary across different versions of Windowse.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.

"Life is like a game of cards. The hand you are dealt is determinism; the way you play it is free will" - Jawaharial Nehru

XCACLS.exe ( Resource Kit )

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 MyFolderXCACLS MyFolder /E /G guests:rx:: Allow guests the Full Control permission in MyFolder and all subfoldersXCACLS 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 MyFolderXCACLS MyFolder /T /P guests:x

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.

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 that have changed since mm-dd-yyyy. If no date is given, the default is to copy files with a modification date before today.(at least 1 day

before) /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 pathnamesExamples:

To copy a file:XCOPY C:\utils\MyFile D:\Backup\CopyFileTo copy a folder:XCOPY C:\utils D:\Backup\utils /iTo copy a folder including all subfolders.XCOPY C:\utils\* D:\Backup\utils /s /iThe /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=/YThis 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

"It is easier to copy than to think, hence fashion" - Wallace Stevens

REM

In a batch file REM at the start of a line signifies a comment or REMARKalternatively adding :: at the start of a line has a similar effect

For example:

@ECHO OFF:::: First comment::REM Second commentREM::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.

BugsThere are problems using a :: comment within an IF or FOR code brackete.g.@echo offFOR /L %%i IN (1,1,10) Do (Echo before comment:: Some commentEcho 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 REMe.g.

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

C:\WORK>ftp -s:ftpscriptftp> !REM This is a remarkftp> bye

C:\WORK>

The603h – 17/01/2010