- /* steve jansen */
- // another day in paradise hacking code and more
- Windows Batch Scripting: Getting Started
- Getting Started with Windows Batch Scripting
- Launching the Command Prompt
- Editing Batch Files
- Viewing Batch Files
- Batch File Names and File Extensions
- Saving Batch Files in Windows
- Running your Batch File
- Comments
- Silencing Display of Commands in Batch Files
- Debugging Your Scripts
- Comments
- Guides
- Recent Posts
- Social Stuff
- cscript cscript
- Синтаксис Syntax
- Параметры Parameters
- Комментарии Remarks
- Windows commands
- Prerequisites
- Command shell overview
- Command-line reference A-Z
/* steve jansen */
// another day in paradise hacking code and more
Windows Batch Scripting: Getting Started
Getting Started with Windows Batch Scripting
Windows batch scripting is incredibly accessible – it works on just about any modern Windows machine. You can create and modify batch scripts on just about any modern Windows machine. The tools come out of the box: the Windows command prompt and a text editor like Notepad.exe. It’s definitely far from the best shell scripting langauge, but, it gets the job done. It’s my “duct tape” for Windows.
Launching the Command Prompt
Windows gurus launch the command prompt using the keyboard shortcut Windows Logo Key + R (i.e., “Run”) > Type cmd.exe then Enter . This is way faster than navigating the Windows Start Menu to find the Command Prompt.
Editing Batch Files
The universal text editor for batch files is Notepad ( Windows Logo Key + R > Type notepad then Enter ). Since batch files are just ASCII text, you can probably use just about any text editor or word processor. Very few editors do anything special for Batch files like syntax highlighting or keyword support, so notepad is good enough fine and will likely be installed on just about every Windows system you encounter.
Viewing Batch Files
I would stick with Notepad for viewing the contents of a batch file. In Windows Explorer (aka, “My Computer”), you should be able to view a batch file in Notepad by right clicking the file and seleting Edit from the context menu. If you need to view the contents within a command prompt window itself, you can use a DOS command like TYPE myscript.cmd or MORE myscript.cmd or EDIT myscript.cmd
Batch File Names and File Extensions
Assuming you are using Windows XP or newer, I recommend saving your batch files with the file extension .cmd . Some seriously outdated Windows versions used .bat , though I recommend sticking with the more modern .cmd to avoid some rare side effects with .bat files.
With the .cmd file extension, you can use just about filename you like. I recommend avoiding spaces in filenames, as spaces only create headaches in shell scripting. Pascal casing your filenames is an easy way to avoid spaces (e.g., HelloWorld.cmd instead of Hello World.cmd ). You can also use punctuation characters like . or — or _ (e.g. Hello.World.cmd , Hello-World.cmd , Hello_World.cmd ).
Another thing with names to consider is avoiding names that use the same name of any built-in commands, system binaries, or popular programs. For example, I would avoid naming a script ping.cmd since there is a widely used system binary named ping.exe . Things might get very confusing if you try to run ping and inadvertently call ping.cmd when you really wanted ping.cmd . (Stay tuned for how this could happen.) I might called the script RemoteHeartbeat.cmd or something similar to add some context to the script’s name and also avoid any naming collisions with any other executable files. Of course, there could be a very unique circumstance in which you want to modify the default behavior of ping in which this naming suggestion would not apply.
Saving Batch Files in Windows
Notepad by default tries to save all files as plain jane text files. To get Notepad to save a file with a .cmd extension, you will need to change the “Save as type” to “All Files (.)”. See the screenshot below for an example of saving a script named “HelloWorld.cmd” in Notepad.
SIDEBAR: I’ve used a shortcut in this screenshot that you will learn more about later. I’ve saved the file to my “user profile folder” by naming the file %USERPROFILE%\HelloWorld.cmd . The %USERPROFILE% keyword is the Windows environmental variable for the full path to your user profile folder. On newer Windows systems, your user profile folder will typically be C:\Users\ . This shortcut saves a little bit of time because a new command prompt will generally default the “working directory” to your user profile folder. This lets you run HelloWorld.cmd in a new command prompt without changing directories beforehand or needing to specify the path to the script.
Running your Batch File
The easy way to run your batch file in Windows is to just double click the batch file in Windows Explorer (aka “My Computer”). Unfortunately, the command prompt will not give you much of a chance to see the output and any errors. The command prompt window for the script will disappear as soon as the script exits. (We will learn how to handle this problem in Part 10 – Advanced Tricks ).
When editing a new script, you will likely need to run the batch file in an existing command window. For newbies, I think the easiest foolproof way to run your script is to drag and drop the script into a command prompt window. The command prompt will enter the full path to your script on the command line, and will quote any paths containing spaces.
Some other tips to running batch files:
- You can recall previous commands using the up arrow and down arrow keys to navigate the command line history.
- I usually run the script as %COMPSPEC% /C /D «C:\Users\User\SomeScriptPath.cmd» Arg1 Arg2 Arg3 This runs your script in a new command prompt child process. The /C option instructs the child process to quit when your script quits. The /D disables any auto-run scripts (this is optional, but, I use auto-run scripts). The reason I do this is to keep the command prompt window from automatically closing should my script, or a called script, call the EXIT command. The EXIT command automatically closes the command prompt window unless the EXIT is called from a child command prompt process. This is annoying because you lose any messages printed by your script.
Comments
The official way to add a comment to a batch file is with the REM (Remark) keyword:
The power user method is to use :: , which is a hack to uses the the label operator : twice, which is almost always ignored.
Most power authors find the :: to be less distracting than REM . Be warned though there are a few places where :: will cause errors.
For example, a FOR loop will error out with :: style comments. Simply fall back to using REM if you think you have a situation like this.
Silencing Display of Commands in Batch Files
The first non-comment line of a batch file is usually a command to turn off printing (ECHO’ing) of each batch file line.
The @ is a special operator to suppress printing of the command line. Once we set ECHO’ing to off, we won’t need the @ operator again in our script commands.
You restore printing of commands in your script with:
Upon exit of your script, the command prompt will automatically restore ECHO to it’s previous state.
Debugging Your Scripts
Batch files invole a lot of trial and error coding. Sadly, I don’t know of any true debugger for Windows batch scripts. Worse yet, I don’t know of a way to put the command processor into a verbose state to help troubleshoot the script (this is the common technique for Unix/Linux scripts.) Printing custom ad-hoc debugging messages is about your only option using the ECHO command. Advanced script writers can do some trickery to selectively print debugging messages, though, I prefer to remove the debugging/instrumentation code once my script is functioning as desired.
Posted by Steve Jansen Mar 1 st , 2013 batch, scripting, shell, windows
Comments
Hi, I’m Steve. I’m a software developer loving life in Charlotte, NC, an (ISC) 2 CSSLP and an avid fan of Crossfit.
And, no, I’m not Steve Jansen the British jazz drummer, though that does sound like a sweet career.
Guides
Recent Posts
Social Stuff
- @steve-jansen on GitHub
- @steve-jansen on StackOverflow
- @steve-jansen ProTips on Coderwall
- @steve-jansen on Microsft Connect
- @steve-jansen on ASP.NET User Voice
- Subscribe via RSS
Copyright © 2015 — Steve Jansen — Powered by Octopress
cscript cscript
Область применения: Windows Server (половина ежегодного канала), Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012 Applies to: Windows Server (Semi-Annual Channel), Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012
Запускает сценарий для запуска в среде командной строки. Starts a script to run in a command-line environment.
Для выполнения этой задачи не требуются административные учетные данные. Performing this task does not require you to have administrative credentials. Поэтому рекомендуется выполнять эту задачу от имени пользователя без административных учетных данных. Therefore, as a security best practice, consider performing this task as a user without administrative credentials.
Синтаксис Syntax
Параметры Parameters
Параметр Parameter | Описание Description |
---|---|
имя_сценария. расширение scriptname.extension | Указывает путь и имя файла скрипта с необязательным расширением имени файла. Specifies the path and file name of the script file with optional file name extension. |
/b /b | Задает пакетный режим, при котором не отображаются предупреждения, ошибки сценариев или входные запросы. Specifies batch mode, which does not display alerts, scripting errors, or input prompts. |
/d /d | Запускает отладчик. Starts the debugger. |
/e: /e: | Указывает подсистему, используемую для выполнения скрипта. Specifies the engine that is used to run the script. |
/h: cscript /h:cscript | Регистрирует cscript.exe в качестве сервера скриптов по умолчанию для выполнения скриптов. Registers cscript.exe as the default script host for running scripts. |
/h: WScript /h:wscript | Регистрирует wscript.exe в качестве сервера скриптов по умолчанию для выполнения скриптов. Registers wscript.exe as the default script host for running scripts. Это значение по умолчанию. This is the default. |
/i /i | Указывает интерактивный режим, который отображает предупреждения, ошибки сценариев и входные запросы. Specifies interactive mode, which displays alerts, scripting errors, and input prompts. Это значение по умолчанию и противоположное /b . This is the default and the opposite of /b . |
/Задание /job: | Запускает задание, определяемое идентификатором в файле скрипта. wsf. Runs the job identified by identifier in a .wsf script file. |
/лого /logo | Указывает, что баннер сервера сценариев Windows отображается в консоли перед запуском скрипта. Specifies that the Windows Script Host banner is displayed in the console before the script runs. Это значение по умолчанию и противоположное /nologo . This is the default and the opposite of /nologo . |
/nologo /nologo | Указывает, что баннер сервера сценариев Windows не отображается перед выполнением скрипта. Specifies that the Windows Script Host banner is not displayed before the script runs. |
/s /s | Сохраняет текущие параметры командной строки для текущего пользователя. Saves the current command-prompt options for the current user. |
/t: /t: | Указывает максимальное время, в течение которого может выполняться скрипт (в секундах). Specifies the maximum time the script can run (in seconds). Можно указать до 32 767 секунд. You can specify up to 32,767 seconds. Значение по умолчанию — без ограничения по времени. The default is no time limit. |
/U /u | Указывает Юникод для входных и выходных данных, которые перенаправляются из консоли. Specifies Unicode for input and output that is redirected from the console. |
/x /x | Запускает скрипт в отладчике. Starts the script in the debugger. |
/? /? | Отображает доступные параметры команды и предоставляет справку по их использованию. Displays available command parameters and provides help for using them. Это то же самое, что ввод cscript.exe без параметров и скрипта. This is the same as typing cscript.exe with no parameters and no script. |
скриптаргументс scriptarguments | Задает аргументы, передаваемые в скрипт. Specifies the arguments passed to the script. Каждому аргументу сценария должна предшествовать косая черта ( / ). Each script argument must be preceded by a slash (/). |
Комментарии Remarks
Каждый параметр является необязательным; Однако нельзя указать аргументы скрипта без указания скрипта. Each parameter is optional; however, you can’t specify script arguments without specifying a script. Если не указать скрипт или какие-либо аргументы скрипта, cscript.exe отображает синтаксис cscript.exe и допустимые параметры узла. If you don’t specify a script or any script arguments, cscript.exe displays the cscript.exe syntax and the valid host options.
Параметр /t предотвращает чрезмерное выполнение скриптов путем установки таймера. The /t parameter prevents excessive running of scripts by setting a timer. Когда время выполнения превышает указанное значение, cscript прерывает работу обработчика скриптов и завершает процесс. When the run time exceeds the specified value, cscript interrupts the script engine and ends the process.
Файлы сценариев Windows обычно имеют одно из следующих расширений имен файлов:. wsf,. vbs,. js. Windows script files usually have one of the following file name extensions: .wsf, .vbs, .js. Сервер сценариев Windows может использовать файлы скриптов. wsf. Windows Script Host can use .wsf script files. Каждый файл. WSF может использовать несколько обработчиков скриптов и выполнять несколько заданий. Each .wsf file can use multiple scripting engines and perform multiple jobs.
Windows commands
All supported versions of Windows (server and client) have a set of Win32 console commands built in.
This set of documentation describes the Windows Commands you can use to automate tasks by using scripts or scripting tools.
Prerequisites
The information that is contained in this topic applies to:
- Windows Server 2019
- Windows Server (Semi-Annual Channel)
- Windows Server 2016
- Windows Server 2012 R2
- Windows Server 2012
- Windows Server 2008 R2
- Windows Server 2008
- Windows 10
- Windows 8.1
Command shell overview
The Command shell was the first shell built into Windows to automate routine tasks, like user account management or nightly backups, with batch (.bat) files. With Windows Script Host you could run more sophisticated scripts in the Command shell. For more information, see cscript or wscript. You can perform operations more efficiently by using scripts than you can by using the user interface. Scripts accept all Commands that are available at the command line.
Windows has two command shells: The Command shell and PowerShell. Each shell is a software program that provides direct communication between you and the operating system or application, providing an environment to automate IT operations.
PowerShell was designed to extend the capabilities of the Command shell to run PowerShell commands called cmdlets. Cmdlets are similar to Windows Commands but provide a more extensible scripting language. You can run Windows Commands and PowerShell cmdlets in Powershell, but the Command shell can only run Windows Commands and not PowerShell cmdlets.
For the most robust, up-to-date Windows automation, we recommend using PowerShell instead of Windows Commands or Windows Script Host for Windows automation.
You can also download and install PowerShell Core, the open source version of PowerShell.
Incorrectly editing the registry may severely damage your system. Before making the following changes to the registry, you should back up any valued data on the computer.
To enable or disable file and directory name completion in the Command shell on a computer or user logon session, run regedit.exe and set the following reg_DWOrd value:
To set the reg_DWOrd value, use the hexadecimal value of a control character for a particular function (for example, 0 9 is Tab and 0 08 is Backspace). User-specified settings take precedence over computer settings, and command-line options take precedence over registry settings.
Command-line reference A-Z
To find information about a specific command, in the following A-Z menu, click the letter that the command starts with, and then click the command name.