Windows Admin Scripting Little Black Book (Little Black Books (Paraglyph Press))

Interacting with the User

When scripting, you might often need the ability to prompt or ask the user for input. This is useful when you need to inform the user that the script has ended, display error messages, ask for the location of a directory, and more.

Using Dialog Boxes with Shell Scripting

Shell scripting does not contain any built-in method to create dialog boxes from the command line. Msgbox.exe is a freeware utility that you can use to create dialog boxes from the command line. The basic syntax of msgbox is as follows :

Msgbox / commands " title " text

Here, title is the dialog box window title. Any characters after title will display text in the body of the dialog box. Multiple quoted phrases of text will result in multiple body lines of text. The available commands are as follows:

To create a batch file example to illustrate the use of msgbox.exe, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download msgbox.exe from http://www. jsiinc .com to the new directory.

  3. Start a command prompt and enter " scriptfile. bat."

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

@Echo Off :Start MSGBOX /H /MT /BO /I! "MSGBOX Example" "This example illustrates how to make" "dialog boxes from the command line." MSGBOX /H /MT /BARI /IS "Fake Error" "Non critical program error." "Pressing a button will continue the example." MSGBOX /H /MT /BYN /D2 /IQ "Repeat Example?" "Would you like to repeat this example?" If errorlevel 5 goto End If errorlevel 2 goto Start :End

Note  

The highlighted code above must be placed on one line.

Using Dialog Boxes with KiXtart

The KiXtart command MessageBox allows you to display a dialog box to the user. To display a dialog box using KiXtart, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and extract the latest version of KiXtart, from http://www.kixtart.org, to the new directory.

  3. Select StartRun and enter "kix32 scriptfile. "

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

MessageBox("This is a dialog box.", "DIALOG BOX", 0)

Note  

The MessageBox command supports many functions, such as allowing for different buttons and icons. See the KiXtart manual for all the included features.

Using Dialog Boxes with Windows Script Host

Windows Script Host provides several methods to display dialog boxes. In the previous chapters, you have seen the Wscript.Echo used to display command prompt lines of text to the user when invoked using CSCRIPT.EXE, the command-line Windows Script Host. If you start your scripts with WSCRIPT.EXE, the line of text will be displayed in a message box:

WScript.Echo "This is a dialog box."

Another method of displaying dialog boxes is using WshShell's PopUp :

Set SHELL = CreateObject("WScript.Shell") SHELL .PopUp "Window Text", 0, "Window Title", 0

Note  

PopUp is very similar to KiXtart's MessageBox . See the WSH documentation for all the included features.

Accepting User Input with Shell Scripting

Shell scripting does not include any method to accept user input, aside from creating temporary files and then parsing the files. Included in the resource kit is a utility called CHOICE.EXE that allows you to accept user choices (one key press) from the command line:

CHOICE /C:ABC IF ERRORLEVEL 1 ECHO You pressed A IF ERRORLEVEL 2 ECHO You pressed B IF ERRORLEVEL 3 ECHO You pressed C

Here, the /C switch states which keys are allowed for input (for example, /C:ABC ). You can determine which key has been pressed by checking the appropriate errorlevel. The first key allowed, in this example A, is associated with the first errorlevel (errorlevel 1), and so on.

Accepting User Input with KiXtart

The KiXtart command GETS allows you to store a line of user input to a variable. To accept user input using KiXtart, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and extract the latest version of KiXtart, from http://www.kixtart.org, to the new directory.

  3. Select StartRun and enter "kix32 scriptfile. "

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

GETS $variable FLUSHKB

Here, variable is the variable to store the user input. The FLUSHKB command clears the keyboard buffer.

Tip  

You can use the KiXtart command Get to accept a single key of input.

Accepting User Input with Windows Script Host

The Windows Script Host command InputBox allows you to store a line of user input to a variable. To accept user input using Windows Script Host, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

Name = InputBox("Please type enter your name:", "YOUR NAME REQUIRED", "JOHN BREYAN") Wscript.Echo "Hello " + Name

Note  

The highlighted code above must be placed on one line.

Changing the Desktop Wallpaper

KiXtart includes a command called SETWALLPAPER to change the desktop wallpaper for the current user. To change the desktop wallpaper using KiXtart, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and extract the latest version of KiXtart, from http://www.kixtart.org, to the new directory.

  3. Select StartRun and enter "kix32 scriptfile. "

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

SETWALLPAPER(" wallpaper ")

Here, wallpaper is the complete path and file name of the bitmap to use.

Working with Shortcuts

Shortcuts are merely pointers to the files and folders you use most often. Shortcuts are easily identified by their .lnk extension and are the building blocks of the Start menu. Most users live and breathe shortcuts, and would be lost without them. Through shell scripting and Windows Script Host, you can easily modify or create shortcuts anywhere on a system.

Creating Shortcuts Using Shell Scripting

SHORTCUT.EXE is a freeware utility you can use to create shortcuts from the command line. To create a shortcut using SHORTCUT.EXE, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download shortcut.exe from http://www.jsiinc.com to the new directory.

  3. Start a command prompt and enter " scriptfile. bat."

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

SHORTCUT /F:" name " /A:Create /T:" target " /W:" directory " /D:" description "

Note  

Here, name is the full path and name of the shortcut; target is the full path and name of the item to create a shortcut to; directory is the full directory path to start the target in; and description is the comment for the shortcut.

Tip  

SHORTCUT.EXE supports many command-line parameters. Type "shortcut.exe /?" for more information.

Creating Shortcuts Using KiXtart

KiXtart does not have the ability to create shortcuts, other than within the Start menu. If you want to create a shortcut somewhere else, you can create a Start menu shortcut, copy the shortcut to the desired location, and then delete the original shortcut. To create a shortcut using KiXtart, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and extract the latest version of KiXtart, from http://www.kixtart.org, to the new directory.

  3. Select StartRun and enter "kix32 scriptfile ."

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

$ SName = " name " $ STarget = " target " $ SDir = " directory " $ SDest = " destination " $ RCODE = AddProgramItem($ STarget ,$ SName ,"",0,$ SDir ,0,0) Copy "SMPDIR$ SName .lnk" $ SDest $ RCODE = DelProgramItem($SName)

Here, name is the name of the shortcut without the extension or path; target is the full path and name of the item to create a shortcut to; directory is the full directory path to start the target in; smpdir is the full path of the Start Menu\Programs directory; and destination is where to store the shortcut.

Tip  

If you just want to create a shortcut in the Start menu, simply use the AddProgramItem command.

Creating Shortcuts Using Windows Script Host

To create a shortcut using Windows Script Host, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

Set Shell = CreateObject("WScript.Shell") sNAME = " name " sTARGET = " target " sDIR = " directory " sICON = " icon " sHKEY = " hotkey " Set Scut = Shell .CreateShortcut( sNAME ) Scut .TargetPath = Shell .ExpandEnvironmentStrings( sTARGET ) Scut .WorkingDirectory = Shell .ExpandEnvironmentStrings( sDIR ) Scut .WindowStyle = 4 Scut .IconLocation = Shell .ExpandEnvironmentStrings( sICON ) Scut .HotKey = sHKEY Scut .Save

Here, name is the complete path and name of the shortcut; target is the item to place a shortcut to; directory is the item's working directory; icon is the shortcut icon to use; and hotkey is the quick key combination to activate the shortcut (for example, ALT+SHIFT+Q).

Deleting Broken Shortcuts

Shortcuts are merely pointers to a file or folder on your system, and when those target items get moved or deleted, those shortcuts are useless. To delete a broken shortcut using Windows Script Host, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

Set FSO = CreateObject("Scripting.FileSystemObject") Set Shell = CreateObject("Wscript.Shell") sDIR = directory Set objDIR = GetFolder( sDIR ) GoSubFolders objDIR Sub MainSub ( objDIR ) For Each efile in objDIR .Files fEXT = FSO .GetExtensionName( efile .Path) If LCase ( fEXT ) = LCase ("lnk") Then Set Shortcut = Shell .CreateShortcut(efile) If NOT FSO .FileExists(Shortcut.TargetPath) Then If NOT FSO .FolderExists(Shortcut.TargetPath) Then DelFile efile End If End If End If Next End Sub

Here, directory is the location to start searching for broken shortcuts.

Note  

You need to append the GoSubFolders , DelFile , and GetFolder routines, listed in Chapter 4, to this script in order for it to run.

Tip  

You can use the resource kit utility CHKLNKS.EXE to perform the same task manually.

Controlling the Start Menu

The Start menu is the central point for organizing application and system shortcuts. For every new application installed, more than likely an associated shortcut or two is installed in the Start menu. Users can spend a good portion of their day navigating through this menu to get to the application or data they want, so it is important to organize this data effectively.

Adding a Program Group with KiXtart

As you learned in the previous section, you can create Start menu shortcuts using the command AddProgramItem . KiXtart also includes a function called AddProgramGroup to create folders in the Start menu:

AddProgramGroup(" Folder ", Location )

Here, folder is the name of the group to create, and location specifies whether to place the group in the common or user Start menu. A value of 0 specifies the user Start menu, whereas a value of 1 specifies the common Start menu.

Moving All Uninstall Shortcuts to a Central Directory

When an application installer places its shortcuts in the Start menu, an uninstall icon is normally included to uninstall this product quickly and easily. Unfortunately, a user quickly browsing through the Start menu might click on an uninstall icon and accidentally remove or damage application or system files. To move the uninstall shortcuts from the Start menu to a central directory, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

Set FSO = CreateObject("Scripting.FileSystemObject") Set Shell = CreateObject("Wscript.Shell") sMENU = Shell.SpecialFolders("Programs") sDIR = "C:\UNINSTALL" If Not FSO .FolderExists( sDIR ) Then FSO .CreateFolder sDIR End If Set objDIR = GetFolder( sMENU ) GoSubFolders objDIR Sub MainSub ( objDIR ) For Each efile in objDIR .Files fEXT = FSO .GetExtensionName( efile .Path) fNAME = LCase(FSO.GetBaseName( efile .Path)) Folder = FSO .GetBaseName( objDIR ) If LCase( fEXT ) = LCase("lnk") Then If InStr( fNAME , "uninstall") <> 0 Then If fNAME = "uninstall" Then efile .Name = fNAME & " " & Folder & "." & fEXT End If MoveFile efile , sDIR End If End If Next End Sub

Note  

You need to append the GoSubFolders , MoveFile , and GetFolder routines, listed in Chapter 3, to this script in order for it to run.

Deleting Old User Profiles

Whenever a new user logs on, a user profile is created. User profiles consist of the user's own personal Start menu, shortcuts, and user registry. As time progresses, profiles can take up a good portion of hard drive space. DELPROF.EXE is a Windows 2000 resource kit utility that allows you to delete old profiles that haven't been used for a while. To delete old user profiles, proceed as follows:

DELPROF /Q /I /D: days

Here, /Q disables prompting during profile deletion; /I instructs DELPROF to ignore errors and continue deletion; and /D indicates to delete profiles inactive more than the specified number of days .

Note  

If a specific user profile cannot be deleted by DELPROF, it might be in use. This includes the current user profile and profiles belonging to accounts associated with running services. You will need administrative privileges to delete other user's profiles.

Managing Services from the Command Line

Services are processes that run in the background, independent of a user logon. Normally, these services are managed manually through the Control PanelServices applet, but in this section you will learn how to manage services from the command line.

Installing a Service

INSTSRV.EXE is a resource kit utility to install a service from the command line. To install a service, start a command prompt and enter the following:

INSTSRV name exe a account p password

Here, name is the name to give the service; exe is the path and name of the executable to run; account is the name of the account to run the service under; and password is the password of the account.

Note  

After you install a service with INSTRV.EXE, the service is not automatically started. See the following section on starting services from the command line.

Uninstalling a Service

To uninstall a service, start a command prompt and enter the following:

INSTSRV name Remove

Here, name is the name of the service to uninstall. The keyword remove instructs INSTSRV to uninstall the service.

Related solution:

Found on page:

Deleting a Service

189

Starting a Service

You can use the NET command to control services from the command line. To start a service from the command line, start a command prompt and enter the following:

NET START " service "

Here, service is the name of the service to start.

Related solution:

Found on page:

Starting Services

186

Pausing a Service

To pause a started service from the command line, start a command prompt and enter the following:

NET PAUSE " service "

Here, service is the name of the started service to pause.

Related solution:

Found on page:

Pausing Services

188

Resuming a Service

To resume a paused service from the command line, start a command prompt and enter the following:

NET CONTINUE " service "

Here, service is the name of the paused service to resume.

Related solution:

Found on page:

Resuming Services

189

Stopping a Service

To stop a started service from the command line, start a command prompt and enter the following:

NET STOP " service "

Here, service is the name of the started service to stop.

Related solution:

Found on page:

Stopping Services

187

Managing NTFS from the Command Line

In Chapter 4, you learned how to modify file and folder properties. NTFS adds additional properties that you can modify through scripting.

Modifying NTFS Permissions

The Windows 2000 resource kit utility XCACLS.EXE allows you to change NTFS permissions from the command line. Most administrators use this utility in a batch file to lock down their desktops and servers. To secure the %WINDIR% \Repair directory access to just administrators, start a command prompt and enter the following:

XCACLS C:\ %WINDIR% \REPAIR\*.* /G administrators:F

Tip  

XCACLS contains many command-line parameters. Enter "XCACLS /?" for more information.

Changing a File Owner

The resource kit utility SUBINACL.EXE allows you to view or modify file, registry, and service security properties. You can use this utility to change the NTFS owner of a file. To set a new owner using SUBINACL.EXE, start a command prompt and enter the following:

SUBINACL /FILE/ filename /SETOWNER= ownername

Here, filename is the full path and name of the file whose ownership is to be changed.

Managing NTFS Encryption

Although NTFS permissions allow you to secure your files and folders from other users, several methods are available to bypass this security (for example, NTFSDOS). Windows 2000/XP/2003 uses an encrypting file system (EFS) to secure your files.

Tip  

The Microsoft Knowledge Base article Q255742 explains several methods to recover data from encrypted files, even if the private key is lost.

Encrypting Files from the Command Line

CIPHER.EXE is a utility that allows you to encrypt/decrypt your files from the command line. This utility supports the following parameters:

Warning  

Encrypted files cannot be read during the boot process. Encrypting files that the system needs to access while booting will cause your system not to boot.

To silently encrypt all the files and folders within a directory, start a command prompt and enter the following:

CIPHER /E /A /S /F /Q /H " directory "

Here, directory is the folder to encrypt.

Decrypting Files from the Command Line

To decrypt all the files within a directory, start a command prompt and enter the following:

CIPHER /D /A /S /Q " directory "

Here, directory is the folder to encrypt.

Managing Shares from the Command Line

Shares allow users to access resources from one common source on the network. As more and more systems and devices are added and shared on your network, managing shares can become an intensive chore.

Listing Shares

You can list shares from the command line using the built-in NET command. To list all shares from the command line, start a command prompt and enter the following:

NET SHARE

Adding Shares

Sharing a resource makes that object available on the network. To share a resource from the command line, start a command prompt and enter the following:

NET SHARE name = path /USERS: maxnum /REMARK:" comment "

Here, name is the name of the share; path is the path to create the share to; maxnum is the maximum number of users allowed to simultaneously access the share; and comment is the comment to give the share.

Tip  

If you want to allow an unlimited number of users to access the share simultaneously, replace the /users: maxnum switch with the /unlimited switch.

Related solution:

Found on page:

Creating a Share

180

Removing Shares

To delete a share from the command line, start a command prompt and enter the following:

NET name /DELETE

Here, name is the name of the share.

Tip  

/D is the abbreviated form of the /DELETE switch. When you delete a share, you are only disabling sharing for that resource, not deleting that resource.

Related solution:

Found on page:

Deleting a Share

181

Copying Share Permissions

Currently, there is no Microsoft method to set share permissions from the command line. However, you can use the resource kit utility PERMCOPY.EXE to copy permissions from one share to another. To use PERMCOPY.EXE to copy permissions from one share to another, start a command prompt and enter the following:

PERMCOPY \ source sname \ destination dname

Here, source is the computer containing the share ( sname ) with proper permissions; and destination is the computer containing the share ( dname ) to copy permissions to.

Tip  

Supplying both the source and destination with the local computer name will copy permissions from one local share to another.

Warning  

Do not use PERMCOPY.EXE to copy permissions on administrative shares (for example, C$). This will cause SERVICES.EXE to crash.

Creating Shares with Permissions

Currently, there is no Microsoft method to create shares with permissions from the command line. RMTSHARE.EXE is a Windows 2000 resource kit utility to create shares with permissions on remote stations . You can provide this utility with the local computer name to create shares with permissions on the local station. To use RMTSHARE.EXE to create shares with permissions, start a command prompt and enter the following:

RMTSHARE \ computer \ name = path /GRANT guser :permission /REMOVE ruser

Note  

The code above must be placed on one line. Here, computer is the computer name to create the share on; name is the name of the share; path is the path to create the share to; guser is the username to grant permissions to; and ruser is the username to deny share access to.

Tip  

RMTSHARE.EXE also supports the same switches as the NET SHARE command.

Calling System Events

In Chapter 5, you learned how to call system events (for example, shutdown, restart) using DLL calls. In this section, you will learn how to call these events without using DLL calls.

Shutting Down/Restarting the Computer in Windows 2000

The resource kit utility SHUTDOWN.EXE allows you to shut down or restart Windows. The basic syntax of the SHUTDOWN command is:

SHUTDOWN parameters

The available parameters for SHUTDOWN.EXE are as follows:

Warning  

Using the /C switch will close all applications without saving and might result in losing data. Use this switch only when you are certain that the local machine does not have any open unsaved files.

Related solution:

Found on page:

Shutting Down a System

191

Logging Off a User

The resource kit utility LOGOFF.EXE allows you to log off a user from a current Windows session. The basic syntax of the LOGOFF command is:

LOGOFF /F /N

Here, /F force-closes all running applications and /N removes any user prompts.

Warning  

Using the /F switch will close all applications without saving and may result in losing data. Use this switch only when you are certain that the local machine does not have any open unsaved files.

Shutting Down/Restarting the Computer in Windows XP/2003

Windows XP/2003 includes the SHUTDOWN command, which you can use to shut down or restart Windows. The basic syntax of the SHUTDOWN command is:

SHUTDOWN parameters

The available parameters for SHUTDOWN.EXE are as follows:

Warning  

Using the -F switch will close all applications without saving and might result in losing data. Use this switch only when you are certain that the local machine does not have any open unsaved files.

Related solution:

Found on page:

Shutting Down a System

161

Logging Off a User in Windows XP/2003

To log off the current user session using the SHUTDOWN command, start a command prompt and enter the following:

SHUTDOWN -L

Windows XP/2003 also provides the LOGOFF command to log off a user from a Windows session. To log off the current user session using the LOGOFF command, start a command prompt and enter the following:

LOGOFF

Категории