- Скрипты для CMD
- Выключение компьютеров в домене по списку
- Единый логон-скрипт для AD
- Интерпретатор CMD — вывод переменных со спецсимволами на экран и в файл
- How to Write a CMD Script
- Related
- Understanding CMD and Written Commands
- Understanding CMD Scripts
- Using a Script CMD to Open Notepad
- Creating Your First Script CMD File
- Using Echo and Echo Off
- Creating a Text File Script
- Creating a Systems Information Script
- Using Scripts to Shut Down Your Computer
- Backing Up Files With a CMD Script
Скрипты для CMD
Скрипты выполняемые интерпретатором CMD.EXE — стандартной консольной оболочкой для Win2000/WinXP/Vista/Seven/Win8/Win2000 Server/Win2003/Win2008.
Иначе говоря — пакетники. Иногда еще их(не вполне оправданно) называют батниками, но классический батник использует возможности обеспечиваемые оболочкой предыдущих систем COMMAND.COM, возможности которого существенно меньше.
- Блог пользователя yurkesha
- Войдите или зарегистрируйтесь, чтобы отправлять комментарии
Выключение компьютеров в домене по списку
- Блог пользователя yurkesha
- Войдите или зарегистрируйтесь, чтобы отправлять комментарии
Единый логон-скрипт для AD
Моя попытка навести порядок и унификацию при подключении сетевых дисков в AD.
Возможна работа как через индивидуальные групповые политики, так и через политику AD по-умолчанию.
Идея состоит в следующем: храним описание вариантов подключений в текстовых файлах, с указанием группы для которой это работает, и анализируем при запуске грeппы конкретного пользователя с использованием dsget и dsquery.
Структура хранимых описаний такова: групповые и общедоменные назначачения хранятся в едином файле расположенном в корне NETLOGON(возможны варианты), а пользовательские назначения располагаются в папках с пользовательским именем входа в систему.
Также в отдельных файлах храним описание запускаемых скриптов для групп и пользователей.
Цель — получить прозрачный и универсальный алгоритм входа в систему единый как для обычного входа, так и для терминального, без черезмерного усложнения групповых политик.
Структура решения:
\dsget.exe — файл из RK для получения списка групп пользователя
\dsquery.dll— файл из RK для получения списка групп пользователя
\dsquery.exe— файл из RK для получения списка групп пользователя
\logon.cmd — собственно тело скрипта
\logon.vbs — костыль для запуска без отображения окна консоли — именно он должен быть назначен в качестве логон скрипта
\rs_list.txt — список групповых и общедоменных назначений подключаемых дисков с указанием группы
\sc_list.txt — список групповых и общедоменных назначений выполняемых скриптов с указанием группы
\_SCRIPT\ — папка с групповыми и общедоменными скриптами
\_SCRIPT\1C.cmd — пример скрипта
\USER1\rs_list.txt- список назначений подключаемых дисков для конкретного пользователя(без указания группы)
\USER1\sc_list.txt— список назначений выполняемых скриптов для конкретного пользователя(без указания группы)
\USER2\rs_list.txtсписок назначений подключаемых дисков для конкретного пользователя(без указания группы)
\USER2\sc_list.txt- список назначений выполняемых скриптов для конкретного пользователя(без указания группы)
Прикрепляю файл с телом скрипта и тестовой структурой.
Приветствуются пожелания по доработке 😉
Добавил ключ рекурсивного анализа вхождения в группы.
И на всякий случай тело скрипта в текстовом виде:
- Блог пользователя yurkesha
- Войдите или зарегистрируйтесь, чтобы отправлять комментарии
Интерпретатор CMD — вывод переменных со спецсимволами на экран и в файл
Известная, но слабоосвещенная тема — обработка в коммандном интерпретаторе CMD данных со спецсимволами.
В большинстве ситуаций она вполне решаема.
Плюс к этому периодически возникают задачи вывода в файл без перевода строки.
Несколько лет назад (на ру-борде) я выкладывал семпловый код, который достаточно подробно иллюстрирует примеры возможной работы:
@ECHO OFF&CLS
(ECHO Обработка переменных со спецсимволами «(«, «)»,»&»,»|»,»>»,» команда»)
SET «AAA=сообщение()&|<>команда»
(ECHO Вывод на экран с обрамляющими двойными кавычками)
(ECHO ^(ECHO «%%AAA%%»^))
(ECHO «%AAA%»)
(ECHO Перенаправление значения переменной в файл file.txt с переводом строки то есть с CR/LF)
(ECHO с заменой существующего file.txt)
(ECHO SET /p»=%%AAA%%»^ file.txt^&ECHO.^>^>file.txt)
SET /p»=%AAA%» file.txt&ECHO.>>file.txt
(ECHO Перенаправление значения переменной в файл file.txt с переводом строки то есть с CR/LF)
(ECHO дописыванием в существующий file.txt)
(ECHO SET /p»=%%AAA%%»^ ^>file.txt^&ECHO. 1^>^>file.txt)
SET /p»=%AAA%» >file.txt&ECHO. 1>>file.txt
(ECHO Перенаправление значения переменной в файл file1.txt без перевода строки то есть без CR/LF)
(ECHO с заменой существующего file1.txt)
(ECHO SET /p»=%%AAA%%»^ file1.txt)
SET /p»=%AAA%» file1.txt
(ECHO Перенаправление значения переменной в файл file1.txt без перевода строки то есть без CR/LF)
(ECHO с дописыванием в существующий file1.txt)
(ECHO SET /p»=%%AAA%%»^ ^>file1.txt)
SET /p»=%AAA%» >file1.txt
(ECHO Вывод значения переменной на экран с переводом строки то есть с CR/LF)
(ECHO SET /p»=%%AAA%%»^ =^>%%»)
(ECHO SET «AAA=%%AAA:(=^(%%»)
(ECHO SET «AAA=%%AAA:)=^)%%»)
SET «AAA=%AAA:&=^&%»
SET «AAA=%AAA:|=^|%»
SET «AAA=%AAA: =^>%»
SET «AAA=%AAA:(=^(%»
SET «AAA=%AAA:)=^)%»
(ECHO ^(ECHO %%AAA%%^))
(ECHO %AAA%)
PAUSE
Кодировка приведенного скрипта CP866.
Для ознакомления рекомендуется выполнить 😉
Само-собой в случае вопросов постараюсь ответить.
How to Write a CMD Script
Related
If you have every used the Command Line, or CMD, interface in Windows, you probably have some idea of the powerful things it can do. Creating your own CMD scripts, you can do even more, but faster.
A CMD script does the same thing as if you typed commands into the CMD window. If you want to do something on a regular basis, such as telling Windows to turn off your computer after an hour, you can write a script and then you can activate the script whenever you want to run it.
Understanding CMD and Written Commands
In the early days of personal computing almost everything was done by typing command_s into a command line interface. If you wanted to open a program, you had to type the name of the program into the command line. Today, you can simply click or touch an icon on your screen to perform most actions. But Windows still accepts type-written commands in the CMD utility. You can write commands_ to open programs, add or change account permissions, back up files or get information about your computer using the CMD window.
Understanding CMD Scripts
The Command Prompt utility in Windows can be opened at any time, simply by typing «cmd» in the Windows Start menu. Here, you can type all sorts of commands to open programs, change settings and make tweaks to how Windows and its programs perform. In Microsoft’s long history of operating systems, CMD i_s a relative newcomer. In MS-DOS, before Windows was released, when you wanted to run a script, you would save it as a .bat file. While you can still save files with that extension today, most people use the .cmd extension._
Using a Script CMD to Open Notepad
To create and save a CMD switch, it’s best to use a basic text editor. Using a word processor like Microsoft Word makes saving the file a hassle. Notepad is much easier to use. So to demonstrate how CMD works, let’s open use it to open Notepad.
- Type CMD in the Windows Start menu and press Enter to open CMD.exe.
- Change the directory from your current username folder to the base directory by typing «cd\» and pressing Enter. It should now read «C:\>» before the blinking cursor.
- Type the following line and pressEnter:start «c:\windows\system32» notepad.exe
As soon as you press Enter, you will see Notepad open. The command you entered has told Windows to start the notepad.exe program, which is located in the system32 folder, which is inside the Windows folder, on the C: drive. CMD commands are not case-sensitive so you can use lowercase or uppercase letters interchangeably.
Creating Your First Script CMD File
Now that Notepad is open, create your first CMD script file by typing the same line you used in the CMD window into notepad: start «c:\windows\system32» notepad.exe
Save the batch file to your desktop by selecting «Save As» from the File menu. Name the file «firstscript.cmd» and click «Save.» Notepad script commands must be saved with the .cmd extension, rather than the default .txt extension.
Double-click the new CMD file on your desktop. You will see the CMD window open for a fraction of a second and then close as Notepad is launched.
This is hardly a useful script, since a desktop shortcut does the same thing. To create something more useful, let’s edit the file so that it creates a new text file on your desktop listing all of your programs.
Using Echo and Echo Off
While the CMD window wasn’t open long enough to see it, by default it will always display the text that was entered in the CMD file when it runs. For longer scripts, this can be a nuisance, so it’s generally good form to turn this off by using the Echo Off command in the first line of the CMD file. By itself, Echo Off disables the display of any text that follows it. To make the Echo Off command apply to itself, put an @ symbol in front of it. Thus, your two-line CMD script would be:
@echo off
start «c:\windows\system32» notepad.exe
Creating a Text File Script
This CMD script will list all the files you have in your Program Files folder and put that list in a new text file.
- Open Notepad. Type «@echo off«in the first line and press Enter.
- In the second line, type: dir «C:\Program Files» > list_of_files.txt
- Select «Save As» from the File menu and save the file as «program-list-script.cmd.»
- Double-click the new text file on your desktop to see the list of files and folders.
The text file will appear in the same folder where the script file itself is. So if the script file is on your desktop, the list-of-files.txt file will also appear on your desktop.
If you want to change the folder where the text file is placed, you can specify its own folder in the script. For example, if you want it to be placed in your Documents folder, use: dir «C:\Program Files» > C:\Users\David\Documents\list_of_files.txt
Creating a Systems Information Script
If you want to use a script to give you needed information, it’s not always necessary to produce a text document with a script. You can have the information posted directly in the CMD window.
The example script below will give you basic information about your computer, including the operating system and version number, the BIOS version, the total physical memory and your computer’s network address. To use the script, type or copy the lines below into a new Notepad file and save it with the .cmd file extension, such as «my_computer_info.cmd.»
In this example, ECHO OFF is used to prevent the CMD window from displaying the script.
The ECHO command is used to display specific text, as well as some equal signs (===) as lines to organize the information in sections.
To insert a comment for your own use — without it affecting the script or appearing in the CMD window — type two colons first. Anything in the same line following » :: « will be commented out from the script.
The PAUSE command directs the CMD program to stay open. Pressing any key on your keyboard will close the window.
@ECHO OFF
:: This CMD script provides you with your operating system, hardware and network information.
TITLE My System Info
ECHO Please wait. Gathering system information.
ECHO OPERATING SYSTEM
systeminfo | findstr /c:»OS Name»
systeminfo | findstr /c:»OS Version»
ECHO BIOS
systeminfo | findstr /c:»System Type»
ECHO MEMORY
systeminfo | findstr /c:»Total Physical Memory»
ECHO CPU
wmic cpu get name
ECHO NETWORK ADDRESS
ipconfig | findstr IPv4
ipconfig | findstr IPv6
PAUSE
Using Scripts to Shut Down Your Computer
Normally, when you shut down your computer, it happens instantaneously. Suppose, however, that you’re listening to an audiobook or watching a training video — and you know that you will fall asleep after an hour. You can use a CMD script to tell your computer to shut itself down, after a specified period of time, using the shutdown command.
When you use the shutdown command, you need to include two additional switches, or subcommands. The first tells the computer to either shutdown or restart. You can use either -s or — r. The second tells the computer how many seconds to wait before performing the command. For this you use -t, followed by the number of seconds.
To shutdown the computer in one second, use: shutdown -s -t 01
To restart the computer in eight seconds, use: shutdown -r -t 08
To shutdown the computer in two hours use: shutdown -s -t 7200
Backing Up Files With a CMD Script
If you find it tedious to back up your files to a second storage device, using a CMD script makes the process a breeze. For this, use the Robocopy command. For example, if you want to back up all of the files in your Documents folder onto a removable storage device, you can write the command in a CMD file and then — at the end of the day — simply double click the file to activate it.
The Robocopy command needs to know, first — which folder you want to copy and, second — where you want the copy placed. Both the source and destination need to be in quotation marks.
If you’re not certain what your drive letters are, open File Explorer and click on «My Computer.»
For example, if your User name is MyName, your Documents folder is in your C: drive and your Backup folder is in a removable storage D: drive, then the command would be:
robocopy D:\Users\MyName\Documents F:\Backup /XA:H /W:0 /R:1 > F:\Backup\backup.log
This example is a bit more complicated, since Robocopy offers you a lot of options.
D:\Users\MyName\Documents: the folder you want to back up.
F:\Backup: the location of your Backup folder.
/XA:H: ignores hidden files.
/W:0: waits zero seconds between retries, instead of the default 30 seconds.
/R:1: retry only once if the file is locked.
> F:\Backup\backup.log: create a backup log placed in the Backup folder.
Note that because this is a mirror backup, if you delete files from the source folder, they will be deleted from the Backup folder the next time you use the script. It would be a good idea to explore additional switches available for Robocopy, so that you ensure that you backup your files the way that works best for you.