Windows Automation Toolkit
Windows Automation Toolkit
PUBLISHED BY
Microsoft Press
A Division of Microsoft Corporation
One Microsoft Way
Redmond, Washington 98052-6399
Copyright © 2005 by Microsoft Corporation
All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or
by any means without the written permission of the publisher.
Library of Congress Control Number: 2005922202
Printed and bound in the United States of America.
1 2 3 4 5 6 7 8 9 QWT 9 8 7 6 5 4 3
vii
viii Contents
6 Server Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Enable Shadow Copy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Under the Hood. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Troubleshooting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Inventory Shadow Copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Under the Hood. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Troubleshooting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
List Internet Explorer Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
List Network Adapter Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
List Installed Service Pack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
List Scheduled Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
xii Contents
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Clear Print Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Print Test Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
List Running Processes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Start a Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
xiv Contents
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
List Disk Quotas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
Enable or Disable Disk Quotas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
Create Shared Folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Copy Shared Folder Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
xviii Contents
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Create DNS Host Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Create Print Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Change an Attribute for Multiple Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Disable Old User Accounts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Delete Published User Certificates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Expire Passwords. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Performing This Task Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Under the Hood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
To Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
xxiv Contents
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
xxxi
A07IX1106977.fm Page xxxiii Tuesday, April 5, 2005 9:49 AM
Introduction
Welcome to Microsoft® Windows® Administrator’s Automation Toolkit. This book is
designed to help you quickly automate over 100 common Windows administrative
tasks. In some cases, I show you how to automate tasks using existing tools such as
those included with the Windows operating system or those available for download
from the Web. In many other cases, however, I provide you with tools that I designed
to help you get the job done. These tools are all written in Microsoft Visual Basic®
Scripting Edition (VBScript), and execute under the Windows Script Host (WSH),
which is included with the Windows operating system. Just because these tools are
written in VBScript doesn’t mean that you need to know anything about scripting. In
fact, I’ve purposely written the tools in a format that allows you to simply run them as
command-line tools, meaning that you don’t need to encounter any scripting at all.
However, because the tools are written in VBScript, you have the option of opening
them up in Microsoft Notepad or in another script editor and making changes to
them, extending their capabilities, and so forth. In fact, I’ll even give you some
pointers for doing that in the first few chapters.
Document Conventions
The next sections describe the conventions used in this book.
Reader Alert Conventions Reader alerts are used throughout the book to point out
useful information.
xxxiii
A07IX1106977.fm Page xxxiv Tuesday, April 5, 2005 9:49 AM
xxxiv Introduction
Element Meaning
Bold font Characters that you type exactly as shown, including com-
mands and parameters. User interface elements also appear in
boldface type.
Italic font Variables for which you supply a specific value. For example,
Filename.ext can refer to any valid file name.
Monospace font Code samples.
%SystemRoot% Environment variable.
Introduction xxxv
Support Policy
Microsoft does not support the tools supplied on the Microsoft Windows Administra-
tor’s Automation Toolkit CD. Microsoft does not guarantee the performance of the tools
or any bug fixes for these tools. However, Microsoft Press provides a way for custom-
ers who purchase Windows Administrator’s Automation Toolkit to report any problems
with the software and to receive feedback for such issues. To report any issues or prob-
lems, send an e-mail message to [email protected]. This e-mail address is only for
issues related to Windows Administrator’s Automation Toolkit.
Microsoft Press also provides corrections for books and companion CDs through the
World Wide Web at http://www.microsoft.com/learning/support/. To connect directly
to the Microsoft Knowledge Base and enter a query regarding a question or issue you
have, go to http://support.microsoft.com. For issues related to the Windows family of
operating systems, refer to the support information included with your product.
You’re also welcome to contact the author at http://www.ScriptingAnswers.com to ask
questions or discuss problems that you might have regarding the scripts included on
the CD that accompanies this book.
System Requirements
To use the Microsoft Windows Administrator’s Automation Toolkit companion CD-ROM,
you’ll need a computer equipped with the following configuration:
You will also need to have the Windows Script Host (WSH) version 5.6 or later,
installed. WSH is a core component of Windows 2000 and later, so unless you’ve
taken special steps to remove the software, it should already be installed.
A07IX1106977.fm Page xxxvi Tuesday, April 5, 2005 9:49 AM
Part I
Understanding Windows
Automation
Chapter 1
Windows Automation
Essentials
In this chapter:
Automating Windows Administration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
VBScript and the Windows Script Host . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Command-Line Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3
4 Part I: Understanding Windows Automation
Unfortunately, VBScript does carry a pretty hefty learning curve, and even the com-
mand-line utilities provided by the Windows operating system, which are easier to use
than VBScript, can be somewhat daunting for many busy administrators who don’t
have time to learn them. That’s where this book comes in handy. Rather than trying to
teach you scripting, or even just listing all the available command-line tools, this book
offers a task-oriented approach to automation. Simply look up the task you want to
automate, fill in a few blanks, and you’re ready to go. Even though many of these tasks
are automated through the power of VBScript and COM, you won’t need to know very
much about either to use this book.
You will, however, need to know a few basics, such as how to run and edit the scripts
(which all appear on the CD that accompanies this book) and the command-line
tools. That’s what this chapter will cover. In keeping with the just-get-started spirit of
this book, I’ll be covering this material quickly using minimal details, but I’ll provide
you with some references throughout in case you’d like to learn more about these
technologies on your own.
Tip If you’re interested in teaching yourself to write VBScript, I can recommend two
sources. One is Managing Windows with VBScript and WMI (Addison-Wesley, 2004), a
book I wrote that takes a step-by-step approach to administrative scripting. Another
option is Ed Wilson’s Microsoft Windows Scripting Self-Paced Learning Guide (Microsoft
Press, 2004), which is conveniently included in e-book format on the CD that accom-
panies this book. Once you’ve moved a bit beyond the basics, you can visit my Web
site, http://www.ScriptingAnswers.com, where you’ll find a variety of free resources for
Windows administrators who are using scripts to automate their environments.
Tip Generally, the latest version of WSH is included with the most recent service
pack for the Windows 2000 product family and later. However, I recommend down-
loading and installing WSH 5.6 regardless, unless you’ve checked the file properties for
%systemroot%\System32\WScript.exe and assured yourself that you have the latest
version.
WSH is available in two flavors, both of which are included in all WSH installations:
WScript and CScript.
WScript
WScript (manifested as WScript.exe on your computer) is the default version of WSH
on newly installed Windows-based systems. Simply put, that means double-clicking a
WSH-related file format (such as .js, .vbs, and .wsf) causes the script to execute in
WScript. WScript is designed for a graphical environment (the “W” stands for “Win-
dows”), so many of WSH’s built-in commands generate graphical displays. For exam-
ple, the built-in WScript.Echo command displays a simple dialog box with an OK
button. The only downside to running a script using WScript is that some scripts out-
put a lot of information, and having to click OK after each message can become annoy-
ing for users. For that reason, many administrators prefer to run their scripts using
CScript.
Tip If WScript isn’t the default script host, you can make it the default. Open a com-
mand-line window and execute WScript //H:WScript.
CScript
CScript (manifested as CScript.exe on your computer) is designed to execute com-
mand-line scripts. The primary difference between CScript and WScript can be seen
when running commands like WScript.Echo. When running in CScript, this com-
mand outputs text to the command line and continues without waiting; in WScript, as
described earlier, the command displays a dialog box and waits for the user to click
OK. As you can imagine, CScript’s handling of WScript.Echo is much more
appropriate when a lot of information is being produced, because you can just watch
6 Part I: Understanding Windows Automation
the information scroll by in the command-line window and not click any buttons. For
most of the scripts in this book, I assume that you are setting CScript as the default
host. If you’re not, many of the scripts in this book will remind you to use CScript so
that their extensive output isn’t displayed in dozens of dialog boxes. Having to click
dozens of OK buttons can be tiresome!
Tip If CScript isn’t the default host, you can make it the default. Open a command-
line window and execute CScript //H:CScript.
WSF Scripts
Most of the scripts in this book are presented in the Windows Script Files (WSF) for-
mat. I’ll discuss that format in more depth in Chapter 3, “Working with VBScript,” but
for now be aware that few of these scripts can be successfully executed simply by dou-
ble-clicking them. In most cases, you have to run a script from a command line, pro-
viding one or more command-line switches to specify server names, operational
parameters, and so forth, just as you would with any command-line utility. Be sure to
read the instructions included with each task for details about running the scripts.
For example, a script named Restart.wsf might be executed by typing the following:
In most cases, switches for scripts in this book are specified by starting with a forward
slash, the name of the switch, a colon, and the value you’re providing for the switch.
These scripts are written in VBScript, so they aren’t much different from a more tradi-
tional command-line utility—generally you can even use the /? switch to see a list of
the script’s command-line switches and an example of how to use the script.
Chapter 1: Windows Automation Essentials 7
Scripts can be readily reviewed in a simple text editor such as Microsoft Notepad. WSF
files, however, have XML formatting that can make the actual scripts somewhat diffi-
cult to read. In these cases, you can consider a commercial script editor, such as
SAPIEN PrimalScript (http://www.primalscript.com), XLnow OnScript (http://
www.onscript.com), Adersoft VBSEdit (http://www.vbsedit.com), and Admin Script Edi-
tor (http://www.adminscripteditor.com). Most of these tools are available as trial ver-
sions so that you can try them to determine whether you like them. Free tools like the
Programmer’s File Editor (downloadable from http://www.download.com) can also be
useful because they provide more script-specific formatting than Notepad. Search for
“Programmer File Editor or PFE.”
Scripts should always be tested in a dedicated test or lab environment, preferably one
that mimics your production environment to the greatest degree practical. For exam-
ple, I use Microsoft Virtual PC to build virtual domain controllers and member servers
that are configured similarly to my production servers. This allows me to test scripts
on the virtual servers before deploying the scripts to production. You can even use Vir-
tual PC features to undo the results of a test, instantly reverting the virtual environ-
ment to its pretesting state so that the environment is ready for another test.
Command-Line Tools
You can accomplish many of the automation tasks in this book not with scripts but
with the many command-line tools included with Windows Server 2003, with the
Support Tools supplied on the Windows Server 2003 CD, or with tools downloadable
from the Microsoft Web site. Third-party tools aren’t used in this book because guar-
anteeing their long-term availability is difficult, but you should definitely spend some
time exploring the Web to locate other useful command-line tools.
Whenever a tool isn’t available as part of a basic Windows Server 2003 installation, I
provide information about where you can obtain the tool. I’ve focused entirely on
freely available tools, so even though you might have to download the tool, you won’t
have to pay any extra for it—either your use of the tool is included in your Windows
Server 2003 license or the tool is freely available to anyone. Please note, however, that
tools not included with the Windows operating system might be unsupported. If the
8 Part I: Understanding Windows Automation
tools don’t work as described in your environment, you won’t be able to contact
Microsoft Product Support Services (PSS), myself, or the publisher of this book for
assistance. Rest assured that everything worked when I tested it, but because of varia-
tions in your environment, a particular tool or technique might not work for you in the
way described. I do invite you to visit my Web site, http://www.ScriptingAnswers.com,
where you can post a message in the Forums and receive help from other site users
about getting the tool to work in your environment.
Summary
In this chapter, you were introduced to the world of scripting and automation so that
you can begin using the various scripts included in this book. You should now under-
stand the differences between WScript.exe and CScript.exe, as well as know where to
find the various command-line tools used throughout this book.
If you’d like to modify any of the scripts included in the CD that accompanies this
book, be sure to check out Chapter 3, “Working with VBScript,” in which I explain the
WSF format and the standards used in producing these scripts. However, before you
do anything else, I strongly recommend that you read the next chapter, which will
deal with the all-important issue of security as it relates to scripting and automation.
Chapter 2
Automation and Security
In this chapter:
Windows Script Host Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Remote Scripting and Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Unfortunately, the same beneficial technologies that make scripting and automation
possible can also be used to create malicious software. Many viruses, for example,
have been written in Microsoft Visual Basic® Script (VBScript), even though VBScript
is also an excellent tool for automation. Configuring your environment to allow bene-
ficial administrative scripts while protecting your environment against malicious
scripts is a crucial skill you must master before proceeding.
What Not to Do
I’ve run across three basic methods that various administrators have cobbled together
to “protect” their environments from malicious scripts. None of these methods, how-
ever, are foolproof, and they might offer a dangerous false sense of security.
9
10 Part I: Understanding Windows Automation
possible for Windows® to replace the files if they’re deleted. Further, these files are
part of the core Windows operating system (and have been since Windows 2000), so
they show up in some hotfixes, in all service packs, and so forth, presenting a number
of opportunities for the files to be replaced, even if you delete them. As a result, you
might think you’ve deleted the files, but the files are likely to come back at some point,
leaving you just as vulnerable as you were before you deleted them.
However, it’s a fairly trivial task for an attacker to execute scripts anyway. WScript.exe
and CScript.exe accept the name of any text file, regardless of its name or extension,
and attempt to execute the file if it contains something recognizable as a script. Attack-
ers need only to create a batch file, Program Information File (PIF), or other file that
launches WScript.exe or CScript.exe and passes the name of a complete script. Even
though the .vbs file name might no longer be associated with WSH, a VBScript file can
still be executed. Essentially, changing the file name extension associations offers no
protection whatsoever; it’s merely a speed bump in an attacker’s way.
Understanding Trust
The key to scripting security is to allow your scripts (or other beneficial scripts) to exe-
cute while preventing other people’s scripts from running. In other words, you want
to allow trusted scripts to run but prevent untrusted scripts from running. That’s a sim-
ple enough concept, but you need some means of helping WSH distinguish between
the scripts you trust and the ones you don’t. For example, could you tell WSH that
scripts coming from a certain intranet file server are trusted but others aren’t? Bad
idea—malicious scripts could be too easily copied to your “trusted” location, fooling
Chapter 2: Automation and Security 11
WSH. Also, the scripts in your “trusted” location could be modified, which should in
theory render them untrusted until you have a chance to review them and decide they
can be trusted again.
Digital certificates provide a way of identifying trusted scripts. How? You start by iden-
tifying a trusted root certification authority. This is an internal or external organization
that you believe does a good job of ensuring the identity of individuals and organiza-
tions to whom they issue digital certificates. In other words, if a certification authority
(CA) issues a certificate to Microsoft, you need to trust that the CA did a good job of
confirming Microsoft’s corporate identity before issuing that certificate.
This certificate works kind of like a driver’s license. You might not realize it, but every-
one in the United States pretty much accepts all the departments of motor vehicles as
trusted CAs of sorts. When the photo on a person’s driver’s license matches his face,
you accept his identity as stated on the license. The license in this sense acts as a cer-
tificate, and the issuer of that license is the CA. Passports serve a very similar function
on an international level. We all trust that the authorities issuing these documents
have done a good job of confirming the document holder’s actual identity and that
the information on the document is accurate and trustworthy. If one state’s depart-
ment of motor vehicles started issuing licenses to anyone who asked for them without
requiring any proof of identity, we’d all eventually stop trusting that state’s depart-
ment as a CA and stop accepting the licenses it issued.
So who do you trust? On your computer, go to Control Panel and open Internet
Options. Select the Content tab and click the Publishers button. Then, select the
Trusted Root Certification Authorities tab. You trust each CA listed, meaning you
firmly believe that each of them does a good job of validating the identities of their cer-
tificate recipients. Wait a minute--what did you say? You don’t trust all of those CAs? In
reality, you probably have no idea what procedures most of those CAs use to validate
certificate recipients’ identities, and for that reason you should consider modifying
the list to remove the CAs you don’t explicitly trust or know about. Do some research,
if necessary, to discover what procedures those CAs use, and leave the ones whose
procedures you feel are trustworthy and thorough. Remove the others.
Tip In a domain-based environment, you can use Group Policy to centrally config-
ure the trusted CA list on domain client computers running Windows 2000 Profes-
sional or Windows XP Professional, as well as server computers running Windows 2000
or Windows Server™ 2003.
Why are these CAs so important? Because among other tasks, they issue code-signing
certificates, which are used to digitally sign program code such as scripts. WSH 5.6
(which is a free download from http://www.microsoft.com/scripting) can be configured
to run only those scripts that are digitally signed using a certificate issued from a
12 Part I: Understanding Windows Automation
trusted CA. Sound confusing? It’s not. A trusted CA—that’s one on the list in Internet
Options—issues a code-signing certificate. That certificate is used to sign a script,
which WSH will regard as trusted and which WSH will run normally. WSH can be
configured to not run untrusted scripts, which are all scripts that are unsigned and
that were signed using a certificate issued by an untrusted CA.
Signing provides two important assurances. First, it tells you the identity of the
script’s author (assuming the issuing CA did a good job of verifying that identity prior
to issuing the script). If a script turns out to be malicious, you have a good shot at
tracking down the author. Second, a signature assures you that the script wasn’t
changed since it was signed. If it was changed, the signature will be invalid; this
ensures that the script is exactly as the author intended it.
Then, you write a very short script to do the actual signing. Assuming your certificate
has a name of “IT Department” and that you want to sign the script C:\MyScript.vbs,
you’d use the following code:
It’s really that easy. A signature block is written into C:\MyScript.vbs, and the script is
signed. From that point, you can’t edit the script unless you plan to sign it again later;
the signature itself includes a sort of fingerprint for the script, and if the script
changes, the signature becomes invalid.
On the CD All scripts included on the CD that accompanies this book were signed
using a digital certificate issued by Microsoft. All computers running Windows will, by
default, trust the issuer of this certificate and allow these scripts to run even when
WSH is configured to not run untrusted scripts. However, if you modified the list of
trusted root certification authorities, your computer (or computers) might not trust
the scripts included on the CD that accompanies this book. In that case, you will need
to either reconfigure your computer to trust the Microsoft certification authority, or
re-sign the scripts using a certificate that your computer has been configured to trust.
Chapter 2: Automation and Security 13
I should point out that some professional script editors include built-in script signing
capabilities. SAPIEN PrimalScript (http://www.sapien.com), for example, allows you
to specify a certificate and have all scripts automatically signed using that certificate
each time the script is saved. This convenient feature can make utilizing the WSH
trust policy more practical, because your scripts will always be properly signed (and
therefore trusted). Many script editors—SAPIEN PrimalScript as well as XLnow
OnScript (http://www.onscript.com)—include features that integrate with WSH trust
policy, allowing you to configure the trust policy on your script development com-
puter by using a graphical user interface.
Of course, manually configuring all your computers to the desired registry settings
can be time-consuming. You could implement logon scripts written in VBScript
(which will run even when unsigned, thanks to the default WSH trust policy setting of
zero) that sets the desired registry values accordingly. For example:
This code snippet sets the per-user TrustPolicy value to 2. Keep in mind that on com-
puters running Windows XP and Windows Server 2003, the per-user setting (and the
per-machine setting, for that matter) will not have any effect as long as the UseWIN-
SAFER value is set to its default of 1. Alternatively, you can push this registry setting
out via Group Policy. I created a Group Policy administrative template (an .adm file)
that you can import into a Group Policy object (GPO) to configure all WSH-related
registry settings. You can download this template from the Downloads section of
http://www.ScriptingAnswers.com. A copy is also included on the CD that accompanies
this book.
At that point, the registry settings kick in. If UseWINSAFER is set to 1 on computers
running Windows XP or Windows Server 2003, WSH stops checking because SRP
has precedence. If UseWINSAFER is set to 0 on all computers running versions of Win-
dows other than Windows XP and Windows Server 2003, WSH continues checking.
(Keep in mind that WSH runs on everything from Windows 95 to later versions,
although SRP is present only on Windows XP and Windows Server 2003.) If the
IgnoreUserSettings value is 0 (zero), WSH checks the TrustPolicy value under
HKEY_CURRENT_USER. If the value is missing or set to zero, untrusted scripts are
executed. If the value is set to 1, the user is prompted before an untrusted script is run.
If the value is set to 2, untrusted scripts are not run. Trusted scripts always run, of
course. If IgnoreUserSettings is set to 1, the TrustPolicy value under
HKEY_LOCAL_MACHINE is used instead. In any event, WSH will display an error
message whenever it refuses to execute an untrusted script, provided the SilentTermi-
nate value is set to 1 and not 0 (zero).
If you’ve implemented the WSH trust policy features as outlined, these antivirus
script blocking features become more of an annoyance than a real protection.
Consider disabling that particular feature of the antivirus software, unless the
software can mimic the WSH trust policy functionality of running trusted
scripts without prompting the user. That will give you an extra layer of protec-
tion, which is always a good idea. However, an antivirus solution that forces
users to approve even signed, trusted scripts is simply an annoyance.
remote scripting. In the next few sections, I’ll help you understand how remote script-
ing and security work together, and how you can configure your computers to most
effectively respond to your remote scripts while maintaining an acceptable level of
security against potentially malicious scripts.
Basic Scripts
Generally speaking, all scripts that you run will execute with whatever permissions
your user account has. If your script is connecting to a remote file share and trying to
delete a file, your user account must have the necessary permissions on the remote
computer to delete the file. For basic operations like file and folder manipulation
and registry manipulation, WSH doesn’t provide any means of passing an alternate
set of credentials. However, that doesn’t mean you can’t execute scripts under alter-
nate credentials.
For example, you might log on to your client computer using a nonadministrative
account. (Doing so is always a good idea and is in keeping with the Principle of Least
Privilege. By using a nonadministrative account, you limit the amount of damage
something like a virus can cause.) However, you might need to run a script that mod-
ifies files on a remote file server and that requires domain administrator permissions
to do so. WSH doesn’t allow you to provide an alternate user name and password, but
you can execute your script using the Windows built-in Runas command, which does
allow you to specify alternate credentials. If your script was named C:\MyScript.vbs,
you’d simply execute the following:
The credentials WMI uses must have some specialized permissions on the remote
computer. Local administrators usually have the necessary permissions (they do by
default, at least), but if you provide nonadministrator credentials, some extra configu-
ration of the remote computers might be required. Specifically, you’ll need to modify
the Distributed Component Object Model (DCOM) permissions so that the user cre-
dentials used by WMI have the DCOM Remote Launch privilege. (Refer to http://
msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/
connecting_through_windows_firewall.asp for details.)
Tip Rather than spend hours reconfiguring your remote computers, I recommend
you use a user account that has administrative privileges on the remote computers. A
user account that is a member of the Domain Admins group, for example, is perfect.
Although you might not use this user account to run the scripts, you can provide the
account’s credentials to the script so that WMI will work properly without complex
reconfiguration of the remote computer.
Firewalls
Remember that many versions of Windows, including Windows XP and Windows
Server 2003, include built-in firewall software. On Windows XP Service Pack 2 and
later, and on Windows Server 2003 Service Pack 1 and later, that firewall software is
enabled by default. Other computers might have third-party firewall software enabled.
In any case, where a firewall is enabled, you might not be able to establish the type of
connection necessary to run scripts on remote computers, because those computers’
firewalls might block the necessary TCP/IP ports. WMI scripts, for example, require
specific TCP ports to connect to remote computers; scripts that utilize Active Direc-
tory Services Interface (ADSI) use different ports to connect to remote computers.
Whenever a script generates an error indicating that it cannot connect to a remote
computer, always start your troubleshooting process by checking that remote com-
puter’s firewall software. You can temporarily disable the remote computer’s firewall
and see whether your script starts to work; if it does, you know that the firewall was
blocking the script’s access to the remote computer. In that case, you’ll need to recon-
figure the firewall to permit the necessary traffic.
18 Part I: Understanding Windows Automation
Caution Do not reconfigure firewall software without first checking your organiza-
tion’s policies regarding firewall configuration. You might need to obtain permission
before modifying the firewall, and you should document any changes you make.
Typically, server computers always allow traffic related to services that they offer, such as
Active Directory®, and file and print sharing. Client computers often have more restric-
tive firewall settings and might not allow any incoming traffic. Scripts that use the File-
SystemObject (FSO) object to manipulate files and folders on remote computers need the
Windows Firewall’s File and Print Sharing exception enabled (on Windows XP Profes-
sional with Service Pack 2 or later, and on Windows Server 2003 with Service Pack 1).
Scripts that connect to WMI on remote computers need a special exception added to
the Windows Firewall (again, on Windows XP Professional with Service Pack 2 or later,
and on Windows Server 2003 with Service Pack 1). This is a one-time process and
requires you to run two command-line utilities on the computer running the script:
You also have to configure the remote computers to allow the incoming WMI traffic:
Note The preceding steps assume that the computers’ Windows Firewall software is
not being centrally controlled through Group Policy. If Group Policy is being used to
configure Windows Firewall, you must apply these changes within Group Policy
instead. Consult the documentation for your version of Windows to determine the
proper Group Policy configuration.
Other firewall software will require different steps to allow TCP port 135; consult the
software’s documentation for instructions.
Summary
Although scripting can be an excellent way to automate Windows administrative
tasks, scripting can also be used to create malicious software. And because scripting
has been used maliciously so often in the past, many managers and administrators are
wary of allowing any kind of scripting in their environments. However, Windows
Script Host 5.6 was specifically designed with new script-related security features,
allowing you to ensure, if desired, that only the scripts you create can execute in your
environment. The key lies in digital signatures, which form the basis for a chain of
trust that allows WSH to distinguish between trusted and untrusted scripts.
Chapter 3
Working with VBScript
In this chapter:
The File Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Running WSF Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Windows Script Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Editing VBScript Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Although you can automate many of the tasks in this book by using simple command-
line tools, you can automate others by utilizing VBScript files. As you’re aware,
VBScript offers a powerful, flexible, and relatively easy-to-understand scripting lan-
guage that can harness many of the features built into the Windows® operating system.
Another advantage of VBScript is that its scripts are contained in simple text files. This
makes scripts in general easier for you to modify and this book’s scripts in particular
a starting point for any number of other automation scripts.
19
20 Part I: Understanding Windows Automation
Note Don’t worry that some of the lines of code seem to wrap from line to line at
unusual points. You’re not meant to type this script in yourself; like all other scripts in
this book, you’ll find the complete script included on the CD that accompanies this
book.
Does not change the service’s logon ACCOUNT, just the password.
</usage>
</runtime>
<script id="Updsvc" language="VBScript">
<![CDATA[
‘==========================================================================
‘
‘ Updsvc
‘
‘ AUTHOR: Don Jones
‘ DATE : 7/31/2004
‘
Chapter 3: Working with VBScript 21
‘ COMMENT:
‘
‘==========================================================================
If Err = 0 Then
’connected - retrieve specified service instance
Set oService = oWMIService.ExecQuery _
("Select * from Win32_Service WHERE Name" & _
" = ’" & sService & "‘")
If Err = 0 Then
’retrieved - change password for the service
errReturn = oService.Change( , , , , , , _
, sPassword)
If errReturn = 0 Then
’change successful
WScript.Echo sClient " changed."
22 Part I: Understanding Windows Automation
Else
’change not successful
WScript.Echo sClient " not changed."
End If
Else
’no matching instances of Win32_Service found
WScript.Echo sClient & ": Error retrieving service"
End If
Else
’couldn’t connect to remote WMI service
WScript.Echo sClient & ": Error connecting"
End If
Else
’input file does not exist
WScript.Echo "Input file does not exist"
End If
]]>
</script>
</job>
</package>
Notice that except for some elements like <script> and </job>, the preceding listing
looks pretty much like a standard VBScript listing. Because WSF files use an XML-
based formatting system, however, there are a few important elements to call to your
attention.
Next is a <comment> section, which allows you to include a description of the entire
WSF file. This is an optional section, and some scripts don’t include it. Notice in the
Chapter 3: Working with VBScript 23
preceding listing that my WSF file contains a comment indicating it was generated by
a wizard within the script editor I use:
<comment>
PrimalCode wizard generated file.
</comment>
The next two lines define the job, or the script, contained within the WSF file.
Although WSF files can actually contain multiple jobs (you use a command-line argu-
ment to specify which job you want to run), this capability isn’t used in this book. I
find it easier to utilize scripts when only one job is contained within the file. The job
definition lines perform two important tasks: enabling or disabling both error mes-
sage display and debugging capabilities.
As you can see from the preceding lines, this script will not display error messages and
will not allow a debugger (such as the Windows Script Debugger) to be launched
should an error occur. Many of the scripts in this book will specify these options, mak-
ing these scripts cleaner looking and cleaner running command-line tools. Feel free to
change the “false” values to “true” if you’d like to enable error messages or debugging.
Tip If you plan to debug scripts, you need a debugger. Microsoft provides a basic
free debugger, the Windows Script Debugger, at http://www.microsoft.com/scripting.
Microsoft Visual Studio® can also be used to debug scripts, although I don’t find it to
be well-suited to that task because it’s such a big, complex tool. Some script editors,
such as SAPIEN PrimalScript (http://www.primalscript.com) and XLnow OnScript
(http://www.onscript.com) include built-in debuggers of their own.
The last major XML section in the WSF file is the <runtime> section:
<runtime>
<description>
Updates services accounts, running on computers listed in a text file, to use a new
logon password.
</description>
<named helpstring="Filename from which to read computer names"
name="file" required="true" type="string"/>
<named helpstring="Service name to change"
name="service" required="true" type="string"/>
<named helpstring="New password service should use to log on"
name="password" required="true" type="string"/>
<usage>
24 Part I: Understanding Windows Automation
Example:
Does not change the service’s logon ACCOUNT, just the password.
</usage>
</runtime>
Most of the subsections under <runtime> are optional, but I include them in this
book’s scripts for completeness. First is the <description> section, which provides a
text description of the script. Last—permit me to skip ahead a bit—is the <usage> sec-
tion, which provides an example of how the script should be used.
In between are the various arguments the script accepts. This script defines three com-
mand-line arguments. Here’s one of them:
Each <named> element defines a single named argument. This argument is named
“service” and it is required, rather than optional, meaning the argument must be spec-
ified when the script is executed. This argument also includes a helpstring, which is
just a brief description of what the argument is used for. Finally, the argument has a
“string” type, which means it’s intended to accept some text value such as the name of
a service.
Arguments are specified at the command line by typing a forward slash (/), the name
of the argument, a colon, and the value that the argument will be given in the script:
The last bit of XML in the beginning of the WSF file defines the place where the
VBScript code itself is located:
What follows is a normal VBScript, which could have been created in Microsoft Note-
pad or any other text editor. (The entire WSF file can be edited just fine in Notepad.)
‘==========================================================================
‘
‘ Updsvc
‘
‘ AUTHOR: Don Jones
‘ DATE : 7/31/2004
‘
‘ COMMENT:
‘
‘==========================================================================
Chapter 3: Working with VBScript 25
If Err = 0 Then
’connected - retrieve specified service instance
Set oService = oWMIService.ExecQuery _
("Select * from Win32_Service WHERE Name" & _
" = ’" & sService & "‘")
If Err = 0 Then
’retrieved - change password for the service
errReturn = oService.Change( , , , , , , _
, sPassword)
If errReturn = 0 Then
’change successful
WScript.Echo sClient " changed."
Else
’change not successful
WScript.Echo sClient " not changed."
End If
26 Part I: Understanding Windows Automation
Else
’no matching instances of Win32_Service found
WScript.Echo sClient & ": Error retrieving service"
End If
Else
’couldn’t connect to remote WMI service
WScript.Echo sClient & ": Error connecting"
End If
Else
’input file does not exist
WScript.Echo "Input file does not exist"
End If+
Most importantly, the file finishes by closing the <script>, <job>, and <package> XML
tags:
]]>
</script>
</job>
</package>
And that’s it: you’ve got a WSF file. If you want to make changes to the script without
changing any of the WSF-specific elements (such as the description and named argu-
ments), you edit the portion of the file containing the script. You could also copy and
paste everything between <![CDATA[ and ]]> into another file, which would give you
only the script without all the WSF elements. Doing that can make the script easier to
edit, but you have to be careful because the script doesn’t predefine the named argu-
ments, and any script relying on the named arguments won’t prompt you for them
automatically if they are missing. However, you can still run the script the same way,
regardless of whether it’s a .wsf or a .vbs file, because all VBScript files can accept
named arguments:
CScript.exe MyFile.wsf
Even better, though, is that you can leave out CScript entirely and run the WSF file by
itself on the command line:
MyFile.wsf
I do recommend that you make CScript your default script host by running
CScript.exe //H:CScript one time. You can change back to the graphical WScript by
running CScript.exe //H:WScript if you like.
You can get syntax help for the WSF files that are included in the book by running the
.wsf with the /? command-line argument:
MyFile.wsf /?
Other WSF authors might or might not include the appropriate information within
the WSF to generate the help display. As I previously mentioned, you specify com-
mand-line arguments by typing a forward slash, the argument name, a colon, and
then the value you want passed to the script for that argument:
Of course, I’ll provide a complete reference to the arguments required by each WSF
script in this book within the appropriate task descriptions.
Registering a WSC is simple. First, copy the .wsc file to a location on your computer’s
local hard drive. (I don’t recommend running them directly from the CD.) Next, right-
click the WSC file and select Register from the shortcut menu. A message is displayed
indicating that registration was successful, and you’re finished. You need to do this
only once per computer, but you have to do it on each computer where the WSC will
be used (that is, on every computer you plan to run the script that utilizes the WSC).
If you ever decide you don’t need the WSC anymore, you can right-click it and select
Unregister to remove the WSC’s information from the registry.
28 Part I: Understanding Windows Automation
WSCs use an XML-based format that’s similar to the one used by WSF files. However,
you don’t need to open or edit any of the WSCs provided in this book to get the max-
imum enjoyment and utility out of them. Because the WSCs provided are used by sev-
eral scripts, I don’t recommend editing the WSCs at all. Doing so might render one or
more dependent scripts unusable. If you want to experiment with the WSCs, make a
copy and play with that, preferably on a different computer (because two WSCs with
the same internal name will cause conflicts on your computer).
This is not to say, however, that Notepad is the best you can do for script editing. It has
a number of shortcomings as a script editor for longer, more complicated scripts. For
example, it doesn’t do any color coding of your script to help distinguish comments,
variables, statements, and so forth. It also doesn’t provide any help with the VBScript
syntax, and it won’t do anything to help make the WSF format more comprehensible
and easier to work with. Finally, Notepad makes it a bit tougher to locate script errors
because it doesn’t display line numbers, which is a key requirement for working with
longer scripts. WSH displays script errors with a notation of the specific lines on
which the errors occurred.
There are third-party script editors designed specifically for VBScript editing. Here’s a
selection of the more popular ones:
Some of these editors are free but most are commercial tools, so you have to buy them.
Some are inexpensive—VBSEdit, for example, costs about $30—whereas others are more
full-featured and cost a good deal more. All, however, offer free trial versions on their
Web sites, so you can download them and try them out for a number of days to find the
editor that best meets your needs. Once you register and log in, you’ll also find reviews
of many of these script editors on my Web site, http://www.ScriptingAnswers.com, that
might help you make a decision.
You don’t need any of these tools to effectively use the scripts in this book. All the
scripts provided are designed to be self-contained, and any required customization is
handled by using command-line arguments. You don’t need to have an editor or even
open any of these scripts in Notepad to use them. However, if you decide you want to
modify these scripts in any way—many of them can be changed to perform different
yet similar tasks—a good editor is a nice tool to have.
Summary
The WSF file format is one of those love-it-or-hate-it things. You either think it’s great
because of the extra features it provides, or you hate it because it makes scripting more
complex, and plenty of people find scripting complex enough to start with. In my
mind, the best aspect of the WSF format is that it allows an experienced scripter to
create traditional command-line tools easily and make those scripts accessible to
administrators who aren’t experienced with scripting. The main reason I chose to use
WSF was so that you don’t have to crack the files open and do anything with them if
you don’t want to. They are also more self-documenting in terms of the arguments
they require. WSF files are still easily editable, once you understand what you’re
looking at.
The structure of WSCs wasn’t addressed because this book isn’t about learning script-
ing. What you do need to know about WSCs is that a few of the scripts in this book
will utilize them, so you need to register the WSCs to make them available to those
scripts. When a script uses a WSC, it will remind you that the WSC needs to be regis-
tered before the script can function.
Note There are a number of resources for learning more about WSCs, including the
MSDN® Library Web site at http://msdn.microsoft.com/scripting. Look under “Web
Development” in the table of contents to locate the “Scripting” section.
Chapter 4
Security Best Practices
In this chapter:
Principle of Least Privilege (or Access). . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Using Alternate Credentials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Security: Do This . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Security: Don’t Do This . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Security is perhaps one of the most important concerns when it comes to scripting
and automation. Although many administrators adopt a casual approach to security,
you’ll gain more respect from your managers and peers by adopting a very cautious
approach to scripting and automation. This advice applies to the scripts included with
this book, by the way—don’t assume anything about them! They should all be tested
before you use them in any production environment, because your production envi-
ronment might be very different from the environment in which the scripts were writ-
ten. By focusing on security as a part of every task you perform, you reduce the risk of
deliberate and accidental damage to your environment.
31
32 Part I: Understanding Windows Automation
actions you perform. When you do need to perform tasks requiring additional per-
missions, you can do so by specifying alternate credentials. And, even then, specify
alternate credentials that have just enough permissions for the particular task.
For example, suppose you normally log on by using a low-privilege user account, and
specify a domain administrator account for your administrative tasks. Domain admin-
istrators are, by default, local administrators on all domain member computers, which
is quite a lot of privilege. Were you to run a script that caused a problem, that problem
could extend to every member in the domain. However, suppose that script required
only the permissions associated with the Account Operators group. A problem in this
case would be more limited in scope, because that group doesn’t have local Adminis-
trator permissions on every computer in the domain.
Simply specify the user account (use the user@domain or domain\user format for
specifying user names from an alternate domain, if necessary) and the application to
run; you’ll be prompted for the user’s password (or other type of credentials; Runas
works with smart cards, for example), and the application will execute under that user
account’s credentials and permissions.
You can also right-click applications in Windows Explorer and select Run As from the
shortcut menu. Doing so will prompt you, via a dialog box, for the alternate user’s
name and password.
Chapter 4: Security Best Practices 33
Security: Do This
Security can be straightforward, and it doesn’t have to be a major burden on the way
you do your job. Here are some best practices for making scripting and automation
more secure (and more securable) in any environment:
■ Never, ever, ever put user passwords of any kind into a script. If a script needs to
use an account’s password, have the script prompt for that password or accept
the password as a command-line argument.
■ Avoid changing default permissions in critical areas like the registry and Windows
Management Instrumentation (WMI). Some administrators like to manage cli-
ent computers through the use of logon scripts, which often require users to
have administrative permissions of some kind. Bad idea. Instead, run a script on
your computer that remotely reconfigures client computers using your adminis-
trative credentials.
■ Don’t use the Script Encoder (see the sidebar in this chapter, “Passwords in
Scripts”). The Script Encoder was primarily designed for Web environments
utilizing VBScript and Microsoft Active Server Pages (ASP). Administrative
scripts and automation tools should be protected by NTFS permissions, which
prevent users from opening the scripts to begin with. There should be no need
for the Encoder.
■ Don’t run scripts without reviewing them unless they come from a trusted
source. Scripts from the Internet can be useful, but you never know when a
bug or piece of malicious code might cause irreparable damage to your environ-
ment. Know what you’re running before you run it.
Chapter 4: Security Best Practices 35
Passwords in Scripts
I get a lot of questions about including passwords in scripts. My universal
answer is don’t do it. This advice applies to VBScript files as well as batch files
and other scripts. Many administrators find Microsoft’s Script Encoder (from
http://www.microsoft.com/scripting) and think they’ve found a way to safely
include passwords within scripts, because the encoder will let them “encrypt”
the script and protect the password. Not so—the Encoder is not an encryption
tool in the security sense of the word encryption. It’s designed only to hide your
script’s source code from casual observation. An easy-to-use Script Decoder can
be found at http://www.aspheute.com/english/20011123.asp. I point this out to
emphasize that the Script Encoder should never be used to protect sensitive
information, particularly information as sensitive as user account passwords.
Another question I get asked is whether you can script the Runas command so
that Runas can be launched programmatically with alternate credentials. This is
possible but not easy, and you shouldn’t do it. Scripting the Runas command
would necessarily involve hardcoding user passwords into a script, which is the
very action you want to avoid at all costs. Microsoft deliberately made the Runas
command not scriptable in that fashion because scripted passwords are trouble.
In short, never type a password into script code. (Scripts might prompt for pass-
words, and storing the passwords in variables is fine.) The corollary of this
would be never type a password into any file that can be saved to disk.
Summary
Scripting can be a tremendously useful, beneficial tool, whether you’re talking about
VBScript or more traditional command-line tools. Unfortunately, scripting—and nearly
any other computer-based technology—can be used to create significant damage,
whether intentionally or accidentally. Security precautions are designed to prevent
accidental damage as much as they are designed to prevent deliberate damage caused
by an attacker or malicious user.
Client management includes tasks such as managing System Restore points and client
time zone settings. Automating these tasks enables you to more easily perform them
and often requires scripts that can run on multiple computers. Note that many of the
tasks in this chapter apply only to computers running Microsoft® Windows® XP,
particularly those tasks dealing with System Restore, which is available only in
Windows XP. Other tasks, such as setting the time zone on one or more computers,
can be performed on a wider variety of Windows versions. Tasks automated in this
chapter include:
39
40 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap5\SetRestorePoint\SetRestorePoint.wsf.
Description
This task sets a new System Restore point on one or more computers. Automation is
provided by a Microsoft Visual Basic® Script (VBScript), which is contained in a WSF
file and can be used as a command-line tool. The script offers a number of options
for specifying the computers to be targeted, including specifying a single computer,
specifying a Microsoft Active Directory® organizational unit (OU) containing com-
puter names, and specifying a text file containing computer names. The newly created
System Restore point will be given the name “Scripted Restore” within the System
Restore user interface. It is a good idea to perform this task before major network-wide
changes (such as modifications to a new application or a new logon script) are rolled
out to ensure that each computer has a safe restore point to roll back to.
1. On the Start menu, navigate to All Programs, Accessories, System Tools, and
then select the System Restore tab.
2. On the Welcome To System Restore page, select Create A Restore Point and click
Next.
3. On the Create A Restore Point page, enter a description for the restore point and
click Create.
4. Click Close.
Chapter 5: Client Management 41
As you can see, creating a System Restore point manually is not difficult. However,
doing so on multiple computers can be very time-consuming without an automated
script.
Example
There are three basic ways to use this tool. First, you can target a single remote com-
puter named ClientA by using the following code:
SetRestorePoint.wsf /computer:ClientA
Second, you can target a list of computers from a text file. The text file is expected to
contain one computer name per line, with no other information in the file. Assuming
the file is named C:\Computers.txt, you would use this syntax:
SetRestorePoint.wsf /list:C:\Computers.txt
Third, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
SetRestorePoint.wsf /container:west
Note that the /container argument will work only against the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3, “Working with VBScript.”
/list:path One and only one of these is required by the script. Use /list to
target a list of computers contained within a text file; use
/computer:name
/computer to target a single computer; use /container to target
/container:name an organizational unit within Active Directory.
You can run this script with the /? parameter to display the command’s syntax.
The current computer name is contained in the variable sName. Note that the script
connects to the computer’s \root\default namespace in Microsoft Windows Manage-
ment Instrumentation (WMI) and then retrieves the SystemRestore class from that
namespace. The SystemRestore class provides a method named CreateRestorePoint that
does the work of creating the new System Restore point.
Chapter 5: Client Management 43
Troubleshooting
You have the opportunity to run into two main problems when using this script: first,
a remote computer won’t be available; or second, you won’t have permission to create
a System Restore point. In either case, you’ll see an error message that alerts you to the
problem for that computer. Make sure you have the appropriate permissions and that
the computer is reachable via the network from the computer running this script.
Unreachable computers can optionally be logged to a text file for a later attempt, and
you can speed up the script by specifying the /ping argument.
To Learn More
■ To learn more about how VBScript and WMI work together, read Chapter 6 in
Microsoft Windows 2000 Scripting Guide (Microsoft Press, 2003).
■ Examine the SystemRestore class reference in the Microsoft WMI documentation
to see how the CreateRestorePoint() method can be used to create other restore
points.
■ Other System Restore script examples can be found in the Microsoft TechNet
Script Center at http://www.microsoft.com/technet/scriptcenter/scripts/desktop
/restore/default.mspx.
44 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap5\SetRestorePoint\RollbackRestorePoint.wsf.
Description
This task will restore a computer to a previously created System Restore point. Auto-
mation is provided by VBScript code, which is contained in a WSF file that can be
used as a command-line tool. The script allows only a single computer to be targeted,
because the process of specifying a restore point is not likely to be accurate for more
than one computer at a time. This script can be used to roll back a restore point on a
remote computer to which you might not have ready access, especially in situations in
which that computer’s user isn’t familiar with the System Restore process.
1. On the Start menu, navigate to All Programs, Accessories, System Tools, and
then select System Restore.
2. On the Welcome To System Restore page, select Restore My Computer To An
Earlier Time, and click Next.
3. On the Select A Restore Point page, select the restore point by using the calendar
and list box, and click Next.
4. On the Confirm Restore Point Selection page, click Next to initiate the restore.
5. Follow any additional instructions to restart the computer after the rollback is
complete.
Although rolling back to a System Restore point manually is not difficult, doing so on
a remote computer without the end-user’s assistance can be complicated, generally
requiring a Remote Assistance or other remote control session to be initiated. The
Chapter 5: Client Management 45
process of selecting the correct restore point can be complex and intimidating for end-
users. If you as the administrator already know the restore point you need, you can
use a script to perform this selection much more quickly.
Example
This script can target only a single computer and uses the following syntax:
This will connect to ClientA and roll back to restore point 20; use the List System
Restore Point script in this chapter to obtain the correct restore point number.
Additional arguments provide more functionality to the command; see the following
section.
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
You can run this script with the /? parameter to display the command’s syntax.
Else
Set oSysRestore = oWMIService.Get("SystemRestore")
If Err <> 0 Then
WScript.Echo " *** Couldn’t get System Restore services from " & sName
WScript.Echo " " & Err.Description
Else
ErrResult = oSysRestore.Restore(WScript.Arguments.Named("point"))
Verbose " " & sName & ": " & ErrResult
End If
End If
The current computer name is contained in the variable sName. Note that the script
connects to the computer’s \root\default namespace in Windows Management Instru-
mentation (WMI) and then retrieves the SystemRestore class from that namespace. The
SystemRestore class provides a method named Restore, which does the work of rolling
back to the specified System Restore point. You will need to use the List System
Restore Point script to see a list of available restore points on the remote computer.
Troubleshooting
You have the potential to run into three problems when using this script. First, the
remote computer won’t be available. Second, you won’t have permission to roll back
to a System Restore point. In either case, you’ll see an error message that alerts you to
the problem. Make sure you have the appropriate permissions (generally, Administra-
tor permissions are required) and that the computer is reachable via the network from
the computer running this script.
A third possible problem is specifying a System Restore point number that doesn’t
exist. In that case, you’ll see an appropriate error message, and nothing will happen.
It’s also possible to specify the wrong System Restore point. In that case, the targeted
computer will be rolled back to the specified point regardless—the script does not pro-
vide an “are you sure?” prompt or any other chance to undo what you’ve done. Be very
careful when using this script and verify the restore point number you provide.
To Learn More
■ To learn more about how VBScript and WMI work together, read Chapter 6 in
Microsoft Windows 2000 Scripting Guide (Microsoft Press, 2003).
■ Examine the SystemRestore class reference in the Microsoft WMI documentation
to see how the CreateRestorePoint() method can be used to create other restore
points.
■ Other System Restore script examples can be found in the Microsoft TechNet
Script Center at http://www.microsoft.com/technet/scriptcenter/scripts/desktop/
restore/default.mspx.
Chapter 5: Client Management 47
On the CD The sample script can be found on the CD that accompanies this book
at \Chap5\SetSysRestoreStatus\SetSystemRestoreStatus.wsf.
Description
This task will enable or disable the System Restore feature on one or more computers
running Windows XP. Automation is provided by a VBScript that is contained in a
WSF file that is to be used as a command-line tool. The script offers a number of options
for specifying the computers to be targeted, including specifying a single computer,
specifying an Active Directory organizational unit (OU) containing computer names,
or specifying a text file containing computer names.
System Restore consumes a configurable amount of disk space, and it does present an
opportunity for users to misconfigure their computers by performing System Restore
rollbacks when not necessary or by specifying an incorrect restore point during a roll-
back. There is also a remote possibility for System Restore to present a virus vector. If
a virus is captured as part of a System Restore point, rolling back to that point will
reintroduce the virus. For these and other reasons, some organizations elect to disable
System Restore on their client computers running Windows XP.
As you can see, although configuring System Restore manually is not difficult, doing
so on multiple computers can be very time-consuming without some kind of auto-
mated script.
Example
There are three basic ways to use this tool. To use it to target a single remote computer
named ClientA and enable System Restore, you would use this code:
You can also target a list of computers from a text file. The text file is expected to con-
tain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax to disable System Restore on the
computers listed in the file:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax to enable
System Restore:
Note that the /container argument will work only against the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
to target a list of computers contained within a text file. Use
/computer:name
/computer to target a single computer. Use /container to
/container:name target an organizational unit within Active Directory.
You can run this script with the /? parameter to display the command’s syntax.
By the time this script is reached, the variable oSysRestore has been set to represent the
System Restore Windows Management Instrumentation (WMI) class on the current
remote computer. This class provides methods to enable or disable System Restore;
the value provided for the /status argument determines the method called. Note that
a provision is included for an unknown value (not enable or disable) being passed to
the /status argument.
50 Part II: Computer Management Tasks
Troubleshooting
You have the potential to run into two main problems when using this script. First, a
remote computer won’t be available. Second, you won’t have permission to configure
System Restore. In either case, you’ll see an error message that alerts you to the prob-
lem for that computer. Make sure you have the appropriate permissions and that the
computer is reachable via the network from the computer running this script.
Unreachable computers can optionally be logged to a text file for a later attempt, and
you can speed up the script by specifying the /ping argument. Generally speaking,
you’ll need local Administrator permissions on each targeted computer to success-
fully run the script.
To Learn More
■ To learn more about how VBScript and WMI work together, read Chapter 6 in
Microsoft Windows 2000 Scripting Guide (Microsoft Press, 2003).
■ Examine the SystemRestore class reference in the Microsoft WMI documentation
to see how the CreateRestorePoint() method can be used to create other restore
points.
■ Other System Restore script examples can be found in the Microsoft TechNet
Script Center at http://www.microsoft.com/technet/scriptcenter/scripts/desktop/
restore/default.mspx.
Chapter 5: Client Management 51
On the CD The sample script can be found on the CD that accompanies this book
at \Chap5\ListRestorePoints\ListRestorePoints.wsf.
Description
This task will list all System Restore points on a single remote computer. Automation
is provided by VBScript code, which is contained in a WSF file that can be used as a
command-line tool. The script allows only a single computer to be targeted, because
the process of specifying a restore point is not likely to be accurate on more than one
computer at a time. Prior to using a different script to roll back to a System Restore
point, this script can be used to obtain the ID number for the desired restore point.
1. On the Start menu, navigate to All Programs, Accessories, System Tools, and
select System Restore.
2. On the Welcome To System Restore page, select Restore My Computer To An
Earlier Time, and click Next.
3. On the Select A Restore Point page, browse the available restore points by using
the calendar and list box.
4. Click Cancel to cancel the System Restore process.
This procedure can be time-consuming when you’re trying to quickly locate a particu-
lar restore point.
52 Part II: Computer Management Tasks
Example
This script can target only a single computer and uses the following syntax:
ListRestorePoints.wsf /computer:ClientA
This code will connect to ClientA and list all restore points. Adding the /verbose argu-
ment will also list the type of each restore point, such as an application installation
restore point and a device driver installation restore point.
Syntax
This script can be executed as a command-line utility. You should set CScript.exe to be
your default script processor, as described in Chapter 3.
You can run this script with the /? parameter to display the command’s syntax.
Case 10
Verbose " (device driver installation)"
Case 11
Verbose " (first run)"
Case 12
Verbose " (modify settings)"
Case 13
Verbose " (cancelled operation)"
Case 14
Verbose " (backup recovery)"
Case Else
Verbose " (other)"
End Select
Next
End If
The current computer name is contained in the variable sName. The script uses a func-
tion named QueryWMI to retrieve the list of System Restore points, and then lists
them. A Select…Case construct contains all possible values for the restore point type;
the Verbose subroutine displays the corresponding output only if the script’s /verbose
argument is specified. Not displaying the restore point type provides for a more com-
pact listing of available restore points.
Troubleshooting
You have the potential to run into two problems when using this script. First, the
remote computer won’t be available. Second, you won’t have permission to roll back
to a System Restore point. In either case, you’ll see an error message that alerts you to
the problem. Make sure you have the appropriate permissions (generally, Administra-
tor permissions are required) and that the computer is reachable via the network from
the computer running this script.
To Learn More
■ To learn more about how VBScript and WMI work together, read Chapter 6 in
Microsoft Windows 2000 Scripting Guide (Microsoft Press, 2003).
■ Examine the SystemRestore class reference in Microsoft’s WMI documentation to
see how the CreateRestorePoint() method can be used to create other restore
points.
■ Other System Restore script examples can be found in the Microsoft TechNet
Script Center at http://www.microsoft.com/technet/scriptcenter/scripts/desktop/
restore/default.mspx.
54 Part II: Computer Management Tasks
Description
This task will change the workgroup or domain that a computer belongs to. To change
a computer’s domain membership, you must first join the computer to a workgroup
(thus removing it from its domain), and then join it to the new domain.
You will need to restart the computer for your changes to take effect. Though easy
enough to perform, this task can be cumbersome when you need to perform it on a
remote computer.
Example
To join computer ClientA to the Company domain and restart the computer after 30
seconds, use this code:
Note The precise syntax of the Netdom.exe utility differs from version to version.
Be sure to check the Support Tools documentation accompanying your version of
Windows for specifics. Also note that the syntax shown is for v2.0 of the Netdom.exe
utility; earlier versions use a completely different syntax and can also join computers
to workgroups.
Syntax
This utility runs from the command line. You can create a batch file to run this com-
mand on multiple computers in sequence, but you will generally need to use it on
only one or two computers at once.
You can run this script with the /? parameter to display the command’s syntax.
Second, Netdom.exe can contact the targeted computer and modify its local configu-
ration to reflect its new domain or workgroup membership. For both tasks—the
domain and local computer configurations—you need to have appropriate permissions.
For the domain, you will generally need to be a domain administrator; for the local
computer, you will need to be recognized as a local administrator.
56 Part II: Computer Management Tasks
Troubleshooting
The most likely cause for problems is having the targeted computer recognize you as
a local administrator. If you run Netdom.exe using domain administrator credentials,
the domain will recognize you, as will all domain members, meaning that you will not
have a problem removing a computer from the domain. However, computers that are
not members of the domain will obviously not recognize a domain administrator as a
local administrator, meaning you will have to independently establish local adminis-
trator credentials when adding a computer to a domain (or changing workgroups).
One way to do so is to execute the following:
Doing so will establish a connection from your computer to ClientA (assuming that’s
the computer you’re targeting with Netdom.exe) and allow you to provide a password
for the local Administrator account. You can, of course, specify any account with the
appropriate permissions; you don’t need to use the built-in Administrator account as
I’ve done in this example. You can also use the Netdom.exe utility’s /UserO switch to
specify alternate credentials.
To Learn More
■ To read more about the Netdom.exe utility, consult the documentation included
with the Support Tools. You can also read http://support.microsoft.com/kb/
266651/EN-US/ for more details.
Chapter 5: Client Management 57
On the CD The sample script can be found on the CD that accompanies this book
at \Chap5\ChangeComputerName\ChangeComputerName.wsf.
Description
This task will change the computer name of a remote computer. You must specify a
valid new computer name, or the script will return an error indicating that the change
could not be made. If you specify the /ping argument, the script will check to make
sure the new computer name is not currently in use by another computer on the net-
work (assuming that any computer already using the name is reachable by pinging its
name).
Walking a user through this process can be difficult, and many users might not have
permissions to change their computers’ names. Using the script allows you to effect a
name change remotely from a command line.
58 Part II: Computer Management Tasks
Example
This script can target only a single computer and uses the following syntax:
This will connect to ClientA and rename it to ClientB. Additional arguments provide
more functionality to the command; see the following section.
Syntax
This script can be executed as a command-line utility. You should set CScript.exe to be
your default script processor, as described in Chapter 3.
You can run this script with the /? parameter to display the command’s syntax.
ErrResults = oComputer.Rename(WScript.Arguments.Named("name"),Null,Null)
If ErrResults <> 0 Then
WScript.Echo " *** Error renaming: " & ErrResults
Else
Verbose "Rename successful. Restart of remote computer is necessary."
End If
The current computer name is contained in the variable sName, whereas the argument
/name contains the new computer name. The Win32_ComputerSystem class is repre-
sented in oComputer, and its Rename() method performs the actual work of renaming
the computer.
Chapter 5: Client Management 59
Troubleshooting
Security permissions can cause problems when running this script. You must be a
member of the computer’s local Administrators group for this script to function; the
script might not work in all circumstances when run remotely on computers that are
members of a domain. In those cases, you might need to modify the script to include
a password and user name in the Rename() method:
ErrResults = oComputer.Rename(WScript.Arguments.Named("name"), _
"passwprd","[email protected]")
The Rename() method cannot be used in all cases to rename computers that are mem-
bers of a domain.
To Learn More
■ Read more about the Win32_ComputerSystem class at http://
msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/
win32_computersystem.asp.
■ Read more about the Rename() method at http://msdn.microsoft.com/library/
default.asp?url=/library/en-us/wmisdk/wmi/
rename_method_in_class_win32_computersystem.asp.
60 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap5\ListTimeZone\ListTimeZone.wsf.
Description
This task will list the time zone bias on one or more remote computers. The bias is the
difference between Universal Time Coordinate (UTC, also referred to as Greenwich
Mean Time, or GMT) and the computer’s current local time. For example, the West
Coast of the United States uses the bias -8:00 to represent eight hours earlier than
UTC.
1. Double-click the clock display in the System Notification area of the Taskbar, or
double-click Date And Time from Control Panel.
2. In the Date And Time Properties dialog box, select the Time Zone tab.
3. Review the time zone setting.
4. Click OK.
Chapter 5: Client Management 61
As you can see, this task becomes a bit time-consuming to perform manually beyond
a couple of computers. Using a script to locate incorrectly configured computers is
much more efficient.
Example
There are three basic ways to use this tool. To target only a single remote computer
named ClientA, you would use this code:
ListTimeZone.wsf /computer:ClientA
You can also target a list of computers from a text file. The text file is expected to con-
tain one computer name per line, with no other information in the file. Assuming the
file is named C:\Computers.txt, you would use this syntax:
ListTimeZone.wsf /list:C:\Computers.txt
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
ListTimeZone.wsf /container:west
Note that the /container argument will work only against the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
Additional arguments provide more functionality to the command; see the following
section.
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
to target a list of computers contained within a text file. Use
/computer:name
/computer to target a single computer. Use /container to tar-
/container:name get an organizational unit within Active Directory.
You can run this script with the /? parameter to display the command’s syntax.
The current computer name is contained in the variable sName. The script uses a func-
tion named QueryWMI() to retrieve the Win32_TimeZone class and displays its Bias
property as script output.
Notice that the bias reported by the script is listed in minutes, not in hours; you can
divide the reported bias by 60 to determine the number of hours between the com-
puter’s configured time zone and UTC.
Chapter 5: Client Management 63
Troubleshooting
Permissions and connectivity are the primary problems you’re likely to encounter
with this script. Ensure that the account running the script has administrative permis-
sions on targeted computers and that network connectivity is available to all targeted
computers. (Specify the /ping argument to allow the script to more easily handle
unreachable computers.)
To Learn More
■ Learn more about the Win32_TimeZone class at http://msdn.microsoft.com/
library/default.asp?url=/library/en-us/wmisdk/wmi/win32_timezone.asp.
■ Read more about time issues and how they can affect the Windows operations
at http://labmice.techtarget.com/windows2000/timesynch.htm.
Chapter 6
Server Management
In this chapter:
Enable Shadow Copy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Inventory Shadow Copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
65
66 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap6\MakeShadowCopy\MakeShadowCopy.wsf.
Description
The Windows Server 2003 Shadow Copy functionality is enabled on a per-volume
basis (although Shadow Copies are made only of files residing in shared folders
within that volume). This task creates a single Shadow Copy for a specified volume on
one or more servers. Using Shadow Copies is recommended because it allows a user
to retrieve an older version of a file on her own—she doesn’t have to contact your orga-
nization’s help desk and request that a backup tape be used to restore a previous ver-
sion of a file.
1. Right-click the desired volume in My Computer, and select Properties from the
shortcut menu.
2. Select the Shadow Copies tab. You can manage the Shadow Copy feature on all
volumes, no matter which volume you right-clicked.
3. Select the desired volume from the list. The list indicates how many shared fold-
ers are available on the volume.
4. Click Enable to enable the Shadow Copies feature.
5. Read the information presented in the Enable Shadow Copies dialog box, and
then click Yes.
Chapter 6: Server Management 67
After Shadow Copies is enabled, you can create a new Shadow Copy by clicking the
Create Now button in the volume’s Properties dialog box.
Example
You can use this tool in three ways. First, you can target a single remote computer
named ServerA and create a Shadow Copy for the C:\ volume:
Second, you can target a list of computers from a text file. The text file is expected to
contain one computer name per line, with no other information in the file. Assuming
the file is named C:\Computers.txt, you would use this syntax to create a Shadow
Copy on the E volume of each server:
Third, you can target an entire organizational unit (OU) of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work only against the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3, “Working with VBScript.”
/list:path One and only one of these is required by the script. Use /list
to target a list of computers contained within a text file. Use
/computer:name
/computer to target a single computer. Use /container to tar-
/container:name get an organizational unit within Active Directory®.
You can run this script with the /? parameter to display the command’s syntax.
The current computer name is contained in the variable sName. Note that the script
connects to the computer’s \root\cimv2 namespace in Microsoft Windows Manage-
ment Instrumentation (WMI) and then retrieves the Win32_ShadowCopy class from
that namespace. This class provides a method named Create() that accepts the volume
Chapter 6: Server Management 69
name and a parameter; the parameter indicates that the created Shadow Copy should
be accessible to clients. In Windows Server 2003, only “ClientAccessible” is used for the
second parameter.
If you use this tool with the /verbose argument, you’ll see an error code number for
each targeted server. A 0 (zero) means that the command completed successfully; any-
thing else means it didn’t. The following list provides some of the common error
codes:
■ 1 Access denied
■ 2 Volume not found
■ 4 Shadow Copies not supported (generally for removable or FAT volumes)
■ 9 Maximum number of shadow copies reached
Other numbers indicate general failures on the part of the Shadow Copy provider
within Windows itself.
Troubleshooting
This script has the potential for three major types of errors. First, a remote computer
won’t be available. Second, you won’t have permission to enable Shadow Copies. In
either case, you’ll see an error message that alerts you to the problem for that com-
puter. Make sure you have the appropriate permissions and that the computer is
reachable via the network from the computer running this script. Unreachable com-
puters can optionally be logged to a text file for a later attempt, and you can speed up
the script by specifying the /ping argument.
Third, it’s possible that an error will occur during the Shadow Copy enabling. In that
case, an error code will be reported by the script, as just described.
To Learn More
■ To learn more about the Shadow Copies feature, consult the Help and Support
Center within Windows Server 2003.
■ You can also read more about Shadow Copies at http://www.microsoft.com
/windowsserver2003/techinfo/overview/scr.mspx.
■ Other script samples dealing with Shadow Copy can be found in the TechNet
Script Center at http://www.microsoft.com/technet/scriptcenter/scripts/shadow
/default.mspx.
70 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap6\ShadowCopyInventory\ShadowCopyInventory.wsf.
Description
This tool lists all Shadow Copy information for the specified server or servers. For
each Shadow Copy on a server, the tool specifically lists the following items:
Example
You can use this tool in three basic ways. First, you can target a single remote com-
puter named ServerA:
ShadowCopyInventory.wsf /computer:ServerA
Chapter 6: Server Management 71
Second, you can target a list of computers from a text file. The text file is expected to
contain one computer name per line, with no other information in the file. Assuming
the file is named C:\Computers.txt, you would use this syntax:
ShadowCopyInventory.wsf /list:C:\Computers.txt
Third, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
ShadowCopyInventory.wsf /container:west
Note that the /container argument will work only against the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
Additional arguments provide extra functionality to the command. See the following
section titled “Syntax.”
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
to target a list of computers contained within a text file. Use
/computer:name
/computer to target a single computer. Use /container to
/container:name target an organizational unit within Active Directory.
You can run this script with the /? parameter to display the command’s syntax.
72 Part II: Computer Management Tasks
The current computer name is contained in the variable sName. Note that the script con-
nects to the computer’s \root\cimv2 namespace in Windows Management Instrumenta-
tion (WMI) and then retrieves the Win32_ShadowCopy class from that namespace.
Next, the script lists specific properties of that class for each instance retrieved. You can
modify this script, if desired, to list other properties of each Shadow Copy.
Also note that this script will output most of its information (assuming you are not
using the /verbose argument) in a comma-delimited format. This allows you to run the
script and capture its output to a text file, if you want, for use within a report. You can
open the resulting file in an application such as Microsoft Excel to view the report in
a columnar format. Use standard command-line redirection to capture the script’s
output to a text file.
Troubleshooting
This script has the potential for two major types of errors. First, a remote computer
won’t be available. Second, you won’t have permission to enable Shadow Copies. In
either case, you’ll see an error message that alerts you to the problem for that com-
puter. Make sure you have the appropriate permissions and that the computer is
reachable via the network from the computer running this script. Unreachable com-
puters can optionally be logged to a text file for a later attempt, and you can speed up
the script by specifying the /ping argument.
To Learn More
■ To learn more about the Shadow Copies feature, consult the Help and Support
Center within Windows Server 2003.
■ You can also read more about Shadow Copies at http://www.microsoft.com
/windowsserver2003/techinfo/overview/scr.mspx.
■ Other script samples dealing with Shadow Copy can be found in the TechNet
Script Center at http://www.microsoft.com/technet/scriptcenter/scripts/shadow
/default.mspx.
Chapter 7
Inventorying and Reporting
In this chapter:
List Installed Hotfixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
List Event Log Entries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
List Installed Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
List Internet Explorer Configuration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
List Network Adapter Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
List Installed Service Pack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
List Scheduled Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
List Installed Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
This chapter presents a set of automation tasks that don’t actually do anything to the
targeted system, but rather simply retrieve information for you, which helps you better
understand what your current environment looks like, how it’s configured, and so
forth. Many of these tasks can’t be easily performed manually, because Microsoft®
Windows® doesn’t include much in the way of cross-server reporting capabilities.
Additionally, most of the scripts provided for this chapter provide the capability to
output their information to comma-delimited files, which you can then open in an
application such as Microsoft Excel. This output feature allows you to view informa-
tion in a columnar format, or more easily export the information to a database or
other reporting system.
Most of the scripts in this chapter work very similarly by querying a set of Microsoft
Windows Management Instrumentation (WMI) instances and writing their proper-
ties to the screen or to the designated output file. You should therefore be able to
75
76 Part II: Computer Management Tasks
review and modify these scripts, if desired, to provide reporting functionality not
specifically listed in this chapter. Tasks automated in this chapter include:
On the CD The sample script can be found on the CD that accompanies this book
at \Chap7\Listhotfixes\ListHotfixes.wsf.
Description
Freely available tools like the Microsoft Baseline Security Analyzer (MBSA) can easily
list the various updates or hotfixes that aren’t installed on your computers, but some
auditing activities require a report of those updates that are installed, along with the
date they were installed. MBSA’s graphical user interface (and even its command-line
version) doesn’t provide this information in a format that lends itself to use within an
audit report; however, the script provided in this chapter, ListHotfixes.wsf, does.
Example
As with many of the tools in this book, you can use this one in three different ways.
First, you can use it to target a single remote computer named ServerA, for example:
ListHotfixes.wsf /computer:ServerA
Second, you can target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
ListHotfixes.wsf /list:C:\Computers.txt
78 Part II: Computer Management Tasks
Third, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
ListHotfixes.wsf /container:west
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU
has nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide extra functionality to the command; see the following
section titled “Syntax.” Specifically, the following will write the tool’s output to a
comma-delimited file named C:\MyOutput.csv:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3, “Working with VBScript.”
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Microsoft Active Directory®.
/output:path Specifies the file to which the tool’s output should be written.
The file specified will be overwritten if it already exists.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Requires that you specify the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
You can run this script with the /? parameter to display the command’s syntax.
Chapter 7: Inventorying and Reporting 79
LogFile(WScript.Arguments.Named("output"),"computer,hotfix,installdate,installedby",
True)
Else
WScript.Echo "Computer, hotfix ID, install date, installed by"
End If
Set cFixes = QueryWMI(sName,"root\cimv2","Select * From Win32_QuickFixEngineering","
","")
If Not IsObject(cFixes) Then
WScript.Echo " *** Couldn’t connect to WMI on " & sName
Else
For Each oFix In cFixes
sOutput = sName & "," & oFix.HotFixID & "," & oFix.InstallDate & ","
& oFix.InstalledBy
If WScript.Arguments.Named.Exists("output") Then
LogFile(WScript.Arguments.Named("output"),sOutput,False)
Else
WScript.Echo sOutput
End If
Next
The current computer name is contained in the variable sName. Note that the script
connects to the computer’s \root\cimv2 namespace in Microsoft Windows Manage-
ment Instrumentation (WMI), and then retrieves the Win32_QuickFixEngineering
instances from that namespace. This query returns a list of all installed hotfixes; the
script then looks at each one and outputs its relevant information, using properties of
the class.
Troubleshooting
As with most scripts, connecting to the remote computer (or computers) and having
the permissions necessary to list hotfixes (generally, local Administrator permissions)
leaves open the potential for errors. This script will catch most errors and display an
appropriate message, moving on to the next targeted computer if possible.
Because this script has the option to output to a file using the /output argument, it’s
also possible that you’ll receive an error if you specify that the file be created in a
location where you don’t have the necessary file system permissions, or if you specify
80 Part II: Computer Management Tasks
a file name that already exists and you don’t have permission to delete and re-create
that file. In both cases, the script will attempt to continue, but you’ll receive errors
each time the log file access is attempted. To break the script’s execution, press Ctrl+C
in the command-line window.
To Learn More
■ You can download individual hotfixes from the Windows Update Catalog, or
use the Windows Update Web site (http://windowsupdate.microsoft.com) to
automatically apply needed updates to a particular computer.
■ The TechNet Script Center includes other script samples that demonstrate
how to work with hotfixes and service packs: http://www.microsoft.com/technet
/scriptcenter/scripts/srvpacks/default.mspx.
Chapter 7: Inventorying and Reporting 81
On the CD The sample script can be found on the CD that accompanies this book
at \Chap7\ListEvents\ListEvents.wsf.
Description
Quickly listing event logs—and having the ability to archive them, if desired—is a core
administrative task in Windows. A number of third-party companies produce tools to
assist with this task; Microsoft released Microsoft Operations Manager (MOM) in
part to help better manage event logs. This script provides the simplest possible event
log management functionality, gathering all events from a designated log on one or
more computers and either displaying those events on the screen or logging them to
a text file you specify.
To view a remote computer’s event log using Windows Event Viewer, follow these
steps:
This process is obviously cumbersome when you want to pull and archive events from
a number of computers.
Example
As with many of the tools in this book, you can use this one in three different ways.
First, you can use it to target a single remote computer named ServerA, for example:
Note that the /log argument is used to specify the log you want to pull. Valid entries
include Application, Security, and System; servers might have additional logs available
for DNS, Active Directory, and so forth.
Second, you can target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Third, you can target an entire organizational unit (OU) of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU
has nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide more functionality to the command. See the following
section titled “Syntax.” Specifically, the following will write the tool’s output to a
comma-delimited file named C:\MyOutput.csv:
Syntax
This script can be executed as a command-line utility. You should set CScript.exe to be
your default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to
/container:name
target an organizational unit within Active Directory.
/output:path Specifies the file to which the tool’s output should be written.
The file specified will be overwritten if it already exists.
/evtlog:logname Required. Specifies the log to pull. Valid entries for logname
include System, Application, and Security, although others
might also be available depending on the services a particu-
lar computer is running.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be
reached on the network.
/log:path Logs unreachable computer names to the specified file. This
file can then be used later, along with the /list argument, to
retry these computers. Requires that you specify the /ping
argument.
/verbose Causes the script to display more detailed, step-by-step
status messages.
You can run this script with the /? parameter to display the command’s syntax.
& oEvent.message & "," & oEvent.sourcename & "," & oEvent.timewritten & ","
& oEvent.type
If WScript.Arguments.Named.Exists("output") Then
LogFile WScript.Arguments.Named("output"),sOutput,False
Else
WScript.Echo sOutput
End If
Next
End If
The current computer name is contained in the variable sName. Note that the script
connects to the computer’s \root\cimv2 namespace in Windows Management Instru-
mentation, and then retrieves the Win32_NTLogEvent instances from that namespace.
Each instance of Win32_NTLogEvent represents a single event entry; notice that the
query limits the instances returned to those that have a LogFile property equal to
the log specified in the /log argument. Thus, the query returns all events for the
specified log.
Troubleshooting
As with most scripts, connecting to the remote computer or computers and having the
permissions necessary to list events (generally, local Administrator permissions)
leaves open the potential for errors. This script will catch most errors and display an
appropriate message. It then moves on to the next targeted computer if possible.
Because this script has the option to output to a file by using the /output argument,
you might receive an error when you specify that the file be created in a location where
you don’t have the necessary file system permissions, or when you specify a file name
that already exists and you don’t have permission to delete and re-create that file. In
both cases, the script will attempt to continue, but you’ll receive errors each time
the log file access is attempted. To break the script’s execution, press Ctrl+C in the
command-line window.
To Learn More
■ Read more about Windows Event Viewer in the Windows Help and Support
Center.
■ The TechNet Script Center includes other script samples that demonstrate how
to work with event logs: http://www.microsoft.com/technet/scriptcenter/scripts
/logs/eventlog/default.mspx.
Chapter 7: Inventorying and Reporting 85
On the CD The sample script can be found on the CD that accompanies this book
at \Chap7\ListHardware\ListHardware.wsf.
Description
This script lists all Plug and Play hardware installed on one or more computers. This
is useful for discovering which computers contain a particular piece of hardware, for
example. Simply log the script’s output to a log file (using the /output argument) and
then use a text editor like Microsoft Notepad or Microsoft Word to search for the
specific piece of hardware you’re interested in. The search will identify each computer
containing that hardware.
Example
You can use this script in three different ways. First, you can use it to target a single
remote computer named ServerA, for example:
ListHardware.wsf /computer:ServerA
86 Part II: Computer Management Tasks
Second, you can target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
ListHardware.wsf /list:C:\Computers.txt
Third, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
ListHardware.wsf /container:west
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within
the same domain that the computer running the script belongs to. If the specified OU
has nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide more functionality to the command. (See the following
section titled “Syntax.” Specifically, the following will write the tool’s output to a
comma-delimited file named C:\MyOutput.csv:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file.
Use /computer to target a single computer. Use /container to
/container:name
target an organizational unit within Active Directory.
/output:path Specifies the file to which the tool’s output should be written.
The file specified will be overwritten if it already exists.
/recurse When used with /container, also targets computers contained
within sub-OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
Chapter 7: Inventorying and Reporting 87
You can run this script with the /? parameter to display the command’s syntax.
The current computer name is contained in the variable sName. Note that the script
connects to the computer’s \root\cimv2 namespace in Windows Management Instru-
mentation (WMI), and then retrieves the Win32_PnPEntity instances from that
namespace. Each instance of this class represents a single Plug and Play entity, or
device. The properties of the entity—DeviceID, Name, and Service—are included in
the script’s output. You could modify this script to query a different class, such as
Win32_POTSModem, which represents installed modems. If you modify the class, be
sure to check the class in the WMI documentation to see what properties are avail-
able. For Win32_POTSModem, for example, the properties DeviceID, DriverDate, and
DeviceType might contain relevant information.
Troubleshooting
As with most scripts, connecting to the remote computer or computers and having the
permissions necessary to list installed hardware opens up the potential for errors.
This script will catch most errors and display an appropriate message, and then move
on to the next targeted computer if possible.
88 Part II: Computer Management Tasks
Because this script has the option to output to a file using the /output argument, you
might receive an error when you specify that the file be created in a location where you
don’t have the necessary file system permissions, or when you specify a file name that
already exists and you don’t have permission to delete and re-create that file. In both
cases, the script will attempt to continue, but you’ll receive errors each time the log file
access is attempted. To break the script’s execution, press Ctrl+C in the command-line
window.
To Learn More
■ The TechNet Script Center includes other script samples that demonstrate how
to work with hardware: http://www.microsoft.com/technet/scriptcenter/scripts
/hardware/default.mspx.
Chapter 7: Inventorying and Reporting 89
On the CD The sample script can be found on the CD that accompanies this book
at \Chap7\ListIEConfig\ListIEConfig.wsf.
Description
This script connects to multiple computers and uses WMI to obtain their Internet
Explorer configurations. Like other scripts in this chapter, this script offers an /output
argument to write the script’s output to a text file; however, this script creates a
formatted report rather than a comma-separated value (CSV) file, because Internet
Explorer’s configuration is more complex than can be easily represented in a single
CSV file.
Example
This script can be used in three different ways. First, you can use it to target a single
remote computer named ServerA, for example:
ListIEConfig.wsf /computer:ServerA
Second, you can target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
ListIEConfig.wsf /list:C:\Computers.txt
90 Part II: Computer Management Tasks
Third, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
ListIEConfig.wsf /container:west
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within
the same domain that the computer running the script belongs to. If the specified OU
has nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.” Specifically, the following will write the tool’s output to a text
file named C:\MyOutput.txt.
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to
/container:name
target an organizational unit within Active Directory.
/output:path Specifies the file to which the tool’s output should be written.
The file specified will be overwritten if it already exists.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be
reached on the network.
/log:path Logs unreachable computer names to the specified file. This
file can then be used later, along with the /list argument, to
retry these computers. Requires that you specify the /ping
argument.
/verbose Causes the script to display more detailed, step-by-step sta-
tus messages.
You can run this script with the /? parameter to display the command’s syntax.
Chapter 7: Inventorying and Reporting 91
The current computer name is contained in the variable sName; the QueryWMI func-
tion is built into the script and does the work of connecting to the remote computer’s
WMI service and retrieving the query results. For each class, the script writes the key
class properties:
The sOutput variable contains all the script’s output. After the script, ListIEConfig.wsf,
completely populates sOutput with all the desired configuration information, sOutput
is written to the screen or, if the /output argument is specified, to a text file.
Troubleshooting
As with most scripts, connecting to the remote computer or computers and having the
permissions necessary to retrieve the configuration information leaves open the
potential for errors. This script will catch most errors and display an appropriate mes-
sage, and then move on to the next targeted computer if possible.
Because this script has the option to output to a file by using the /output argument,
you might receive an error if you specify that the file be created in a location where you
92 Part II: Computer Management Tasks
don’t have the necessary file system permissions, or if you specify a file name that
already exists and you don’t have permission to delete and re-create that file. In both
cases, the script will attempt to continue, but you’ll receive errors each time the log file
access is attempted. To break the script’s execution, press Ctrl+C in the command-line
window.
To Learn More
■ The TechNet Script Center includes other script samples that demonstrate
how to work with the Internet Explorer configuration: http://www.microsoft.com
/technet/scriptcenter/scripts/desktop/ie/default.mspx.
Chapter 7: Inventorying and Reporting 93
On the CD The sample script can be found on the CD that accompanies this book
at \Chap7\ListNICConfig\ListNICConfig.wsf.
Description
This task retrieves key network adapter configuration information—such IP address,
DHCP status, DNS domain and host name—from one or more computers and displays
that information on the screen. By using the /output argument, the script can generate
this information to a file instead. This task is useful for quickly learning which com-
puters on your network have particular IP addresses, inventorying Media Access
Control (MAC) addresses, and so on.
You can retrieve all this information for a single computer by running the Windows
Ipconfig command on that computer followed by the /all argument:
Ipconfig /all
However, using this approach to obtain information from multiple computers can be
time-consuming.
94 Part II: Computer Management Tasks
Example
As with many of the tools in this book, you can use this one in three different ways.
First, you can use it to target a single remote computer named ServerA, for example:
ListNICConfig.wsf /computer:ServerA
Second, you can target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
ListNICConfig.wsf /list:C:\Computers.txt
Third, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
ListNICConfig.wsf /container:west
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
You can run this script with the /? parameter to display the command’s syntax.
The current computer name is contained in the variable sName. Note that the script
connects to the computer’s \root\cimv2 namespace in Windows Management Instru-
mentation (WMI) and then retrieves the Win32_NetworkAdapterConfiguration
instances from that namespace. This query returns a list of all installed adapters and
their configurations. The script then simply looks at each one and outputs its relevant
information, using properties of the class.
Note that a computer can have multiple adapters, and that each adapter can have
multiple configurations. This script supports these scenarios and will list each unique
adapter configuration combination independently. You could also modify the
script to list other properties of interest; refer to the WMI documentation on the
Win32_NetworkAdapterConfiguration class for more details about available properties.
96 Part II: Computer Management Tasks
Troubleshooting
As with most scripts, connecting to the remote computer (or computers) and having
the permissions necessary to list network adapter configurations (generally, local
Administrator permissions) leaves open the potential for errors. This script will catch
most errors and display an appropriate message, and then move on to the next
targeted computer if possible.
Because this script has the option to output to a file by using the /output argument,
you might receive an error if you specify that the file be created in a location where you
don’t have the necessary file system permissions, or if you specify a file name that
already exists and you don’t have permission to delete and re-create that file. In both
cases, the script will attempt to continue, but you’ll receive errors each time the log file
access is attempted. To break the script’s execution, press Ctrl+C in the command-line
window.
To Learn More
■ To learn more about the Windows Ipconfig utility, consult the Windows Help
and Support Center.
■ The TechNet Script Center includes other script samples that demonstrate
how to work with network configuration: http://www.microsoft.com/technet
/scriptcenter/scripts/network/client/default.msx.
Chapter 7: Inventorying and Reporting 97
On the CD The sample script can be found on the CD that accompanies this book
at \Chap7\ListServicePack\ListServicePack.wsf.
Description
This script creates a report—either on the screen or in a text file—that lists each tar-
geted computer’s name, the version of Windows it is running, and the version of the
latest service pack. Windows versions take the form of major.minor.build, with Win-
dows XP (for example) returning 5.1.2600. Service packs generally have only a major
number but are expressed as major.minor, such as 2.0 for Service Pack 2.
This script is useful for quickly checking your computers to determine what Windows
operating system and service pack they are running. This script does not check to see
whether the installed service pack is intact; it’s possible, for example, for a computer
to have Service Pack 2 installed but to have specific files overwritten with older
versions of those files, which effectively removes a portion of the service pack.
Example
As with many of the tools in this book, you can use this one in three different ways.
First, you can use it to target a single remote computer named ServerA, for example:
ListServicePack.wsf /computer:ServerA
98 Part II: Computer Management Tasks
Second, you can target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
ListServicePack.wsf /list:C:\Computers.txt
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
ListServicePack.wsf /container:west
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU
has nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.” Specifically, the following will write the tool’s output to a
comma-delimited file named C:\MyOutput.csv:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
You can run this script with the /? parameter to display the command’s syntax.
The current computer name is contained in the variable sName. Note that the script
connects to the computer’s \root\cimv2 namespace in Windows Management Instru-
mentation (WMI), and then retrieves the Win32_OperatingSystem instances from that
namespace. Although WMI supports the concept of multiple operating systems, in
practice, only one instance will be returned by this query. You could modify the script
to also report other operating system properties, such as the page file size and operat-
ing system manufacturer.
Troubleshooting
As with most scripts, connecting to the remote computer or computers and having the
permissions necessary to list service pack information (generally, local Administrator
permissions) leaves open the potential for errors. This script will catch most errors
and display an appropriate message, and then move on to the next targeted computer
if possible.
100 Part II: Computer Management Tasks
Because this script has the option to output to a file by using the /output argument,
you might receive an error if you specify that the file be created in a location where you
don’t have the necessary file system permissions, or if you specify a file name that
already exists and you don’t have permission to delete and re-create that file. In both
cases, the script will attempt to continue, but you’ll receive errors each time the log file
access is attempted. To break the script’s execution, press Ctrl+C in the command-line
window.
To Learn More
■ You can download the Microsoft Baseline Security Analyzer from http://
www.microsoft.com/mbsa.
■ The TechNet Script Center includes other script samples that demonstrate how
to work with hotfixes and service packs: http://www.microsoft.com/technet
/scriptcenter/scripts/srvpacks/default.mspx.
Chapter 7: Inventorying and Reporting 101
On the CD The sample script can be found on the CD that accompanies this book
at \Chap7\ListTasks\ListTasks.wsf.
Description
This task creates a report of scheduled tasks on one or more computers, providing a
way to quickly inventory all scheduled task operations on multiple computers. The
output of this script includes information about the schedules of these tasks, as well
as the basic command line used to execute the tasks. Regularly running this script can
be a valuable part of change management efforts because it creates a consistent,
complete inventory of scheduled tasks across your enterprise.
Example
You can use this script in three different ways. First, you can use it to target a single
remote computer named ServerA, for example:
ListTasks.wsf /computer:ServerA
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
ListTasks.wsf /list:C:\Computers.txt
102 Part II: Computer Management Tasks
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
ListTasks.wsf /container:west
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU
has nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.” Specifically, the following will write the tool’s output to a
comma-delimited file named C:\MyOutput.csv:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use
/computer:name /list to target a list of computers contained within a text
file. Use /computer to target a single computer. Use
/container:name
/container to target an organizational unit within Active
Directory.
/output:path Specifies the file to which the tool’s output should be writ-
ten. The file specified will be overwritten if it already exists.
/recurse When used with /container, also targets computers con-
tained within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce
the timeout wait when one or more computers cannot be
reached on the network.
/log:path Logs unreachable computer names to the specified file.
This file can then be used later, along with the /list argu-
ment, to retry these computers. Requires that you specify
the /ping argument.
/verbose Causes the script to display more detailed, step-by-step
status messages.
You can run this script with the /? parameter to display the command’s syntax.
Chapter 7: Inventorying and Reporting 103
The current computer name is contained in the variable sName. The script connects to
the computer’s \root\cimv2 namespace in Windows Management Instrumentation
(WMI), and then retrieves the Win32_ScheduledJob instances from that namespace.
This query returns a list of all scheduled tasks. The script then looks at each tasks and
outputs the relevant information for each by using properties of the class. Some of the
scheduled task properties, such as DaysOfMonth and DaysOfWeek, can be difficult to
interpret, so I recommend viewing those tasks for which you know the schedule
(or can look the schedule up in the graphical user interface) to compare the results of
this script. Doing so will help you become more familiar with how this information is
output by the operating system.
Also note that this script might return the message “***Couldn’t connect to WMI”
when a targeted computer has no scheduled tasks. This is normal and expected,
because no instances of the Win32_ScheduledJob class are returned to the script.
Troubleshooting
As with most scripts, connecting to the remote computer or computers and having the
permissions necessary to list scheduled tasks (generally, local Administrator permis-
sions, to view all tasks regardless of owner) leaves open the potential for errors. This
script will catch most errors and display an appropriate message, and then move on to
the next targeted computer if possible.
104 Part II: Computer Management Tasks
Because this script has the option to output to a file by using the /output argument,
you might receive an error if you specify that the file be created in a location where you
don’t have the necessary file system permissions, or if you specify a file name that
already exists and you don’t have permission to delete and re-create that file. In both
cases, the script will attempt to continue, but you’ll receive errors each time the log file
access is attempted. To break the script’s execution, press Ctrl+C in the command-line
window.
To Learn More
■ To learn more about the At.exe or Schtasks commands, consult the Windows
Help and Support Center.
■ The TechNet Script Center includes other script samples that demonstrate how
to work with scheduled tasks: http://www.microsoft.com/technet/scriptcenter
/scripts/os/tasks/default.mspx.
Chapter 7: Inventorying and Reporting 105
On the CD The sample script can be found on the CD that accompanies this book
at \Chap7\ListSoftware\ListSoftware.wsf.
Description
This task utilizes WMI and the Windows Installer service to retrieve a list of installed
applications on one or more computers, and to display that information on the screen
or in a report. This task is useful for discovering which computers have particular soft-
ware installed, or for auditing the software packages installed on a set of computers.
Example
As with many of the tools in this book, you can use this one in three different ways.
First, you can use it to target a single remote computer named ServerA, for example:
ListSoftware.wsf /computer:ServerA
Second, you can target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
ListSoftware.wsf /list:C:\Computers.txt
106 Part II: Computer Management Tasks
Third, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
ListSoftware.wsf /container:west
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.” Specifically, the following will write the tool’s output to a
comma-delimited file named C:\MyOutput.csv:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to
/container:name
target an organizational unit within Active Directory.
/output:path Specifies the file to which the tool’s output should be written.
The file specified will be overwritten if it already exists.
/recurse When used with /container, also targets computers
contained within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce
the timeout wait when one or more computers cannot be
reached on the network.
/log:path Logs unreachable computer names to the specified file. This
file can then be used later, along with the /list argument, to
retry these computers. Requires that you specify the /ping
argument.
/verbose Causes the script to display more detailed, step-by-step
status messages.
You can run this script with the /? parameter to display the command’s syntax.
Chapter 7: Inventorying and Reporting 107
The current computer name is contained in the variable sName. Note that the script
connects to the computer’s \root\cimv2 namespace in Windows Management
Instrumentation (WMI), and then retrieves the Win32_Product instances from that
namespace. This query returns a list of all installed software. The script then looks
at each item and outputs its relevant information by using properties of the class.
Troubleshooting
As with most scripts, connecting to the remote computer or computers and having
the permissions necessary to list installed software (generally, local Administrator
permissions) leaves open the potential for errors. This script will catch most errors
and display an appropriate message, moving on to the next targeted computer if
possible.
Because this script has the option to output to a file by using the /output argument,
you might receive an error if you specify that the file be created in a location where you
don’t have the necessary file system permissions, or if you specify a file name that
already exists and you don’t have permission to delete and re-create that file. In both
cases, the script will attempt to continue, but you’ll receive errors each time the log file
access is attempted. To break the script’s execution, press Ctrl+C in the command-line
window.
108 Part II: Computer Management Tasks
To Learn More
■ You can use the Msiexec command-line utility to install and manage applica-
tions from the command line. To learn more about this utility, consult the
Windows Help and Support Center.
■ The TechNet Script Center includes other script samples that demonstrate
how to work with applications: http://www.microsoft.com/technet/scriptcenter
/scripts/apps/user/default.mspx.
Chapter 8
Registry Management
In this chapter:
Create a Registry Key or Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
List Registry Permissions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
List Registry Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
109
110 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this
book at \Chap8\CreateRegKey\CreateRegKey.wsf and \Chap8\CreateRegKey\
CreateRegValue.wsf.
Description
When you need to distribute a new registry key to multiple computers—say, to config-
ure a new corporate application—you can do so via Group Policy in Microsoft Active
Directory®. However, using Group Policy does require you to create an administrative
template (.adm) file defining the registry key and values you want to set, which can be
a time-consuming and frustrating task. When you want to create only a single key or
value, this script offers a somewhat quicker way (which is admittedly less manageable
in the long term than a Group Policy, but still has its uses).
Note that this task is actually accomplished by using two commands: one to create
keys, and the other to create and set values under those keys.
Regedit does allow you to export registry information to a .reg file, which can then be
imported to remote computers. However, properly distributing the .reg files and
ensuring their integrity can be cumbersome in some environments.
Chapter 8: Registry Management 111
Example
These scripts allow you to target one computer or multiple computers. For example,
to target a single remote computer named ServerA and create a registry key named
SOFTWARE\MyKey under HKEY_LOCAL_MACHINE, you would use this code:
Note that these scripts work only with HKEY_LOCAL_MACHINE (HKLM). Modify-
ing HKEY_CURRENT_USER (HKCU) is complex when you’re working remotely;
because these tools use WMI, and because WMI impersonates your credentials on the
remote machine, the HKCU you modify will be yours, not that of the primary user of
the remote machine. To modify the primary user’s HKCU, you’d need to modify
HKEY_USERS and know the primary user’s Security ID (SID).
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
This code creates a new decimal word (DWORD, or numeric) value named MyValue
under the specified key, and sets the new value equal to 1.
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.”
112 Part II: Computer Management Tasks
Syntax
The scripts, CreateRegKey.wsf and CreateRegValue.wsf, can be executed as command-
line utilities. Set CScript.exe to be your default script processor, as described in
Chapter 3, “Working with VBScript.”
You can run these scripts with the /? parameter to display the command’s syntax.
Dim oReg
Set oReg=GetObject(“winmgmts:{impersonationLevel=impersonate}!\\” & sName &
“\root\default:StdRegProv”)On Error Resume Next
oReg.CreateKey &H80000002, WScript.Arguments.Named(“key”)
If Err <> 0 Then
WScript.Echo “ *** Failed to create key on “ & sName
Else
Verbose “ Created key on “ & sName
End If
Chapter 8: Registry Management 113
The StdRegProv provider is a piece of software running on the remote machine that
ties WMI into that machine’s registry. Using the CreateKey() method of the provider
creates a new registry key on the remote computer. The &H80000002 value is a
constant that specifies the HKLM portion of the registry, which is all these scripts are
capable of modifying.
Troubleshooting
These scripts have the potential to cause two major types of errors. First, a remote
computer won’t be available. Second, you won’t have permission to work with the
remote computer’s registry. In either case, you’ll see an error message that alerts you
to the problem for that particular computer. Make sure you have the appropriate
permissions and that the computer is reachable via the network from the computer
running this script. Unreachable computers can optionally be logged to a text file for
a later attempt, and you can speed up the script by specifying the /ping argument.
To Learn More
■ Learn more about the StdRegProv provider at http://go.microsoft.com/fwlink
/?LinkId=29999.
■ You can find a tutorial for using WMI to manage the registry at http://www.
serverwatch.com/tutorials/article.php/1476831.
114 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap8\ListRegPermission\ListRegPermission.wsf.
Description
Occasionally, you might need to figure out what permissions a particular user has on
a given registry key. The ListRegPermission.wsf script is designed to help with that
task. However, there are some caveats concerning what this script can accomplish for
you; see the next “Under the Hood” section for more details.
Example
This tool allows you to target one computer or multiple computers. When targeting
multiple computers, you can request they be listed in a text file or queried from Active
Directory. For example, if you want to use the script to target only a single remote
computer named ServerA and check a registry key named SOFTWARE\MyKey under
HKEY_LOCAL_MACHINE, you would use this code:
Note that you have to include the user name and password for the user you want to
check; more details about this are included in the next “Under the Hood” section.
Chapter 8: Registry Management 115
You can also target a list of computers from a text file. The text file is expected to con-
tain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide more functionality to the command; see the following
“Syntax” section.
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
116 Part II: Computer Management Tasks
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Requires the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/key:keyname Required. Specifies the registry key to create or the key under
which a new value should be created.
/user:name The user name and password of the user account whose
/password:password permissions you want to check. Optional; if you omit these
arguments the script will check your permissions on the
specified registry key.
/output:path Logs the script’s output to a text file specified in path.
You can run these scripts with the /? parameter to display the command’s syntax.
The QueryWMI() function is used to connect to the targeted computer and issue a
query to its WMI service. When you include the /user and /password arguments, this
connection is made using the user credentials you specify. Thus, the remote com-
puter’s WMI service is impersonating the credentials you provided, and the registry
CheckAccess() method is checking the access for that account. If you omit the /user
and /password arguments, your user account is used to make the connection.
Chapter 8: Registry Management 117
The CheckAccess() method requires that you specify a registry key as well as a permis-
sion that you want to check, such as permission to query the key (represented by
KEY_QUERY_VALUE in the preceding script code). This script, then, performs sev-
eral calls to CheckAccess() to check various permissions for the specified user account.
Troubleshooting
Permissions become a complex issue with this script. To use the script, you must
specify a user account that has permissions to both connect to each targeted com-
puter and issue WMI queries to those computers. However, the account you specify is
the account whose permissions will be checked in the registry. In other words, you
won’t be able to check the permissions of any account that does not already have per-
missions to connect to the targeted computers and issue WMI queries to them. Most
of the problems that this script can run into are, therefore, related to permissions. The
script will attempt to display any errors that occur so that you can try an alternate user
account.
To Learn More
■ Learn more about the StdRegProv provider at http://go.microsoft.com/fwlink
/?LinkId=29999.
■ You’ll find a tutorial for using WMI to manage the registry at http://www.
serverwatch.com/tutorials/article.php/1476831.
118 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap8\ListRegValue\ListRegValue.wsf.
Description
One common administrative task is to figure out what various computers have for a
specific registry value. This ListRegValue.wsf script makes it easy to inventory that
information by remotely checking the specified registry value on multiple computers
and logging that information to a file for later analysis.
Example
This tool allows you to target one computer or multiple computers. When targeting
multiple computers, those compters can listed in a text file or queried from Active
Directory. For example, if you wanted to use the script to target a single remote com-
puter named ServerA and check a registry key named SOFTWARE\MyKey under
HKEY_LOCAL_MACHINE, the tool would check a REG_SZ (string) value named
MyValue:
Because these tools use WMI, and because WMI impersonates your credentials on
the remote machine, the HKCU you check will be yours, not the primary user of the
remote machine. To modify the primary user’s HKCU, you’d need to modify
HKEY_USERS and know the primary user’s Security ID (SID).
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
You can run these scripts with the /? parameter to display the command’s syntax.
Troubleshooting
To use this script, you need to have, on each remote computer, permissions to query
the registry. Any problems encountered by this script will most likely be related to
permissions, and the script will display appropriate error and progress messages to
advise you of these problems.
To Learn More
■ Learn more about the StdRegProv provider at http://go.microsoft.com/fwlink
/?LinkId=29999.
■ You’ll find a tutorial on using WMI to manage the registry at
http://www.serverwatch.com/tutorials/article.php/1476831.
Chapter 9
Other Computer
Management Tasks
In this chapter:
Change Local Account Passwords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Clear Print Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Print Test Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
List Running Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Start a Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
End a Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
List Page Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Modify Page File Settings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Shut Down or Restart Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Modify Boot.ini Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Administrators are often required to make minor changes to client computers in their
environments—minor, of course, until they must be made on a large number of com-
puters. Some of these changes include adjustments to security practices such as mod-
ifying local account passwords. Other changes result from troubleshooting efforts and
maintenance, such as managing client and server page files.
123
124 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap9\ChangeLocalPassword\ChangeLocalPassword.wsf.
Description
One of the best yet most overlooked security practices in a Windows® environment is
regularly changing local account passwords, especially for sensitive built-in accounts
like Administrator. Domain-based password policies can be used to force a change on
a periodic basis, but because local accounts like Administrator are rarely used on
many client computers, the password change is never triggered. (Password policies
can require a change only when the account is actually used to log on to the com-
puter.) As a result, these local passwords often go unchanged for long periods of time,
increasing the likelihood that they will be compromised.
However, the Windows operating system does not provide a built-in means of chang-
ing local accounts on multiple computers at once. (In fact, the primary purpose of a
domain is to avoid the need to constantly manage local user accounts on multiple
computers.)
126 Part II: Computer Management Tasks
Example
The ChangeLocalPassword.wsf script allows you to target one computer or multiple
computers. If you want to use it to target a single remote computer named ServerA and
change the password for the Administrator account, you would use this code:
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain that the computer running the script belongs to. If the specified OU
has nested OUs, you can include their computer accounts as well by specifying one
additional argument:
This is an excellent way to ensure that a consistent local user account password is
used across multiple client or server computers. Additional arguments provide more
functionality to the command; see the following section titled “Syntax.”
Syntax
This script can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3, “Working with VBScript.”
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Microsoft Active Directory®.
Note that all computer names must be actual computer names;
aliases such as localhost, as well as IP addresses, will not work.
/recurse When used with /container, also targets computers contained
within nested OUs.
Chapter 9: Other Computer Management Tasks 127
You can run these scripts with the /? parameter to display the command’s syntax.
Dim oUser
Set oUser = QueryADSI(sName,"WinNT:// " & sName & "/" &
WScript.Arguments.Named("user") & ",user")
If Not IsObject(oUser) Then
WScript.Echo " *** Couldn’t retrieve user from " & sName
Else
On Error Resume Next
oUser.setpassword WScript.Arguments.Named("password")
If Err <> 0 Then
WScript.Echo " *** Couldn’t change password on " & sname
WScript.Echo " " & Err.Description
Else
Verbose " Changed password on " & sName
End If
End If
The script uses this WinNT provider to connect to each targeted computer and retrieve
the specified user account. (The inclusion of ",user" ensures that computer, group, or
other objects with similar names are not retrieved by accident.) The returned User
object supplies a SetPassword method that is used to change the password.
128 Part II: Computer Management Tasks
Troubleshooting
This script has the potential to create three major types of errors. First, a remote com-
puter won’t be available. Second, you won’t have permission to work with the remote
computer’s users. (Typically, only a member of the Administrators local group has
permission to change user passwords.) In either case, you’ll see an error message that
alerts you to the problem for that computer. Make sure you have the appropriate
permissions and that the computer is reachable via the network from the computer
running this script. Unreachable computers can optionally be logged to a text file for
a later attempt, and you can speed up the script by specifying the /ping argument.
The third potential problem is that one or more of the targeted computers won’t have
the user account specified. Although this situation wouldn’t normally occur for built-
in accounts like Administrator (unless you’ve inconsistently renamed that account on
various computers), it could occur for other local accounts that you might have
created. In these instances, the script will return an error and continue trying with
the next targeted computer.
To Learn More
■ Learn more about the WinNT ADSI provider at http://msdn.microsoft.com
/library/default.asp?url=/library/en-us/adsi/adsi/adsi_winnt_provider.asp.
■ Find more local user account management samples in Microsoft Visual Basic®
(VBScript) at http://www.microsoft.com/technet/scriptcenter/scripts/ds/local
/users/default.mspx.
Chapter 9: Other Computer Management Tasks 129
On the CD The sample script can be found on the CD that accompanies this book
at \Chap9\ClearPrintQueue\ClearPrintQueue.wsf.
Description
This script, ClearPrintQueue.wsf, will clear documents from one or more print queues
on one or more computers. This is typically a troubleshooting or maintenance step
performed by an administrator.
Example
This tool allows you to target one computer or multiple computers. You can clear all
print queues on each targeted computer, or you can choose to clear only one named
queue. In the latter case, the queue specified must exist with the same name on
each targeted computer. To use the script to target a single remote computer named
ServerA and clear all queues, you would use this code:
You can also target a list of computers from a text file. The text file is expected to con-
tain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Note that this example clears a queue named MyQueue (which is the name of the
installed printer), which would exist on each targeted computer. Additional argu-
ments provide more functionality to the command; see following section titled
“Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/all One of these is required. Use /all to clear all queues on each
/queue:queuename targeted computer, or specify a specific queue by using
/queue:queuename.
You can run these scripts with the /? parameter to display the command’s syntax.
Chapter 9: Other Computer Management Tasks 131
Troubleshooting
This script has the potential for several types of errors. First, a remote computer won’t
be available. Second, you won’t have permission to work with the remote computer’s
print queues. (Typically, only a member of the Administrators and Power Users or
Print Operators groups has permission to cancel all print jobs; ordinary users can
typically cancel only their own jobs.) In either case, you’ll see an error message that
alerts you to the problem for that computer. Make sure you have the appropriate
permissions and that the computer is reachable via the network from the computer
running this script. Unreachable computers can optionally be logged to a text file for
a later attempt, and you can speed up the script by specifying the /ping argument.
The third potential problem is that one or more of the targeted computers won’t have
the queue specified (if you use the /queue argument). In these instances, the script
will return an error and continue trying with the next targeted computer. It’s also pos-
sible for the script to encounter an error while trying to cancel one or more jobs—jobs
132 Part II: Computer Management Tasks
can become stuck, or the script might be unable to obtain permissions for specified
jobs. In these cases, the script will again return an error message and continue trying
with the next print queue. However, the script is not designed to retry queues whose
jobs have failed to cancel.
To Learn More
■ Find more VBScript samples for managing printers at http://
www.microsoft.com/technet/scriptcenter/scripts/printing/default.mspx.
■ Learn more about the Win32_Printer class at http://msdn.microsoft.com/library
/default.asp?url=/library/en-us/wmisdk/wmi/win32_printer.asp.
Chapter 9: Other Computer Management Tasks 133
On the CD The sample script can be found on the CD that accompanies this book
at \Chap9\PrintTestPage\PrintTestPage.wsf.
Description
This tool will print test pages, on one or more computers, for all queues or for a named
queue. This is a great way to periodically test your queues for proper operation, or a
quick way for an administrator or support technician to test a remote print server’s
queues during troubleshooting.
I’ve also used this script to quickly identify which physical print devices are connected
to a given print server—helpful because some organizations lose track of this informa-
tion. This script can target all queues on a given print server; print devices producing
a test page reveal which devices are connected to a particular server.
1. Right-click a printer in the Printers And Faxes folder, and select Properties.
2. In the printer’s Properties dialog box, click Print Test Page.
A one-page (typically) test is produced that confirms that the printer is working
properly and that lists the driver files in use by the printer.
Example
This tool allows you to target one computer or multiple computers. You can clear all
print queues on each targeted computer, or you can choose to clear only one named
queue. In the latter case, the queue specified must exist with the same name on each
targeted computer. If you wanted to use the script to target a single remote computer
named ServerA and test all queues, you would use this code:
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain of the computer running the script. If the specified OU has nested
OUs, you can include their computer accounts as well by specifying one additional
argument:
Note that this example tests a queue named MyQueue (which is the name of the
installed printer), which must exist on each targeted computer. Additional arguments
provide more functionality to the command; see the following section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
Chapter 9: Other Computer Management Tasks 135
You can run these scripts with the /? parameter to display the command’s syntax.
Troubleshooting
This script has the potential to experience several types of errors. First, a remote com-
puter won’t be available. Second, you won’t have permission to work with the remote
computer’s print queues. A permissions issue is rare, however, because you’re merely
printing a document, which all users generally have permissions to do. Any permis-
sions issue you encounter will more likely be a result of connecting to WMI itself, a
task that often only Administrators have permission to do. In either case, you’ll see an
error message that alerts you to the problem for that computer. Make sure you have
the appropriate permissions and that the computer is reachable via the network from
the computer running this script. Unreachable computers can optionally be logged to
a text file for a later attempt, and you can speed up the script by specifying the /ping
argument.
The third potential problem is that one or more of the targeted computers won’t have
the queue specified (if you use the /queue argument). In these instances, the script
will return an error and continue trying with the next targeted computer. It’s also pos-
sible for the script to encounter an error while trying to print the test page. This is also
rare—Windows typically sends the test page job to the printer much like it would for
any other print job. Problems will show up in the printer’s queue monitoring window,
but problems won’t usually result in an error being returned to the script.
To Learn More
■ Find more VBScript samples for managing printers at http://
www.microsoft.com/technet/scriptcenter/scripts/printing/default.mspx.
■ Learn more about the Win32_Printer class at http://msdn.microsoft.com/library
/default.asp?url=/library/en-us/wmisdk/wmi/win32_printer.asp.
Chapter 9: Other Computer Management Tasks 137
On the CD The sample script can be found on the CD that accompanies this book
at \Chap9\ListProcesses\ListProcesses.wsf.
Description
This tool will list all processes running on one or more computers. Optionally, the
script’s output can be directed to a comma-separated values (CSV) file, providing you
with a report of running processes. This file is a useful inventory tool because it allows
you to more easily audit the processes running on your computers and look for unau-
thorized applications, outdated software, and so forth.
Example
This tool allows you to target one computer or multiple computers. To use the script
to target a single remote computer named ServerA and list the running processes to
the console, you would use the following code:
ListProcesses.wsf /computer:ServerA
138 Part II: Computer Management Tasks
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Note that this syntax outputs the process list to a CSV file named C:\Proclist.csv. This
file is especially useful when targeting multiple computers, because the amount of
information generated can be awkward to review in a command-line window.
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the com-
puter running the script. In other words, the OU specified must exist within the same
domain of the computer running the script. If the specified OU has nested OUs, you
can include their computer accounts as well by specifying one additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/output:path Optionally logs the script’s output to a CSV file.
You can run these scripts with the /? parameter to display the command’s syntax.
Chapter 9: Other Computer Management Tasks 139
The variable sOutput is used to contain information about each process, including its
name, process ID, and the command-line used to execute the process. The sOutput
variable is then printed in the command-line window or, if you use the /output argu-
ment, to the specified CSV file.
Troubleshooting
This script has the potential to result in two types of errors. First, a remote computer
won’t be available. Second, you won’t have permission to work with the remote com-
puter’s processes. (Typically, only a member of the Administrators group has permis-
sion to do so.) In either case, you’ll see an error message that alerts you to the problem
for that computer. Make sure you have the appropriate permissions and that the com-
puter is reachable via the network from the computer running this script. Unreach-
able computers can optionally be logged to a text file for a later attempt, and you can
speed up the script by specifying the /ping argument.
To Learn More
■ Find more VBScript samples for managing and monitoring processes at
http://www.microsoft.com/technet/scriptcenter/scripts/os/process/default.mspx.
■ Learn more about the Win32_Process class at http://msdn.microsoft.com/library
/default.asp?url=/library/en-us/wmisdk/wmi/win32_process.asp.
140 Part II: Computer Management Tasks
Start a Process
On the CD The sample script can be found on the CD that accompanies this book
at \Chap9\StartProcess\StartProcess.wsf.
Description
This tool will start a new process, using the specified command line, on one or more
computers. The results of this tool will differ somewhat depending on the precise
circumstances in which you run the script. For example, when a user starts a new
process (such as an application) using Microsoft Windows Explorer, the process
runs under the user’s normal security context and is visible on the user’s desktop.
Processes started by other users, however, are generally prevented from interacting
with the logged-on user’s desktop. Because this script uses your credentials to connect
to remote computers, the processes you start will usually be running under your secu-
rity context on the remote computer and might not be visible to the user logged on to
that computer. So you might not be able to use this script to, for example, open a new
instance of Microsoft Notepad, which will be visible to the logged-on user. Consider
this tool to be more appropriate for starting new background maintenance tasks
(such as disk defragmenters), which require no user interaction.
The lack of user interaction can also pose problems. If you start a process that requires
some user interaction, but the process is not visible to the logged-on user, the process
might “hang” while it waits for a response to a dialog box or some other interactive ele-
ment. Try to avoid remotely starting processes that might require such interaction.
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use the script to target a single remote computer named ServerA and start a process
named MyProcess.exe, you would use the following code:
Note that the /cmd argument requires a complete path to the process you want started
unless the process specified is in the system search path (which generally includes the
Windows and Windows\System32 directories).
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within
the same domain of the computer running the script. If the specified OU has nested
OUs, you can include their computer accounts as well by specifying one additional
argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
142 Part II: Computer Management Tasks
You can run these scripts with the /? parameter to display the command’s syntax.
Troubleshooting
This script has the potential to result in several types of errors. First, a remote
computer won’t be available. Second, you won’t have permission to start remote
processes. Generally, local Administrator permissions are required to start remote
Chapter 9: Other Computer Management Tasks 143
processes via WMI. In either case, you’ll see an error message that alerts you to the
problem for that computer. Make sure you have the appropriate permissions and that
the computer is reachable via the network from the computer running this script.
Unreachable computers can optionally be logged to a text file for a later attempt, and
you can speed up the script by specifying the /ping argument.
The third potential problem is that the targeted computers will be unable to access the
executable you specify. This will result in the script displaying an error, which will
likely occur for all targeted computers. In most environments, WMI will attempt to
access the specified executable using your credentials, so if you must, specify a UNC
or local file path to which your user account has at least Read and Execute privileges.
To Learn More
■ Find more VBScript samples for managing and monitoring processes at http://
www.microsoft.com/technet/scriptcenter/scripts/os/process/default.mspx.
■ Learn more about the Win32_Process class at http://msdn.microsoft.com
/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_process.asp.
144 Part II: Computer Management Tasks
End a Process
On the CD The sample script and be found on the CD that accompanies this book
at \Chap9\EndProcess\EndProcess.wsf.
Description
This tool will end a named process on one or more computers. This is an excellent
way to stop undesired processes that might be running. Note that you must provide
the name of each process, which is sometimes slightly different from the name of its
command-line executable. The name sometimes includes a file name extension, such
as .exe, but not always; I recommend using the ListProcesses script, described in this
chapter, to list the processes on a representative computer. That script lists, among
other details, each process’s name.
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use the script to target a single remote computer named ServerA and terminates a
process named MyProcess.exe, you would use this code:
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within
the same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list to
/computer:name target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
/log:path Logs unreachable computer names to the specified file. This
file can then be used later, along with the /list argument, to
retry these computers. Note that a log is created only when
used in conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/name:processname Required. Identifies the name of the process to terminate. This
must be the actual process name, which might include a file
name extension for some processes.
You can run these scripts with the /? parameter to display the command’s syntax.
146 Part II: Computer Management Tasks
Each instance of the Win32_Process class provides a Terminate() method that attempts
to end the process.
Troubleshooting
This script has the potential to result in several types of errors. First, a remote com-
puter won’t be available. Second, you won’t have permission to work with the remote
computer’s processes (typically, only a member of the Administrators group will have
permission to terminate a process). In either case, you’ll see an error message that
alerts you to the problem for that computer. Make sure you have the appropriate
permissions and that the computer is reachable via the network from the computer
running this script. Unreachable computers can optionally be logged to a text file for
a later attempt, and you can speed up the script by specifying the /ping argument.
The third potential problem is that one or more of the targeted computers won’t have
the process. In these instances, the script will return an error and continue trying with
the next targeted computer. It’s also possible for the script to encounter an error
while trying to terminate the process; some processes can be configured, for security
Chapter 9: Other Computer Management Tasks 147
Note that terminating a process is not the same as ending it cleanly. Terminating a pro-
cess will often result in the loss of whatever data the process was working with; you
should terminate processes only when you’re certain that doing so will not destabilize
Windows, other processes or services, or result in a loss of important data.
To Learn More
■ Find more VBScript samples for managing and monitoring processes at http://
www.microsoft.com/technet/scriptcenter/scripts/os/process/default.mspx.
■ Learn more about the Win32_Process class at http://msdn.microsoft.com/library
/default.asp?url=/library/en-us/wmisdk/wmi/win32_process.asp.
148 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap9\ListPageFile\ListPageFile.wsf.
Description
This tool will list the page file properties for all page files on one or more computers.
For each page file, you are shown its host drive, initial size, and maximum size.
Optionally, the tool can save this information to a CSV file for long-term archiving
or reporting. This is a useful way to quickly check a number of computers to ensure
that their page files are optimally configured or configured to meet your organiza-
tion’s policies.
1. Right-click My Computer.
2. Select Properties to open the System Properties dialog box.
3. Select the Advanced tab.
4. Under the Performance section, click Settings to display the Performance
Options dialog box.
5. Select the Advanced tab.
6. Under the Virtual Memory section, click Change to display the Virtual Memory
dialog box.
Using this procedure to review the page file settings of multiple computers, however,
can be tedious.
Chapter 9: Other Computer Management Tasks 149
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use the script to target a single remote computer named ServerA and display its page
file settings in the command-line window, you would use this code:
ListPageFile.wsf /computer:ServerA
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Note that this saves the output to a CSV file, which can be easier to review than the
command-line window when targeting multiple computers. Finally, you can target an
entire organizational unit of computer accounts. If your domain contains an OU
named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within
the same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list to tar-
/computer:name get a list of computers contained within a text file. Use /computer
to target a single computer. Use /container to target an organiza-
/container:name
tional unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
150 Part II: Computer Management Tasks
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/output:path Saves the script’s output to a CSV file specified in path.
You can run these scripts with the /? parameter to display the command’s syntax.
Troubleshooting
This script has the potential to result in two types of errors. First, a remote computer
won’t be available. Second, you won’t have permission to work with the remote
computer’s page files. In either case, you’ll see an error message that alerts you to the
problem for that computer. Make sure you have the appropriate permissions and that
the computer is reachable via the network from the computer running this script.
Unreachable computers can optionally be logged to a text file for a later attempt, and
you can speed up the script by specifying the /ping argument.
Chapter 9: Other Computer Management Tasks 151
To Learn More
■ Find more VBScript samples for managing page files at http://
www.microsoft.com/technet/scriptcenter/scripts/os/pagefile/default.mspx.
■ Learn more about the Win32_PageFile class at http://msdn.microsoft.com
/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_pagefile.asp.
152 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap9\ModifyPageFile\ModifyPageFile.wsf.
Description
This tool will modify the initial and maximum sizes for all page files on one or more
computers. This is a useful, quick way to reconfigure multiple computers to have con-
sistent page file settings.
1. Right-click My Computer.
2. Select Properties to open the System Properties dialog box.
3. Select the Advanced tab.
4. Under the Performance section, click Settings to display the Performance
Options dialog box.
5. Select the Advanced tab.
6. Under the Virtual Memory section, click Change to display the Virtual Memory
dialog box.
Using this procedure to modify the page file settings of multiple computers, however,
can be tedious.
Example
This tool allows you to target one computer or multiple computers. You must specify
the /initsize and /maxsize parameters, which both accept a size in megabytes (MB). If
you wanted to use the script to target a single remote computer named ServerA and set
Chapter 9: Other Computer Management Tasks 153
its page file to have an initial size of 128 MB and a maximum size of 384 MB, you
would use this code:
Note that for computers with multiple page files (many administrators, for example,
create page files on multiple physical drives to help spread the page file workload),
each page file will be configured to have the initial and maximum size you specify.
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within
the same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
154 Part II: Computer Management Tasks
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/initsize:MB Required. Specifies the initial page file size in megabytes.
/maxsize:MB Required. Specifies the maximum page file size in megabytes.
You can run these scripts with the /? parameter to display the command’s syntax.
Next
End If
Chapter 9: Other Computer Management Tasks 155
Notice that the Win32_PageFile class is retrieved from each computer, and the class’s
InitialSize and MaximumSize properties are modified. These are some of the very few
WMI properties that can be directly read and written by a script; most WMI properties
are read-only, and you make changes by using methods of the class. In the example
in the preceding code, you must use the class’s Put_() method to save the changes
made to the properties.
Troubleshooting
This script has the potential to result in several types of errors. First, a remote com-
puter won’t be available. Second, you won’t have permission to work with the remote
computer’s page files. (Typically, only a member of the Administrators group has
permission to do so.) In either case, you’ll see an error message that alerts you to the
problem for that computer. Make sure you have the appropriate permissions and
that the computer is reachable via the network from the computer running this script.
Unreachable computers can optionally be logged to a text file for a later attempt, and
you can speed up the script by specifying the /ping argument.
The third potential problem is that one or more of the targeted computers won’t have
the disk space needed to support the page file sizes you specify. Be very careful to
not specify a page file that would exceed the available disk space; Chapter 10, “File,
Disk, and Volume Management,” includes tools to help you automate the process of
inventorying available drive space on multiple computers.
To Learn More
■ Find more VBScript samples for managing page files at http://
www.microsoft.com/technet/scriptcenter/scripts/os/pagefile/default.mspx.
■ Learn more about the Win32_PageFile class at http://msdn.microsoft.com
/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_pagefile.asp.
156 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap9\ShutdownRestart\ShutdownRestart.wsf.
Description
This tool will shut down, restart, log off, or power off multiple computers. The power
off functionality must be supported in the computers’ hardware and BIOS; if it is not,
the power off command will be interpreted as a simple shutdown command. This tool
will, by default, issue normal commands for shut down, restart, and so forth, meaning
individual applications could intercept and abort the command. This tool can option-
ally force the specified operation, which will give applications a fixed amount of time
in which to shut down properly, and then it can terminate any applications that fail
to do so.
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use the script to target a single remote computer named ServerA and shut it down, you
would use this code:
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the com-
puter running the script. In other words, the OU specified must exist within the same
domain as that of the computer running the script. If the specified OU has nested OUs,
you can include their computer accounts as well by specifying one additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/action:command Required. Command must be one of these: restart, logoff,
shutdown, or poweroff.
/force Forces the command specified in /action, preventing an applica-
tion or process from aborting the specified command.
You can run these scripts with the /? parameter to display the command’s syntax.
158 Part II: Computer Management Tasks
The Win32_OperatingSystem class also has a Shutdown() method, but this script uses
the more flexible Win32Shutdown() method, which supports additional commands
such as power off as well as the ability to force the specified command.
Chapter 9: Other Computer Management Tasks 159
Troubleshooting
In this script, other than connectivity issues (which can be avoided by specifying the
/ping argument to test for connectivity), only a lack of permissions will result in an
error. Typically, members of a computer’s local Administrators group have permis-
sions to initiate remote shutdown, restart, poweroff, or logoff.
To Learn More
■ Learn more about the Win32_OperatingSystem class and its Win32Shutdown()
method at http://msdn.microsoft.com/library
/default.asp?url=/library/en-us/wmisdk/wmi/win32shutdown_method_
in_class_win32_operatingsystem.asp.
■ Read more about the Shutdown.exe command-line tool.
❑ Windows 2000: http://support.microsoft.com/default.aspx?scid=kb;
en-us;317371.
❑ Windows Server 2003: http://www.microsoft.com/resources/documentation
/WindowsServ/2003/standard/proddocs/en-us/Default.asp?url=/resources
/documentation/WindowsServ/2003/standard/proddocs/en-us
/shutdown.asp.
160 Part II: Computer Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap9\ModifyBootIni\ModifyBootIni.wsf.
Description
This tool will modify the Boot.ini file on one more computers so that it has a new
startup delay time. This delay time specifies how long the Windows operating system
selection screen is displayed before Windows starts the default operating system.
Many Windows computers will not display an operating system selection screen.
When only one operating system and the Recovery Console is not installed, Boot.ini
contains only one entry, and Windows always starts that entry without displaying
the selection screen. However, it is a best practice (at least on servers) to install the
Recovery Console, which will cause the selection screen to be displayed when the
server starts. Consistently configuring the delay time on this screen will make your
servers more predictable and easier to manage in the event the Recovery Console is
needed.
1. Right-click My Computer.
2. Select Properties to display the System Properties dialog box.
3. Select the Advanced tab.
4. Under the Startup And Recovery section, click Settings to display the Startup
And Recovery dialog box.
5. Modify the Time to display a list of operating systems values as desired. (The
default is 30 seconds.)
Chapter 9: Other Computer Management Tasks 161
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use the script simply to target a single remote computer named ServerA and set its
startup delay to 45 seconds, you would use this code:
You can also target a list of computers from a text file. The text file is expected to con-
tain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached on
the network.
162 Part II: Computer Management Tasks
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/delay:seconds Required. Specifies the number of seconds to display the operat-
ing system selection screen before starting the default entry.
You can run these scripts with the /? parameter to display the command’s syntax.
Troubleshooting
This script has the potential to result in two types of errors. First, a remote computer
won’t be available. Second, you won’t have permission to work with the remote com-
puter’s Boot.ini properties. (Typically, only a member of the Administrators group will
Chapter 9: Other Computer Management Tasks 163
have permission to do so.) In either case, you’ll see an error message that alerts you to
the problem for that computer. Make sure you have the appropriate permissions and
that the computer is reachable via the network from the computer running this script.
Unreachable computers can optionally be logged to a text file for a later attempt, and
you can speed up the script by specifying the /ping argument.
To Learn More
■ Find more VBScript samples for managing startup and shutdown properties at
http://www.microsoft.com/technet/scriptcenter/scripts/desktop/state/default.mspx.
■ Learn more about remote access to the Win32_ComputerSystem class at http://
msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi
/accessing_a_remote_wmi_win32_computersystem_object.asp.
Part III
Disk and File Management Tasks
Chapter 10
File, Disk, and Volume
Management
In this chapter:
Taking Ownership of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Compress or Uncompress Files and Folders . . . . . . . . . . . . . . . . . . . . . . . 172
List Free Disk Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Inventory Disks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
Inventory Logical Drives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Defragment Disks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Schedule Disk Defragmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
File, disk, and volume management can often be one of the most tedious kinds of
management in a Microsoft® Windows® environment. The widespread use of the
Windows® operating system as a file server means that many organizations have
hundreds or thousands of megabytes of files. Thus, any management task that must
affect more than a handful of files can become laborious and time-consuming.
167
168 Part III: Disk and File Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap10\TakeOwnership\TakeOwnership.wsf.
Description
Most organizations routinely make the Administrator account the owner of all files
not belonging to a particular user. Ownership of files by the Administrator account
helps ensure consistent permissions and recoverability for files across the organiza-
tion. On file servers where quotas are enabled, having files owned by the Administra-
tor account enables those files to be excluded from an individual user’s quota, which
is commonly desired for files that are shared by a project team, by a department, or by
the entire company. This script, TakeOwnership.wsf, enables you to quickly take own-
ership of multiple files on multiple servers, improving consistency and manageability.
5. In the Change Owner To list box, select the new owner for the file or folder.
Select the Replace Owner On Subcontainers And Objects check box to make the
change effective for files and subfolders within a folder.
6. Click OK twice.
This technique does not, however, work across multiple servers. You can perform this
task remotely, one server at a time, by accessing remote files through a shared folder
or by logging onto the remote server using Remote Desktop (if enabled).
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use it to target a single remote computer named ServerA and take ownership of all files
in the C:\Shares folder, you would use this code:
Notice that the /folder argument requires you to provide a local file path, not a UNC.
The preceding code will therefore take ownership of the C:\Shares folder on the
computer named ServerA.
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit (OU) of computer accounts. If
your domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
This script always assigns ownership to your user account. Additional arguments
provide more functionality to the command; see the following section titled “Syntax.”
170 Part III: Disk and File Management Tasks
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3, “Working with VBScript.”
/list:path One and only one of these is required by the script. Use /list to
/computer:name target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Microsoft Active Directory®.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached on
the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/folder:path Required. Specifies the local path of the folder to take ownership
of. Must exist on all targeted servers.
You can run these scripts with the /? parameter to display the command’s syntax.
Notice that the script handles the conversion of the folder path you specify to the
format required by WMI; specifically, backslashes (which are treated as special char-
acters by WMI) are doubled, ensuring they will be recognized as part of the folder
path. This conversion is accomplished through the use of the Replace() function.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to take ownership of the files involved.
This is unusual if you’re running the script as an administrator, but the script will
detect this error, display a message, and continue running.
It’s also possible that one or more targeted servers won’t contain the folder you’ve
specified. This script’s primary value is in ensuring consistent ownership across file
servers that are already more or less consistently configured; for example, all your file
servers might house their shared folders under a root \Shares folder, which could in
turn be targeted by this script. However, on less consistently configured servers, the
script will display a message and skip any server not containing the specified folder.
To Learn More
■ Learn more about the Win32_Directory class and its TakeOwnership() method at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/
takeownership_method_in_class_win32_directory.asp.
■ Find more local folder managament samples in Microsoft Visual Basic®
(VBScript) at http://www.microsoft.com/technet/scriptcenter/scripts/storage/
folders/default.mspx.
172 Part III: Disk and File Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap10\CompressDecompress\CompressDecompress.wsf.
Description
Many organizations use the native file compression features offered by Windows to
reduce disk space utilization on crowded file servers. This script enables you to con-
sistently apply or remove file compression on a folder that exists on multiple file
servers. This script works best for file servers that are consistently configured—for
example, servers that contain all their shared folders under a root \Shares folder. This
script is designed to target local file paths rather than shared folders, enabling you to
apply or remove folder compression at any level of the folder hierarchy.
This technique does not, however, work across multiple servers. You can perform this
task remotely, one server at a time, by accessing remote files through a shared folder
or by logging on to the remote server using Remote Desktop (if enabled).
Chapter 10: File, Disk, and Volume Management 173
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use it to target a single remote computer named ServerA and compress all files in the
C:\Shares folder, you would use this code:
Notice that the /folder argument requires you to provide a local file path, not a UNC.
Using the local file path compresses the C:\Shares folder on the computer named
ServerA.
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within
the same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.”
Syntax
These scripts can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target an
/container:name
organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
174 Part III: Disk and File Management Tasks
You can run these scripts with the /? parameter to display the command’s syntax.
Notice that the script handles the conversion of the folder path you specify to the
format required by WMI; specifically, backslashes (which are treated as special
characters by WMI) are doubled, ensuring they will be recognized as part of the folder
path. This conversion is accomplished through the use of the Replace() function.
Chapter 10: File, Disk, and Volume Management 175
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second
possible error is that you won’t have permission to manage compression of the files
involved. This is unusual if you’re running the script as an administrator, but the
script will detect this error, display a message, and continue running.
It’s also possible that one or more targeted servers won’t contain the folder you’ve
specified. This script’s primary value is in ensuring consistent compression settings
across file servers that are already more or less consistently configured; for example,
all your file servers might house their shared folders under a root \Shares folder,
which could in turn be targeted by this script. However, on less consistently config-
ured servers, the script will display a message and skip any server not containing the
specified folder.
To Learn More
■ Learn more about the Win32_Directory class and its Compress() method at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/
compress_method_in_class_win32_directory.asp.
■ Find more local folder management samples in VBScript at http://
www.microsoft.com/technet/scriptcenter/scripts/storage/folders/default.mspx.
176 Part III: Disk and File Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap10\ListFreeDiskSpace\ListFreeDiskSpace.wsf.
Description
Without using third-party tools, quickly obtaining a free disk report from multiple
computers can sometimes be difficult. Being able to do so is certainly useful for
servers, but it’s also useful for client computers, because it allows you to quickly
determine which computers might need additional maintenance to free up disk space.
This script can target multiple computers and create a formatted report of available
disk space one ach drive within each computer.
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use it to target a single remote computer named ServerA and display its free disk space
in the command-line window, you would use this code:
FreeDiskSpace.wsf /computer:ServerA
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Note that this saves the free disk space report to a comma-separated values (CSV) file
named C:\Report.csv, which can be easier to review than the command-line window
display.
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the com-
puter running the script. In other words, the OU specified must exist within the same
domain as that of the computer running the script. If the specified OU has nested OUs,
you can include their computer accounts as well by specifying one additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target an
/container:name
organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached on
the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry these
computers. Note that a log is created only when used in conjunc-
tion with the /ping argument.
/output:path Saves the free disk space information to a CSV file specified in path.
You can run these scripts with the /? parameter to display the command’s syntax.
178 Part III: Disk and File Management Tasks
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query.
The second possible error is that you won’t have permission to examine the drives
involved. This is unusual if you’re running the script as an administrator, but the
script will detect this error, display a message, and continue running.
To Learn More
■ Learn more about the Win32_LogicalDisk class at http://msdn.microsoft.com/
library/default.asp?url=/library/en-us/wmisdk/wmi/win32_logicaldisk.asp.
■ Find more disk management samples in VBScript at http://www.microsoft.com/
technet/scriptcenter/scripts/storage/disks/drives/default.mspx.
Chapter 10: File, Disk, and Volume Management 179
Inventory Disks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap10\InventoryDrives\InventoryDrives.wsf.
Description
Obtaining a quick inventory of your computers’ hard disks can be difficult if you
aren’t using a systems management tool like Microsoft Systems Management Server
(SMS). This script can scan multiple computers and create a report of their hard disks,
including device IDs, interface type, manufacturer, model, size, and cylinder and head
configuration. Not all information will be available for all drives; some drive manufac-
turers don’t expose certain information in a way that Windows can access.
Example
This tool allows you to target one computer or multiple computers. Suppose you want
to use it to target a single remote computer named ServerA and inventory its drives to
the command-line window:
InventoryDrives.wsf /computer:ServerA
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Note that this will create a comma-separated values (CSV) file named C:\Drives.csv
containing the drive inventory for the targeted computers.
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
The /container argument will work only in the default domain of the computer run-
ning the script. In other words, the OU specified must exist within the same domain
as that of the computer running the script. If the specified OU has nested OUs, you
can include their computer accounts as well by specifying one additional argument:
Syntax
These scripts can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/output:path Saves the drive inventory to a CSV file specified in path.
You can run these scripts with the /? parameter to display the command’s syntax.
Chapter 10: File, Disk, and Volume Management 181
You can easily modify this script to display or save additional properties from the
Win32_DiskDrive class.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query.
The second possible error is that you won’t have permission to inventory the drives’
properties. This is unusual if you’re running the script as an administrator, but the
script will detect this error, display a message, and continue running.
To Learn More
■ Learn more about the Win32_DiskDrive class at http://msdn.microsoft.com/
library/default.asp?url=/library/en-us/wmisdk/wmi/win32_diskdrive.asp.
■ Find more physical disk management samples in VBScript at http://
www.microsoft.com/technet/scriptcenter/scripts/storage/disks/drives/
default.mspx.
182 Part III: Disk and File Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap10\InventoryPartitions\InventoryPartitions.wsf.
Description
Most organizations maintain documentation about the logical disk configuration
of their servers, but they rarely maintain documentation for their client computers.
Such detailed configuration information can be invaluable when troubleshooting
problems, planning upgrades, and so forth. This script can target multiple computers
and create a complete inventory of their logical disk configuration. The information
can be displayed in a command-line window for immediate use, or written to a
comma-separated values (CSV) file for reporting and archival.
Example
This script, InventoryPartitions.wsf, allows you to target one computer or multiple
computers. If you wanted to use it to target a single remote computer named ServerA
and take an inventory of its logical disks, you would use this code:
InventoryPartitions.wsf /computer:ServerA
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Note that this code will write the inventory information to a CSV file named
C:\Report.csv, which is more useful than having the code write the information to the
command-line window when you’re targeting multiple computers. Finally, you can
target an entire organizational unit of computer accounts. If your domain contains an
OU named West, you would use the following syntax:
Note that the /container argument will work only in the default domain of the com-
puter running the script. In other words, the OU specified must exist within the same
domain as that of the computer running the script. If the specified OU has nested
OUs, you can include their computer accounts as well by specifying one additional
argument:
This script always assigns ownership to your user account. Additional arguments
provide more functionality to the command; see the following section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target an
/container:name
organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached on
the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/output:path Saves the logical disk inventory to a CSV file specified in path.
You can run these scripts with the /? parameter to display the command’s syntax.
184 Part III: Disk and File Management Tasks
You can modify this script to display additional properties of the Win32_LogicalDisk
class, if desired.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to inventory the logical disks on a targeted
computer. This is unusual if you’re running the script as an administrator, but the
script will detect this error, display a message, and continue running.
To Learn More
■ Learn more about the Win32_LogicalDisk class at http://msdn.microsoft.com/
library/default.asp?url=/library/en-us/wmisdk/wmi/win32_logicaldisk.asp.
■ Find more logical disk management samples in VBScript at http://
www.microsoft.com/technet/scriptcenter/scripts/storage/disks/drives/
default.mspx.
Chapter 10: File, Disk, and Volume Management 185
Defragment Disks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap10\DefragDrives\DefragDrives.wsf.
Description
This script allows you to analyze and, if necessary, defragment the drives on multiple
computers. Regular disk defragmentation can improve computer performance,
although starting a defragmentation process on multiple computers can sometimes
be time-consuming.
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use it to target a single remote computer named ServerA and defragment all drives
which require defragmentation:
DefragDrives.wsf /computer:ServerA
Note that any drive not recommended by Windows for defragmentation will be skipped
automatically. You can add the /analyze argument to return just a fragmentation report:
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
DefragDrives.wsf /list:C:\Computers.txt
186 Part III: Disk and File Management Tasks
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
DefragDrives.wsf /container:west
Note that the /container argument will work only in the default domain of the com-
puter running the script. In other words, the OU specified must exist within the same
domain as that of the computer running the script. If the specified OU has nested
OUs, you can include their computer accounts as well by specifying one additional
argument:
This script will always skip drives that are not recommended by Windows for defrag-
mentation; there is no facility provided to force defragmentation on a drive that
doesn’t currently require it. Additional arguments provide more functionality to the
command; see the following section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/analyze Skips defragmentation on all drives and instead returns a
fragmentation report for all drives.
You can run these scripts with the /? parameter to display the command’s syntax.
Chapter 10: File, Disk, and Volume Management 187
Note that all analysis and defragmentation occurs locally on each targeted computer;
the process is simply started and monitored by the script. Very little network band-
width is required for this script to execute.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to defragment the drives. This is unusual
if you’re running the script as an administrator, but the script will detect this error,
display a message, and continue running.
It’s also possible that an error can occur during the defragmentation. The script will
attempt to handle these errors, usually displaying the error information and moving
on to the next drive or computer.
188 Part III: Disk and File Management Tasks
To Learn More
■ Learn more about the Win32_Volume class at http://msdn.microsoft.com/library/
default.asp?url=/library/en-us/wmisdk/wmi/win32_volume.asp.
■ Find more VBScript defragmentation examples at http://www.microsoft.com/
technet/scriptcenter/scripts/storage/disks/drives/default.mspx.
Chapter 10: File, Disk, and Volume Management 189
On the CD The sample script can be found on the CD that accompanies this book
at \Chap10\ScheduleDefrag\ScheduleDefrag.wsf.
Description
This script gives you the ability to create a consistent disk defragmentation schedule
for multiple computers, including client computers running Windows XP. Rather
than using VBScript or WMI to perform the defragmentation, this script uses VBScript
to create a new scheduled task in Windows Scheduled Tasks, and configures that task
to run the command-line Defrag.exe tool on a regular basis (by default, at 1:00 A.M.
UTC on the fifth day of each month).
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use it to target a single remote computer named ServerA and schedule the defragmen-
tation for volume C, you would use this code:
You can also specify the /force argument, which creates a scheduled task that always
performs the defragmentation on schedule. Without the /force argument, the scheduled
task will always analyze disk fragmentation but begin an actual defragmentation
process only when one is recommended by Windows.
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the com-
puter running the script. In other words, the OU specified must exist within the same
domain as that of the computer running the script. If the specified OU has nested OUs,
you can include their computer accounts as well by specifying one additional argument:
Additional arguments provide more functionality to the command; see the following
section titled “Syntax.”
Syntax
These scripts can be executed as command-line utilities. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target an
/container:name
organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached on
the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/volume:letter Required. Specifies the volume to defragment, identified by drive
letter.
/force Forces a defragmentation rather than analyzing and performing a
defragmentation only when recommended by Windows.
You can run these scripts with the /? parameter to display the command’s syntax.
Chapter 10: File, Disk, and Volume Management 191
The schedule is specified in the Create() method. To change the time (which is always
measured in UTC, not in local time), change the “100000” portion of the Create()
method. In other words, to configure 12:00 A.M. UTC, use “120000” instead. To
change the execution day from the fifth day, change the 16 in the Create() method to
another number: Use 1 for the 1st, 2 for the 2nd, 4 for the 3rd, 8 for the 4th, and so
forth; each successive day of the month is the next power of two.
Note that this script does not check for an existing schedule; it just creates a new
scheduled task. Targeting a computer multiple times will result in multiple identical
scheduled tasks. This can be useful if, for example, you target the C volume in one run
and the D volume in another, but it can create scheduling conflicts if you target the
same volume in multiple runs of the script.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to work with scheduled tasks on the
remote computers. This is unusual if you’re running the script as an administrator,
but the script will detect this error, display a message, and continue running.
This script provides no feedback on the defragmentation process; this script just cre-
ates the scheduled task.
192 Part III: Disk and File Management Tasks
To Learn More
■ Learn more about the Win32_ScheduledJob class at http://msdn.microsoft.com/
library/default.asp?url=/library/en-us/wmisdk/wmi/win32_scheduledjob.asp.
■ Find more VBScript scheduled task management samples at http://
www.microsoft.com/technet/scriptcenter/scripts/os/tasks/default.mspx.
Chapter 11
File Server Management
In this chapter:
List Disk Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
List Open File Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
List Disk Quotas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Enable or Disable Disk Quotas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Create Shared Folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Copy Shared Folder Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Manage Shared Folder Permissions and Removing Shared Folders . . . 215
Modify File and Folder Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Microsoft® Windows®–based file servers offer a number of useful features for almost
any environment, including shared folders and disk quotas. However, managing these
features for a number of servers can be unnecessarily time-consuming.
193
194 Part III: Disk and File Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap11\ListDiskUsagePerUser\ListDiskUsagePerUser.wsf.
Description
Any file server that has disk quotas enabled keeps track of the amount of disk space
utilized by each user. A user’s disk utilization consists of the total disk space occupied
by files that are owned by that user. This script, ListDiskUsagePerUser.wsf, lists all
disk space used by all users. This script retrieves its information from disk quotas, so
it can be used only on file servers where disk quotas have been enabled (other servers
will report no disk utilization at all). You don’t need to have disk quotas enforcing a
limit; they simply have to be enabled so that disk utilization statistics are maintained.
This script can output its information to a comma-separated values (CSV) file.
Because the script can target multiple file servers at once, the CSV output is perhaps
the most useful way to use this script. Once the CSV file is created, you can import it
into an application like Microsoft Excel and determine aggregate disk space usage
for individual users across multiple servers, create chargeback data for internal disk
utilization accounting in your organization, and so forth.
Windows will display a Quota Entries dialog box listing all current quotas. Even if a
quota limit is not enforced, Windows still tracks per-user disk utilization whenever
the quota system is enabled for a volume.
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use it to target a single remote computer named ServerA, you would use this syntax:
ListDiskUsagePerUser.wsf /computer:ServerA
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Notice that this command writes the information to a file named C:\Usage.csv.
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within
the same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3, “Working with VBScript.”
/list:path One and only one of these is required by the script. Use /list to tar-
/computer:name get a list of computers contained within a text file. Use /computer to
target a single computer. Use /container to target an organizational
/container:name
unit within Microsoft Active Directory®.
/recurse When used with /container, also targets computers contained within
nested OUs.
196 Part III: Disk and File Management Tasks
You can run this script with the /? parameter to display the command’s syntax.
In the event that a server without quotas enabled is targeted, the script will not
retrieve any instances of the Win32_DiskQuota class from that server, making it
appear in the output as if no disk space is being utilized on that server.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to view quota information. This is unusual
Chapter 11: File Server Management 197
if you’re running the script as an administrator, but the script will detect this error,
display a message, and continue running.
It’s also possible that one or more targeted servers won’t have the disk quota system
enabled. In those cases, no information will be returned, but no error should occur.
To Learn More
■ Learn more about the Win32_DiskQuota class at http://msdn.microsoft.com
/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_diskquota.asp.
■ Find more disk quota management samples in Microsoft Visual Basic® Script
(VBScript) at http://www.microsoft.com/technet/scriptcenter/scripts/storage
/quotas/default.mspx.
198 Part III: Disk and File Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap11\ShowOpenFileUsers\ShowOpenFileUsers.wsf.
Description
When maintaining a file server, it can sometimes be frustrating to try to move, open,
or delete a file, only to see an error message indicating that the file has been opened by
another user. This experience can be especially common on a busy file server because
multiple users might have the file open. Determining which users have the file open
can be difficult, but the ShowOpenFileUsers.wsf script takes care of this task by
quickly listing all users who have a particular file open through a shared folder.
Example
The script requires only two arguments: the name of the file server containing the file,
and the path of the file itself. For example:
Note that the file path must be the local path of the file because the file sits on the
server. You cannot specify a Universal Naming Convention (UNC)—for example,
\\Server1\Sales\Report.xls. Also keep in mind that the script can list only those
files that are currently held open through the Server service, meaning files that are
Chapter 11: File Server Management 199
currently opened through a shared folder. Review the information in the next
“Troubleshooting” section for more details, especially if the script doesn’t seem to be
returning the information you expect.
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/file:path Specifies the local file path of the file to check. This must start with a
local volume letter, followed by a colon and a complete local path to
the file itself. Example: C:\Shares\Sales\Report.xls. UNC paths are not
acceptable.
/server:name Specifies the name of the file server to check.
You can run this script with the /? parameter to display the command’s syntax.
Because the Server service tracks files by their local path (for example, C:\SharedFiles
\Sales\Report.xls rather than \\Server1\Sales\Report.xls), you must remember to
specify this local path in the /file argument of the script.
Troubleshooting
A number of situations can make this script appear as though it is not working
correctly. Always remember that this script can display only those files that are
currently opened through a shared folder. Files that have been opened locally on
200 Part III: Disk and File Management Tasks
the server, or through a Remote Desktop or Terminal Services session, will not be
listed by the script because those open files don’t consume resources through the
Server service (which is what this script queries). The script also will not display files
that are opened by services on the server, because those opened files aren’t consum-
ing Server service resources.
Additionally, keep in mind that some applications don’t maintain an open file connec-
tion. For example, if you open a text file in Microsoft Notepad, Notepad opens the
file, reads its contents, and then immediately closes the file. The file does not remain
open while you view or edit it in Notepad, and so this script will not report that file as
open unless you happen to run the script during the split second when Notepad is
actually reading the file’s contents.
The errors that can occur with this script are generally limited to connectivity and
permissions.
To Learn More
■ Find more file management scripts in the ScriptVault at
http://www.scriptinganswers.com.
■ Read about managing file resources through ADSI at http://
support.microsoft.com/default.aspx?scid=kb;en-us;234234.
■ Read the ADSI WinNT Provider documentation at http://msdn.microsoft.com
/library/default.asp?url=/library/en-us/adsi/adsi/adsi_winnt_provider.asp.
Chapter 11: File Server Management 201
On the CD The sample script can be found on the CD that accompanies this book
at \Chap11\QuotaReport\QuotaReport.wsf.
Description
If you’re using the disk quota support integrated into the Windows operating system,
you might from time to time want to generate a report of all existing quotas, their
current status, the amount of disk space consumed, and so forth. These reports can be
useful for both maintenance and troubleshooting purposes, but Windows does not
provide a built-in means of obtaining this information across a number of servers.
This script, QuotaReport.wsf, provides the functionality you need.
Windows will display the Quota Entries dialog box listing all current quotas. Even if
a quota limit is not enforced, Windows tracks per-user disk utilization whenever the
quota system is enabled for a volume.
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use it to target a single remote computer named ServerA, you would use this code:
QuotaReport.wsf /computer:ServerA
202 Part III: Disk and File Management Tasks
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Notice that this command writes the information to a file named C:\Usage.csv.
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within
the same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target an
/container:name
organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached on
the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/output:path Specifies the path and file name of a file to which the script will
write its information, rather than displaying that information in
the command-line window.
You can run this script with the /? parameter to display the command’s syntax.
Chapter 11: File Server Management 203
This script is similar to the earlier ListDiskUsagePerUser.wsf script, but this script
returns more information from the Win32_DiskQuota class, making it more useful
for monitoring systems in which a quota limit and warning limit have been
established.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to view quota information. This is unusual
if you’re running the script as an administrator, but the script will detect this error,
display a message, and continue running.
It’s also possible that one or more targeted servers won’t have the disk quota
system enabled. In those cases, no information will be returned, but no error
should occur.
You might occasionally see results from this script that do not match the graphical
user interface for quota management. Keep in mind that the disk quota information is
updated nearly in real time, so it is possible—probable, even, on a busy file server—for
the statistics to constantly change. As a result, running the script and then looking at
the graphical user interface might yield different results; even running the script twice
204 Part III: Disk and File Management Tasks
To Learn More
■ Learn more about the Win32_DiskQuota class at http://msdn.microsoft.com
/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_diskquota.asp.
■ Find more disk quota management samples in VBScript at http://
www.microsoft.com/technet/scriptcenter/scripts/storage/quotas/default.mspx.
Chapter 11: File Server Management 205
On the CD The sample script can be found on the CD that accompanies this book
at \Chap11\EnableDisableQuotas\EnableDisableQuotas.wsf.
Description
You might want to enable or disable the disk quota system on multiple file servers at
once. For example, you might want to temporarily enable the system so that you can
obtain a report of per-use disk utilization, and then disable the system because you
don’t plan to use it again for some time. This script, EnableDisableQuotas.wsf, pro-
vides you with the ability to quickly turn the disk quota system on or off on any num-
ber of computers at once.
Example
This tool allows you to target one computer or multiple computers. If you wanted to use
it to target a single remote computer named ServerA, you would use this syntax:
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
This example enables the quota system on the C: volume of every targeted computer.
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
This example disables the quota system on the D: volume of every targeted computer.
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within
the same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
/log:path Logs unreachable computer names to the specified file. This
file can then be used later, along with the /list argument, to
retry these computers. Note that a log is created only when
used in conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
Chapter 11: File Server Management 207
You can run this script with the /? parameter to display the command’s syntax.
You could modify this script to enable or disable quotas on all volumes—simply
remove the following text from the script:
You will still need to specify a /volume argument when running the script (further
modification would be required to remove the need for the argument), but the script
will essentially ignore the argument and enable or disable quotas on every volume on
every targeted server.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possible
error is that you won’t have permission to view quota information. This is unusual if
208 Part III: Disk and File Management Tasks
you’re running the script as an administrator, but the script will detect this error,
display a message, and continue running.
It’s also possible that one or more targeted servers won’t be able to enable the disk
quota system. If you accidentally target a Windows 2000 Server computer, for
example, an error might occur because those computers do not support WMI-based
management of disk quotas, even though they do have a disk quota system.
To Learn More
■ Learn more about the Win32_QuotaSetting class at http://msdn.microsoft.com
/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_quotasetting.asp.
■ Find more disk quota management samples in VBScript at http://
www.microsoft.com/technet/scriptcenter/scripts/storage/quotas/default.mspx.
Chapter 11: File Server Management 209
On the CD The sample script can be found on the CD that accompanies this book
at \Chap11\ShareFolder\ShareFolder.wsf.
Description
This script, ShareFolder.wsf, shares a folder on one or more computers. Although the
script can target multiple servers, that functionality is most often used when you have
multiple file servers hosting the same content (and are perhaps load-balancing or
directing content to those servers using the Distributed File System [DFS]). The script
works fine against a single computer, as well, making it easy to remotely create shared
folders.
This script creates shared folders that have the default security permissions; under
Windows Server 2003, for example, the default share permissions grant Read permis-
sion to the Everyone group.
Performing this task on remote computers, however, can be tedious and might require
the use of Remote Desktop or another remote-control technique. Performing this task
on multiple remote computers can be even more time-consuming.
210 Part III: Disk and File Management Tasks
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use it to target a single remote computer named ServerA, you would use this code:
This example shares the D:\Shares\Sales folder as Sales, with a maximum of 100
connections, the default share permissions (which is not configurable), and a descrip-
tion of “SalesDepartment”. Descriptions with spaces, for example, “Sales Depart-
ment”, must be enclosed in quotation marks.
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within
the same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
Chapter 11: File Server Management 211
You can run this script with the /? parameter to display the command’s syntax.
The script allows the operating system of the targeted computer to determine the
share permissions: Windows 2000 Server prior to Service Pack 3, for example, applies
Full Control permission to the Everyone group, whereas Windows Server 2003
applies only Read permission to the Everyone group. You can modify the share per-
missions manually, or you can use a tool such as Permcopy.exe, discussed next in this
chapter.
212 Part III: Disk and File Management Tasks
Troubleshooting
This script can run into several possible errors. It’s possible that the folder specified
might not exist, which will cause an error that the script can deal with. It’s also possible
that the share name specified might already exist. The script can usually handle this
and move on to the next targeted computer. Or, you might not have permission
to create shared folders on a targeted computer. The script will usually display an
error and continue running.
The script is not designed to target clustered file servers. Although the script can prop-
erly share a folder on a cluster node’s local storage, the script cannot create clustered
file shares. Targeting an active cluster node will result in a non-clustered share being
created; targeting an inactive node (one without access to the folder path specified)
will result in an error.
To Learn More
■ Learn more about the Win32_Share class at http://msdn.microsoft.com/library
/default.asp?url=/library/en-us/wmisdk/wmi/win32_share.asp.
Chapter 11: File Server Management 213
Description
Permcopy.exe is a Windows Server 2003 Resource Kit command-line tool that can be
used to copy shared folder permissions. It is an excellent way to automate share folder
configuration, as it provides faster operation and better consistency. For example, I
recommend maintaining a set of empty template shared folders that contain no files
but have permissions appropriate for various needs within your environment (such as
specific projects and classes of user). When a new share is created, the permissions
can easily be copied from one of these templates to the new share.
Once created, shared folder permissions can be modified from within this same
dialog box by clicking the Permissions button and assigning the desired permissions.
Example
Permcopy.exe is easy to use:
This code copies the permissions from the shared folder \\Server1\Sales to the
shared folder \\Server2\Finance. Note that there is no backslash between the server
and share names.
214 Part III: Disk and File Management Tasks
Syntax
This tool is a command-line utility. Its syntax is straightforward:
In this syntax, sourceserver is the name of the server containing sourceshare, which is
the share from which you will copy permissions; and targetserver is the destination
server containing targetshare, which is the share to which permissions will be copied.
You can run this tool with the /? parameter to display the command’s syntax.
Troubleshooting
Permcopy.exe should not be used to copy permissions to an administrative share (the
default shares created by the operating system for each attached drive, such as C$).
Doing so will generally result in a service locking up and the permissions being incor-
rectly copied. See http://www.microsoft.com/resources/documentation/WindowsServ/
2003/all/techref/en-us/Default.asp?url=/Resources/Documentation/windowsserv/
2003/all/techref/en-us/permcopy_remarks.asp for more details.
Permcopy.exe cannot create shared folders; if the specified source or target share does
not exist, an error will occur.
To Learn More
■ Learn more about the Permcopy.exe tool syntax at http://www.microsoft.com
/resources/documentation/WindowsServ/2003/all/techref/en-us/Default.asp?url=
/Resources/Documentation/windowsserv/2003/all/techref/en-us
/permcopy_syntax.asp.
■ Read more about copying files, shares, and permissions at http://www.microsoft
.com/windowsserver2003/upgrading/nt4/tooldocs/msfsc.mspx, which discusses
the Microsoft File Server Migration Toolkit.
Chapter 11: File Server Management 215
Description
Rmtshare.exe was originally a part of the Microsoft Windows NT 4.0 Resource Kit;
since then, Microsoft has released the tool into the public domain and made it avail-
able for download from their Internet FTP site. The tool works with current versions
of Windows, and provides the ability to list share permissions, change share permis-
sions, and perform other tasks with shares located on remote servers.
Once created, shared folder permissions can be modified from within this same
dialog box by clicking the Permissions button and assigning the desired permissions.
Example
This tool is a command-line utility, and it has many functions. To display all shares on
a remote server, you would use this code:
RMTSHARE \\server
216 Part III: Disk and File Management Tasks
RMTSHARE \\server\sharename
Options include:
/USERS:number
/UNLIMITED
/REMARK:"text"
/GRANT user:perm
/REMOVE user
For example, to create a share named \\Server1\MyShare, for the folder C:\MyFolder,
with unlimited connections and Read permissions for the Everyone group, you would
use this code:
To edit an existing share, specify the share and any of the preceding options to modify
permissions or change the share’s connections:
To remove a shared folder (but not the underlying files and folders):
Syntax
Rmtshare.exe has a fairly straightforward syntax.
/GRANT user:perm Adds a user or group to the share’s access control list, along
with the specified permission (Read, Full Control, or Write).
/REMOVE user Removes a user or group (and their permissions) from the
share’s access control list.
/DELETE When used with an existing share, removes the share.
You can run this tool with the /? parameter to display the command’s syntax.
Rmtshare.exe can be scripted, in the form of batch files, to affect multiple computers
at once. However, share details are rarely applied identically to multiple computers,
and so you will most likely use Rmtshare.exe as a convenient tool for managing shares
on remote computers.
Troubleshooting
Having sufficient permissions to manage remote shares is, of course, required
when using Rmtshare.exe. Other than permissions or potential connectivity issues,
Rmtshare.exe will rarely encounter problems.
One trick with the tool is that long file paths must be enclosed in double quotation
marks. For example:
Failure to do so will result in Rmtshare.exe trying to share C:\Program (which will fail
if the folder doesn’t exist) and treating Files as a separate argument, which will cause
an error.
To Learn More
■ Read about Share.vbs, an alternative means of managing remote shared folders
(although not their permissions), at http://www.microsoft.com/Resources
/documentation/SBS/2000/all/reskit/en-us/sbrkapxf.mspx.
■ Read more about Rmtshare.exe at http://www.jsiinc.com/SUBM/tip6300
/rh6353.htm.
218 Part III: Disk and File Management Tasks
Description
Managing file and folder permissions can be complicated, especially when you need
to modify permissions on a large number of files and folders at once. Microsoft
provides the Xcacls.exe tool, which can be used to automate permissions changes.
Another tool, Cacls.exe, is included with all recent versions of Windows. However,
Cacls.exe provides less flexibility and cannot apply the full set of permissions
available through the graphical user interface. Xcacls.exe is more flexible and can
work with the entire set of possible permissions.
Example
At its most basic, Xcacls.exe can be used to completely replace the access control list
(ACL) on a file or folder (or on a set of files and folders). This removes all previous
permissions and replaces them with whatever you specify, so it is critical that you
specify the correct permissions. It is entirely possible to lock yourself out of files and
folders by having Xcacls.exe replace the existing permissions with ones that do not
include your user account or groups. For example:
This will replace the permissions on all files in the current folder, granting the admin-
istrator read/write permissions. The /y argument suppresses a confirmation prompt
that reminds you that you are replacing all effective permissions on the files.
Chapter 11: File Server Management 219
Xcalcs.exe has a more powerful mode in which it edits the existing ACL rather than
replacing it entirely:
This modifies the ACL of all files in the current folder, granting the TestUser account
read, write, execute, and delete permissions on new files, as well as read and write per-
missions on any existing files, without modifying any other permissions that are
already in the ACL.
Syntax
Xcacls.exe has a somewhat complex syntax, which fits with the tool’s flexibility.
Folder or file Required. If used with no other options, lists the existing ACL.
/t Applies changes to the current folder and all subfolders, includ-
ing all files contained therein.
/e Edits, rather than replaces, the existing ACL.
/x Edits, rather than replaces, the existing ACL, and edits only ACL
entries corresponding to the specified user or group.
/c Continues processing (that is, it skips the denied file) if access is
denied to a specified file or folder.
/g User:Perm;Spec Grants a permission. User is the user or group to grant permis-
sion to. In the case of a file, only Perm is necessary. In the case of
a folder, Perm specifies file inheritance for the folder.
/r User Removes the specified user or group from the ACL.
/p User:Perm;Spec Replaces the access rights for the specified user or group. Perm
and Spec work the same as they do for the /g argument.
/d User Denies the specified user access to the file or folder.
/y Suppresses the warning confirmation normally displayed when
replacing permissions.
You can run this tool with the /? parameter to display the command’s syntax.
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)
220 Part III: Disk and File Management Tasks
Troubleshooting
Having sufficient permissions to manage file and folder security is, of course, required
when using Xcalcs.exe. If the tool encounters an error, it will stop processing further
files and folders unless you specify the /c argument. Other than permissions issues,
Xcacls.exe will rarely encounter problems.
To Learn More
■ Read the official documentation on Xcacls.exe at http://www.microsoft.com
/resources/documentation/WindowsServ/2003/all/techref/en-us/Default.asp?url=
/Resources/Documentation/windowsserv/2003/all/techref/en-us/xcacls_syntax.asp.
■ Read the documentation on Cacls.exe, a somewhat easier version of Xcacls.exe
that is included with the Windows operating system, at http://www.microsoft
.com/resources/documentation/WindowsServ/2003/standard/proddocs/en-us
/Default.asp?url=/resources/documentation/WindowsServ/2003/standard/proddocs
/en-us/cacls.asp.
Part IV
Security and Network
Management Tasks
Chapter 12
General Network and Server
Management Tasks
In this chapter:
List FSMO Role Holders. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Create DHCP Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Modify DHCP Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Create DNS Host Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Create Print Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Network management tasks aren’t always the ones you need to perform on multiple
computers, but they are often the ones you need to perform frequently or in a hurry
(perhaps while troubleshooting a problem), or with great accuracy. Automation can
help make information available quickly in time of need, can perform configuration
changes with great accuracy, and can make frequently performed tasks less tedious.
223
224 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap12\ListFSMOs\ListFSMOs.wsf.
Description
Microsoft Active Directory® defines five Flexible Single Master Operations (FSMO)
roles, which provide specialized services for various domain and forest functions.
Each FSMO role is initially held by the first domain controller in the first forest you
create; you can manually reassign these roles to other domain controllers. When trou-
bleshooting domain problems, it can be useful to know which domain controllers
hold which FSMO roles. For example, the Schema Master role is required to make
changes to the Active Directory schema; if you are attempting to make changes to the
schema and having problems, figuring out which domain controller holds the Schema
Master role is a good first troubleshooting step. If, for example, that domain controller
is unavailable or unreachable, you’ll know why you’re having problems.
■ To view the current Schema Master by using the Active Directory Schema
console, with the console open, right-click Active Directory Schema and select
Operations Master.
■ To view the current Domain Naming Master by using the Active Directory
Domains and Trusts console, with the console open, right-click Active
Directory Domains And Trusts and select Operations Master.
Chapter 12: General Network and Server Management Tasks 225
■ To view all other FSMO roles by using the Active Directory Users and
Computers console, with the console open, right-click Active Directory
Users And Computers, point to All Tasks, and then select Operations Master.
Note that you can also manually change the role holder for each FSMO role using the
preceding steps. After selecting Operations Master, you’ll see the current role holder
and a Change button, which allows you to select a new role holder.
Example
This script requires no command-line arguments. Simply run it:
ListFSMOs.wsf
The script will work for only the default domain of the computer on which the script
is run, displaying the domain and forestwide roles for that default domain. This
script will not work when run from a computer that is not a member of a domain.
Syntax
This script has no command-line arguments. Set CScript.exe to be your default script
processor, as described in Chapter 3, “Working with VBScript.” You can run this
script by using the /? parameter to display the command’s syntax.
The first line of code connects to the domain; the last five lines of code query the
Schema Master role holder name and display that information on the command line.
The script repeats this process to obtain the other four FSMO role holder names.
Troubleshooting
The most common problem with this script is its inability to connect to the domain,
which usually occurs only on a computer that is not a member of a domain at all. On
a domain member computer, this script rarely has a problem; even if it is unable to
connect to the computer’s preferred domain controller, it will automatically attempt to
contact another domain controller to obtain the FSMO information.
To Learn More
■ Learn more about the FSMO roles and how to manually view their holders
and transfer holders at http://support.microsoft.com/default.aspx?
kbid=324801&product=winsvr2003.
■ Read more about the FSMO roles and their function within Active Directory by
referring to the Windows Server 2003 Help and Support Center.
Chapter 12: General Network and Server Management Tasks 227
On the CD The sample script can be found on the CD that accompanies this book
at \Chap12\CreateDHCPScopes\CreateDHCPScopes.wsf.
Description
The Dynamic Host Configuration Protocol (DHCP) server included with Microsoft
Windows Server 2003 is designed to support one or more scopes, which are ranges of
IP addresses, from which addresses are issued to DHCP clients. Creating new scopes
is typically performed through the DHCP Server console, a graphical administrative
tool. However, using the console to configure a new server with a large number of
scopes can be time-consuming and error-prone. Windows Server 2003 provides a
scriptable command-line tool, Netsh, that can be used to create new scopes from the
command line. However, this tool can be complex and difficult to use manually. The
CreateDHCPScopes.wsf script automates the Netsh tool, enabling easier bulk creation
of multiple DHCP scopes.
You can also use the Netsh command to manually configure a new scope. For exam-
ple, the following will create a new scope named MyScope for the 192.168.1.0/24
subnet, on a DHCP server at 192.168.12.2:
Additional steps are required to add an IP address range and any scope options to the
newly created scope.
228 Part IV: Security and Network Management Tasks
Example
This script can be executed as follows:
The script assumes a 24-bit subnet mask and assumes that the router for this subnet
is at the .1 host address. It assigns an IP address range from .10 through .254 for use
by DHCP clients. The new scope has the following properties:
The scope is created on a DHCP server at address 192.168.12.2. After creating the
scope, adding the IP address range, and specifying the router scope option, the script
activates the scope.
Syntax
This script has several command-line arguments, which are described in the following
table. Set CScript.exe to be your default script processor, as explained in Chapter 3.
/server:address Specifies the name or IP address of the DHCP server. This must be a
Windows Server 2003 server running the Windows DHCP Service.
/scope:address Specifies the subnet address for the new scope. This must be only
three octets. For example, to create a scope for 192.168.5.0/24,
specify /scope:192.168.5.
/name:string Specifies the name of the new scope.
You can run this script by using the /? parameter to display the script’s syntax.
Dim sCmd
sCmd = "netsh dhcp server " & WScript.Arguments.Named("server") & _
" add scope " & WScript.Arguments.Named("scope") & ".0 255.255.255.0 " & _
WScript.Arguments.Named("name") & " ScriptedScope"
GoRun sCmd
Chapter 12: General Network and Server Management Tasks 229
'activate scope
sCmd = "netsh dhcp server " & WScript.Arguments.Named("server") & _
" scope " & WScript.Arguments.Named("name") & _
" set state active"
GoRun sCmd
You can make changes to some of the script’s code so that you can change some of the
script’s basic operations. At the beginning of the script, the following code specifies
how the new scope will be created:
sStart = "10"
sFinish = "254"
sRouter = "1"
Change sStart from 10 and sFinish from 254 to other values to change the IP address
range included in the scope. For example, to have the script always create scopes with
IP address ranges from .12 through .100, change sStart to 12 and sFinish to 100. If your
routers are typically configured to use a .2 host address, change sRouter to 2, and each
new scope’s router option will use the .2 host address.
Troubleshooting
Because the Netsh command is not a scriptable COM object, it can’t provide detailed
feedback when a command fails. For this reason, troubleshooting this script can be
difficult. Thus, you need to ensure that you have sufficient permissions to create
scopes on the targeted DHCP server and that you provide acceptable values for the
script’s arguments. The script runs the Netsh command four times to create the scope,
add the IP address range, create the router option, and activate the scope; each time,
the Netsh command output will appear in a command-line window, where you might
also be prompted for user credentials if necessary.
230 Part IV: Security and Network Management Tasks
To Learn More
■ Learn more about using the Netsh command to create DHCP scopes at
http://www.microsoft.com/resources/documentation/WindowsServ/2003
/standard/proddocs/en-us/Default.asp?url=/resources/documentation
/WindowsServ/2003/standard/proddocs/en-us/netsh_dhcp_example.asp.
■ Read more about Windows Server 2003 DHCP Server at http://
www.microsoft.com/technet/prodtechnol/windowsserver2003/serverroles
/dhcpserver/default.mspx.
Chapter 12: General Network and Server Management Tasks 231
Description
Windows DHCP servers support a number of server and scope options. These
options are used to pass IP configuration information to DHCP clients. Specifically,
server options are passed to all DHCP clients obtaining an address from the server,
whereas scope options are passed only to clients obtaining an address for the associ-
ated scope. Thus, the options passed to a client are all options for that client’s issuing
scope and all server options.
Example
The Netsh command-line tool provides a means to modify DHCP server and scope
options from the command line. By using the tool in a batch file, you can automate the
process of changing multiple scopes or servers simultaneously.
Where:
■ A.a.a.a is the IP address of the DHCP server; alternately, you might specify
\\servername to use the server’s name.
■ Xxx is the number option code you want to change.
■ Datatype is the type of data contained within the option. This might be BYTE,
WORD, DWORD, STRING, or IPADDRESS. IPADDRESS is perhaps the most
common.
■ Data is the actual data to be assigned to the option, such as an IP address.
Netsh dhcp server a.a.a.a scope scope set optionvalue xxx datatype data
For example, to set the Router option (whose option code is 003) to 192.168.1.1 for a
scope 192.168.1.0 on the DHCP server at 192.168.12.2, you would run this code:
Note that not all DHCP clients support all the preceding options, but they can all be
assigned to the DHCP server for those clients that do support them.
Turning the Netsh command into an automation tool is simple—just create a new text
file with a .bat file name extension. If, for example, you need to change the DNS server
option to 192.168.7.54 on three servers, the .bat file would contain the following:
Tip Using the Copy and Paste features in Microsoft Notepad makes it easier to
duplicate this line three times and reduces the chance you will introduce a typo when
manually creating the second and third lines.
Saving and double-clicking the .bat file will make your change on all three servers.
Syntax
Server address Specifies the name or IP address of the DHCP server. This
must be a Windows Server 2003 server running the Windows
DHCP Service. When specifying a name, use the format
\\servername.
Scope scope Specifies the scope when changing a scope option.
Optionvalue code Specifies the option code for the option you want to change
type value or set, the type (DWORD, WORD, STRING, IPADDRESS, or
BYTE), and the value to change (or set) the option to.
Troubleshooting
Netsh provides excellent feedback when errors occur, and the most common errors
are syntax-related. Before creating a .bat file containing multiple Netsh commands,
take a moment to test a sample command against a nonproduction DHCP server to
verify the command’s accuracy and operation; then create your .bat file based on that
tested command.
To Learn More
■ Learn more about Netsh scripting at http://www.brienposey.com/kb
/netsh_scripting.asp.
■ Read more about DHCP-specific uses of Netsh at http://www.microsoft.com
/resources/documentation/windows/xp/all/proddocs/en-us/netsh_dhcp.mspx.
■ Read the complete list of industry-standard DHCP options at http://
www.iana.org/assignments/bootp-dhcp-parameters.
234 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap12\CreateARecords\CreateARecords.wsf.
Description
Although most Windows-based environments utilize Dynamic DNS (DDNS) to regis-
ter host records, many environments still require the use of static host records in DNS
for computers and devices that are not DDNS-capable (such as legacy devices and
many non-Microsoft operating systems). This script, CreateARecords.wsf, automates
the process of creating host records for both IP and IPv6 addresses (stored in DNS A
and AAAA records, respectively).
Manual record creation is also necessary on systems where DDNS has been disabled.
DDNS is often disabled on DNS servers that connect to the Internet, because having
DDNS enabled presents a potential security risk. This script is also useful for these sit-
uations and does not require DDNS to be enabled.
Note This script functions only with the Windows Server 2003 DNS Service. It can
also work with the Microsoft Windows 2000 Server DNS Service, provided the DNS
server has the Windows Management Instrumentation (WMI) provider installed.
See the “Learn More” links at the end of this section for more information about this
provider and its installation procedures.
Example
This script is designed to read host names and addresses from a text file in which the
host name, IP address, and IPv6 address (optional) are separated by commas. A
sample text file might look like this:
Server1,192.168.0.12,3ffe:ffff:0100:f101:0210:a4ff:fee3:9566
Server2,192.168.7.43,3ffe:ffff:100:f101:210:a4ff:fee3:9566
Server3,192.168.7.216,3ffe:ffff:100:f101::1
As shown in the preceding text file example, both full and abbreviated IPv6 addresses
are acceptable. The file does not contain a header row. If you don’t want to specify
IPv6 addresses, omit that information.
Note When specifying IPv6 addresses, you typically provide the address that any
client can use to reach the server. Link-local addresses are not usually registered with
DNS, for example, because they are valid only on the computer’s local subnet. Private
addresses (typically routable within an intranet) and global addresses (which are
routable on the Internet) are suitable for DNS registration.
Running the script requires you to specify the text file path and name, as well as the
DNS server name (or address) and whether you want IPv6 records created:
You must also specify the domain in which the records will be created, and the DNS
server specified must host a writable (primary) copy of that domain’s zone. Note that
specifying the /ipv6 argument will cause errors if the input file does not contain IP
and IPv6 addresses for each host.
Syntax
This script has several command-line arguments, which are listed in the following
table. Set CScript.exe to be your default script processor, as described in Chapter 3.
You can run this script with the /? parameter to display the script’s syntax.
236 Part IV: Security and Network Management Tasks
Do Until oTS.AtEndOfStream
sData = Split(oTS.ReadLine,",")
sName = sData(0)
sAddress = sData(1)
'Create A records
Set oItem = oWMIService.Get("MicrosoftDNS_AType")
WScript.Echo " Creating A record for " & sName
errResult = oItem.CreateInstanceFromPropertyData (sDNSServer, sDomain, sName, 1,
600, sAddress)
If errResult <> 0 Then
WScript.Echo " ** Error: " & Err.Description
End If
Loop
The variable oWMIService is set to an instance of the DNS server’s WMI service, which
provides the interface for querying and creating DNS records. The WMI namespace
used, root\MicrosoftDNS, is available only when the DNS WMI provider is installed
(which is always the case on computers running Windows Server 2003 and the
Microsoft DNS service).
Troubleshooting
Several things can go wrong with this script, although the most common problem
concerns permissions. The user account running the script must have permission to
create new DNS records on the DNS server specified.
Other problems generally come from the DNS server itself. For example, the DNS
server might not allow a record to be created if an existing record with the same name
exists; the outcome depends on how the permissions on that record are configured.
The DNS server might also be configured to disallow certain record types (unlikely
with A records but more likely with AAAA records, which are less commonly used).
In all cases, the script will display an error message if the DNS server returns one.
Chapter 12: General Network and Server Management Tasks 237
Other errors usually result from improperly formatted input files. Always check to
make sure your input file’s format matches the example shown earlier and that the
first line of the file contains a host name and an IP address, and not a header row.
To Learn More
■ Learn more about the DNS WMI provider at http://msdn.microsoft.com/library
/default.asp?url=/library/en-us/dns/dns/dns_wmi_provider_overview.asp.
■ Get DNS WMI scripting examples from http://msdn.microsoft.com/library
/default.asp?url=/library/en-us/dns/dns/dns_wmi_provider_scripting_
examples.asp.
■ Download and install the DNS WMI provider from http://msdn.microsoft.com
/library/default.asp?url=/library/en-us/dns/dns/installing_the_provider.asp (for
Windows 2000 Server only; the provider is preinstalled on Windows Server 2003).
■ Learn more about IPv6 at http://www.ipv6.org/.
238 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap12\CreatePrintQueues\CreatePrintQueues.wsf.
Description
This script, CreatePrintQueues.wsf, is used to create multiple print queues. (A print
queue is referred to as a printer in Microsoft Windows terminology. The physical hard-
ware is referred to as a print device.) Because an administrator rarely needs to create
the same kind of print queue on multiple computers, this script is designed to create
multiple printers on a single computer. This can be useful for restoring a print server
that contains multiple queues, or for migrating a print server’s queues to a new server.
Example
This script provides two basic modes of operation. The first mode reads the existing
printers on a server and writes their information into a text file. The second mode
reads a text file—such as the kind created by the first mode—and creates printers based
on the data contained within the file.
This code will connect to a server named Server1 and write its printer information to
a file named Printers.csv. This file is a comma-separated values (CSV) file formatted as
follows:
DriverName,PortName,DeviceID,Location,Network,Shared,ShareName
The second mode of the script reads a CSV file formatted in that fashion and creates
printers:
Keep in mind that this script does not install printer drivers; it simply creates queues
that reference those drivers. For example, the script is capable of creating a queue for
a Brand X print device, but it cannot install the Brand X device drivers. All device
drivers needed to create the queues listed in the input file must be installed before
running the script.
Syntax
This script has several command-line arguments, which are listed in the following
table. Set CScript.exe to be your default script processor, as described in Chapter 3.
You can run this script with the /? parameter to display the script’s syntax.
This is a simple WMI query for all available instances of the Win32_Printer class.
Using the script’s /input argument runs the following code, which reads information
from a file and creates new printers by spawning instances of the Win32_Printer class:
sData = ots.ReadLine
sData=Split(sData,",")
Set oPrinter = oWMI.Get("Win32_Printer").SpawnInstance_
oPrinter.DriverName = sData(0)
oPrinter.PortName = sData(1)
oPrinter.DeviceID = sData(2)
oPrinter.Location = sData(3)
oPrinter.Network = sData(4)
oPrinter.Shared = sData(5)
oPrinter.ShareName = sData(6)
oPrinter.Put_
If Err <> 0 Then
WScript.Echo "** Error creating " & sData(0)
WScript.Echo Err.Description
End If
The script expects the data in the input file to be within acceptable ranges and prop-
erly formatted. Use the /output switch to generate a sample file if you plan to manually
create your own input files.
This script works best with networked printers that are accessed via TCP/IP printing
(also called LPD/LPR or IP printing). Other types of printers might require local
printer port configurations, which the script cannot automatically create.
Troubleshooting
To run this script, you must have permission to create new printers on the targeted
server. The script will not be able to create all printer types. Those using specialized
ports, those using drivers that are not installed, and some printers utilizing USB con-
nectivity will often cause errors. You can edit the file produced with the /output argu-
ment to remove any printers that you do not want created or that are causing problems.
If a printer cannot be created, the script will try to obtain and display error information.
Removing the printer from the input file will prevent the error from recurring.
To Learn More
■ Find more Microsoft Visual Basic® Script (VBScript) samples that deal with
printers and print queues at http://www.microsoft.com/technet/scriptcenter
/scripts/printing/servers/default.mspx.
Chapter 13
Security Management Tasks
In this chapter:
Archive and Clear Security Logs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Back Up Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
Restore Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
Back Up a CA or the CA Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
Restore a CA or the CA Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Publish a CRL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Request Renewal CA Certificate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Many of the chapters in this book address security-related management tasks, and
this chapter will bring together many tasks that are specific to security, including
security log management and Public Key Infrastructure (PKI) management. For the
PKI tasks in particular, I’ll tend to direct you to existing command-line tools rather
than providing scripts. That’s because you typically perform PKI tasks on a single
computer rather than on multiple computers, although you might want to schedule
the tasks to run repetitively—functionality that command-line tools excel at.
In addition, the PKI-related tasks that you would want to perform on multiple com-
puters usually need to be performed for the primary user of those computers, which
often means working with the users’ profiles. This is difficult to do remotely because
by default remote scripts work with the profile of the person running the script, not
with the profile of the remote computer’s primary user. Command-line tools can be
easily added to logon scripts, which makes easier the automation of tasks that deal
with individual user profiles.
241
242 Part IV: Security and Network Management Tasks
On the CD The sample script for this task can be found on the CD that accompa-
nies this book at \Chap13\ArchiveLogs\ArchiveLogs.wsf.
Description
The Security event log in Windows contains detailed information about auditing
events (if you enabled auditing) and other security-related system events. Many orga-
nizations have policies that require security logs to be archived for a period of time as
an audit trail; some organizations might even be required by law or industry practices
to retain this information. This script, ArchiveLogs.wsf, is designed to create an
archive of the security logs. When archiving a log, the script also clears it, making
room for new events.
Example
This tool allows you to target one computer or multiple computers. If you wanted to
use it to target a single remote computer named ServerA, you would use this code:
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within
the same domain of the computer running the script. If the specified OU has nested
OUs, you can include their computer accounts as well by specifying one additional
argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3, “Working with VBScript.”
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Microsoft Active Directory®.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/path:path Specifies the path where the archive files will be saved. The script
will create a subfolder for each targeted computer and will name
individual files with the current date. The path specified must
already exist.
You can run this script with the /? parameter to display the command’s syntax.
Chapter 13: Security Management Tasks 245
Note that the script specifically requests both Security and Backup permissions; both
are required to archive and clear the Security event log. If the user account used to run
the script can’t obtain these permissions, the script will return an error.
Note that the archived files are given the current date as determined by the computer
on which the script is run; if you are archiving logs from computers located in differ-
ent time zones, the log file names might not precisely match the events contained
within the logs. Consider the file name to be just an indicator of when the log archive
was created; it has no relation to the events within the file.
246 Part IV: Security and Network Management Tasks
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to view or clear the security log. This error
is unusual if you’re running the script as an administrator, but the script will detect
this error, display a message, and continue running.
The script is not designed to be run more than once per day. Each archived security
log is given the current date as its file name, such as 1-1-2005.evt. If the script is run
twice in one day and used to target the same computer each time, the script will be
successful the first time but will return an error the second time. This is the intended
functionality so that it avoids overwriting any existing log files.
To Learn More
■ Find more event log management samples in Microsoft Visual Basic® Script
(VBScript) at http://www.microsoft.com/technet/scriptcenter/scripts/logs
/eventlog/default.mspx.
Chapter 13: Security Management Tasks 247
Back Up Keys
Note This script is included with Windows Server 2003 when Certificate Services is
installed.
Description
Essentially, the certificate (and associated public and private keys) for a Certificate
Authority (CA) is its license to issue keys to users, computers, and other entities.
Without the keys contained in its CA certificate, a CA is useless. If those keys become
damaged or lost, every certificate ever issued by the CA becomes useless. It’s therefore
an excellent idea to create reliable backups of CA certificates (and to test those back-
ups). The certificates don’t change, so this isn’t a task you need to perform frequently.
Example
The Certutil.exe command-line utility provides a scriptable means of backing up the
certificates for multiple CAs, making it easier to get a complete set of backups for an
entire PKI. The basic use of the command-line tool is as follows:
Replace server\caname with the name of the server and CA to back up; replace path
with the location for the backup files to be written. This command can be added to a
batch file to target multiple computers simply by listing the command multiple times
and changing each instance to target a different server\caname. Note that the password
argument is the password that will be used to protect the backed-up keys. If you
include this command in a batch file, be sure to remove the password after running
the script so that the password cannot be discovered by reading the batch file.
248 Part IV: Security and Network Management Tasks
Syntax
This command has many command-line arguments. The most common are described
in the following table.
You can run this script with the /? parameter to display the script’s syntax.
The backup operation of Certutil.exe produces a PKCS #12 (.pfx) file, which is
an industry-standard file format for storing certificates. For maximum safety,
these files should be written to permanent backup media (such as a backup tape,
a CD-R, or other media) for archiving, and the physical media should be stored
in a safe and secured location such as a locked fire safe or secure off-site storage
location.
Chapter 13: Security Management Tasks 249
Troubleshooting
Certutil.exe assumes that the user account used to run the tool has permission to per-
form the desired operations within Certificate Services. Because Certificate Services
represents such a critical portion of an organization’s security, it is often secured in
such a way that normal administrative accounts—such as the Domain Admins group—
don’t have administrative access. Instead, administrative access to the PKI is granted
to another group, often reducing the number of individual users who have control
over the PKI. Be sure you are running Certutil.exe using an appropriate user account.
If necessary, execute the tool by using the Runas command to provide alternative user
credentials.
To Learn More
■ Learn more about using the Certutil command at http://www.microsoft.com
/resources/documentation/WindowsServ/2003/standard/proddocs/en-us
/Default.asp?url=/resources/documentation/WindowsServ/2003/standard
/proddocs/en-us/sag_CS_CertUtil2.asp.
■ Read more about Certificate Services at http://www.microsoft.com/resources
/documentation/WindowsServ/2003/all/techref/en-us/Default.asp?url=
/Resources/Documentation/windowsserv/2003/all/techref/en-us
/w2k3tr_crtsv_what.asp.
250 Part IV: Security and Network Management Tasks
Restore Keys
Note The script is included with Windows Server 2003 when Certificate Services is
installed.
Description
The certificate (and associated public and private keys) for a Certificate Authority
(CA) is essentially its license to issue keys to users, computers, and other entities.
Without the keys contained in its CA certificate, a CA is useless. If those keys become
damaged or lost, every certificate ever issued by the CA becomes useless. Provided
you have a backup of the CA’s certificate, you can restore that backup to restore a CA
to functionality and prevent the keys it has issued from becoming useless.
Example
The Certutil.exe command-line utility provides a scriptable means of restoring the cer-
tificates for multiple CAs, making it easier to restore a complete set of backups for an
entire PKI. You generally need to restore only a single CA at a given time, but during
disaster recovery scenarios you might need to restore multiple CAs (for example, if
you are performing disaster recovery at an off-site facility). Having a scriptable means
of performing the restore will allow your CAs to be up and running more quickly. The
basic use of the command-line tool is as follows:
Replace server\caname with the name of the server and CA to back up; replace path
with the location of the backup file (a .pfx file). This command can be added to a
batch file to target multiple computers by listing the command multiple times and
changing each instance to target a different server\caname. Note that the password
argument is the password that will be used to open the backed-up keys; if you include
Chapter 13: Security Management Tasks 251
this command in a batch file, be sure to remove the password after running the script
so that the password cannot be discovered by reading the batch file.
Syntax
This command has several command-line arguments, as listed in the following table.
You can run this script with the /? parameter to display the script’s syntax.
Certutil.exe uses remote procedure calls (RPCs) to connect to CAs and restore certifi-
cates. Be sure that the CAs you target are reachable on RPC ports (a broad range of
ports, making it difficult to perform this task across a firewall).
Troubleshooting
Certutil.exe assumes that the user account used to run the tool has permission to per-
form the desired operations within Certificate Services. Because Certificate Services
represents such a critical portion of an organization’s security, it is often secured in
such a way that normal administrative accounts—such as the Domain Admins group—
don’t have administrative access. Instead, administrative access to the PKI is granted
to another group, often reducing the number of individual users who have control
over the PKI. Be sure you are running Certutil.exe by using an appropriate user
account; if necessary, execute the tool by using the Runas command to provide
alternative user credentials.
252 Part IV: Security and Network Management Tasks
To Learn More
■ Learn more about using the Certutil command at http://www.microsoft.com
/resources/documentation/WindowsServ/2003/standard/proddocs/en-us
/Default.asp?url=/resources/documentation/WindowsServ/2003/standard
/proddocs/en-us/sag_CS_CertUtil2.asp.
■ Read more about Certificate Services at http://www.microsoft.com/resources
/documentation/WindowsServ/2003/all/techref/en-us/Default.asp?url=
/Resources/Documentation/windowsserv/2003/all/techref/en-us
/w2k3tr_crtsv_what.asp.
Chapter 13: Security Management Tasks 253
Note This script is included with Windows Server 2003 when Certificate Services is
installed.
Description
The database used by Certificate Services contains configuration information, issued
keys, and other critical data. Routinely backing this information up will help protect
against a loss of data should the CA become damaged or corrupted. Backups can also
be used to restore the CA to operation after a disaster, such as at an off-site disaster
recovery facility.
Example
The Certutil.exe command-line utility provides a scriptable means of backing up the
certificates for multiple CAs, making it easier to get a complete set of backups for an
entire PKI. The basic use of the command-line tool is as follows:
Replace server\caname with the name of the server and CA to back up; replace path
with the location for the backup files to be written. This command can be added to a
batch file to target multiple computers by listing the command multiple times and
changing each instance to target a different server\caname. Note that the password
argument is the password that will be used to protect the backed-up keys; if you
include this command in a batch file, be sure to remove the password after running
the script so that the password cannot be discovered by reading the batch file.
254 Part IV: Security and Network Management Tasks
Specifying –backup rather than –backupdb will perform a more lengthy backup that
includes the database, the CAs keys, and other components—essentially a complete
backup of the entire CA.
Syntax
This command has several command-line arguments, as listed in the following table.
You can run this script with the /? parameter to display the script’s syntax.
Troubleshooting
Certutil.exe assumes that the user account used to run the tool has permission to per-
form the desired operations within Certificate Services. Because Certificate Services
represents such a critical portion of an organization’s security, it is often secured in
Chapter 13: Security Management Tasks 255
such a way that normal administrative accounts—such as the Domain Admins group—
don’t have administrative access. Instead, administrative access to the PKI is granted
to another group, often reducing the number of individual users who have control
over the PKI. Be sure you are running Certutil.exe using appropriate user account; if
necessary, execute the tool by using the Runas command to provide alternative user
credentials.
To Learn More
■ Learn more about using the Certutil command at http://www.microsoft.com
/resources/documentation/WindowsServ/2003/standard/proddocs/en-us
/Default.asp?url=/resources/documentation/WindowsServ/2003/standard
/proddocs/en-us/sag_CS_CertUtil2.asp.
■ Read more about Certificate Services at http://www.microsoft.com/resources
/documentation/WindowsServ/2003/all/techref/en-us/Default.asp?url=
/Resources/Documentation/windowsserv/2003/all/techref/en-us
/w2k3tr_crtsv_what.asp.
256 Part IV: Security and Network Management Tasks
Note This script is included with Windows Server 2003 when Certificate Services is
installed.
Description
Restoring a CA database (or, if necessary, the entire CA, including keys) provides a
means for returning a nonfunctional CA to service without losing any information.
This task is especially useful in disaster recovery scenarios, and because the
Certutil.exe tool is scriptable, you can more easily restore multiple CAs in a short
period of time—a good technique to use when, for example, you are bringing your
business back online at an off-site disaster recovery facility.
Example
The Certutil.exe command-line utility provides a scriptable means of backing up the
certificates for multiple CAs, making it easier to restore multiple CAs at one time. The
basic use of the command-line tool is as follows:
Replace server\caname with the name of the server and CA to restore; replace path
with the location of the backup files. Note that you might need to stop the Certificate
Service service to perform any restore of the database. This command can be added to
a batch file to target multiple computers by listing the command multiple times and
changing each instance to target a different server\caname. Note that the password
Chapter 13: Security Management Tasks 257
argument is the password that will be used to protect the backed-up keys. If you
include this command in a batch file, be sure to remove the password after running
the script so that the password cannot be discovered by reading the batch file.
Syntax
This command has several command-line arguments, as listed in the following table.
You can run this script with the /? parameter to display the script’s syntax.
Troubleshooting
Certutil.exe assumes that the user account used to run the tool has permission to per-
form the desired operations within Certificate Services. Because Certificate Services
represents such a critical portion of an organization’s security, it is often secured in
such a way that normal administrative accounts—such as the Domain Admins group—
don’t have administrative access. Instead, administrative access to the PKI is granted
to another group, often reducing the number of individual users who have control
258 Part IV: Security and Network Management Tasks
over the PKI. Be sure you are running Certutil.exe using an appropriate user account;
if necessary, execute the tool by using the Runas command to provide alternative user
credentials.
To Learn More
■ Learn more about using the Certutil command at http://www.microsoft.com
/resources/documentation/WindowsServ/2003/standard/proddocs/en-us
/Default.asp?url=/resources/documentation/WindowsServ/2003/standard
/proddocs/en-us/sag_CS_CertUtil2.asp.
■ Read more about Certificate Services at http://www.microsoft.com/resources
/documentation/WindowsServ/2003/all/techref/en-us/Default.asp?url=
/Resources/Documentation/windowsserv/2003/all/techref/en-us
/w2k3tr_crtsv_what.asp.
Chapter 13: Security Management Tasks 259
Publish a CRL
Note This script is included with Windows Server 2003 when Certificate Services is
installed.
Description
About Certificate Revocation List (CRL) is a list of certificates that have been revoked
by a CA. Client computers and other security principals regularly download a CRL
and use it to check the validity of any certificates presented to them. The CRL is basi-
cally a list of certificates that should not be accepted, even though they appear to be
valid and are not expired.
Example
Publishing a CRL using the Certutil.exe command is straightforward:
Replace server\caname with the appropriate server and CA name. You can add this
command to a batch file, specifying different servers, to publish a CRL from multiple
stand-alone CAs at once.
Syntax
This command has several command-line arguments, as listed in the following table.
You can run this script with the /? parameter to display the script’s syntax.
Note that outfile is the name of the file you want the CRL written to. This command
can be included in a client logon script, which will at least execute the next time users
log on to their computers.
Troubleshooting
Certutil.exe assumes that the user account used to run the tool has permission to per-
form the desired operations within Certificate Services. Because Certificate Services
represents such a critical portion of an organization’s security, it is often secured in
such a way that normal administrative accounts—such as the Domain Admins group—
don’t have administrative access. Instead, administrative access to the PKI is granted
to another group, often reducing the number of individual users who have control
over the PKI. Be sure you are running Certutil.exe using an appropriate user account;
if necessary, execute the tool by using the Runas command to provide alternative user
credentials.
Chapter 13: Security Management Tasks 261
To Learn More
■ Learn more about using the Certutil command at http://www.microsoft.com
/resources/documentation/WindowsServ/2003/standard/proddocs/en-us
/Default.asp?url=/resources/documentation/WindowsServ/2003/standard
/proddocs/en-us/sag_CS_CertUtil2.asp.
■ Read more about Certificate Services at http://www.microsoft.com/resources
/documentation/WindowsServ/2003/all/techref/en-us/Default.asp?url=
/Resources/Documentation/windowsserv/2003/all/techref/en-us
/w2k3tr_crtsv_what.asp.
262 Part IV: Security and Network Management Tasks
Note This script is included with Windows Server 2003 when Certificate Services is
installed.
Description
When a CA’s root certificate expires, the CA loses the ability to issue more certificates
and jeopardizes all certificates already issued by the CA, which technically expire no
later than the CA’s own root certificate. Although CA expiration is infrequent—most
organizations configure their CAs to be valid for at least two years, and many for as
long as five—being able to renew them all with a single batch file can save time and
improve consistency.
Example
The Certutil.exe command-line tool makes it easier to request a renewal certificate for
a CA:
Replace server\caname with the appropriate server and CA name. You can add this
command to a batch file, specifying different servers, to renew multiple CAs at one
time. Additional command-line arguments allow the command to be customized; in
particular, you might use the reusekeys argument.
Syntax
This command has several command-line arguments, as listed in the following table.
You can run this script with the /? parameter to display the script’s syntax.
However, retaining the same keys for a long period of time increases the chances that
they will be cryptographically broken and compromised, allowing unauthorized par-
ties to duplicate the CA’s private key and forge signatures. Omitting the reusekeys argu-
ment forces a new key pair to be generated in the renewal, reducing the likelihood of
forged keys. This does mean that all previously issued certificates might be treated as
invalid and will need to be reissued; however, common practice has all issued certifi-
cates expiring before the CA certificate expires anyway, so those certificates would
expire on their own and need to be reissued.
The question of whether to reuse keys is one every organization should investigate on
its own and decide on according to its own business needs.
Troubleshooting
Certutil.exe assumes that the user account used to run the tool has permission to per-
form the desired operations within Certificate Services. Because Certificate Services
represents such a critical portion of an organization’s security, it is often secured in
such a way that normal administrative accounts—such as the Domain Admins group—
don’t have administrative access. Instead, administrative access to the PKI is granted
to another group, often reducing the number of individual users who have control
over the PKI. Be sure you are running Certutil.exe using an appropriate user account;
if necessary, execute the tool by using the Runas command to provide alternative user
credentials.
264 Part IV: Security and Network Management Tasks
To Learn More
■ Learn more about using the Certutil command at http://www.microsoft.com
/resources/documentation/WindowsServ/2003/standard/proddocs/en-us
/Default.asp?url=/resources/documentation/WindowsServ/2003/standard
/proddocs/en-us/sag_CS_CertUtil2.asp.
■ Read more about Certificate Services at http://www.microsoft.com/resources
/documentation/WindowsServ/2003/all/techref/en-us/Default.asp?url=
/Resources/Documentation/windowsserv/2003/all/techref/en-us
/w2k3tr_crtsv_what.asp.
Chapter 14
Service Management Tasks
In this chapter:
Change Service Logon Accounts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
Change Service Logon Passwords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
Change Service Startup Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
Listing Computers That Use a Specified Service. . . . . . . . . . . . . . . . . . . . 277
Listing Services That Use a Specified Account . . . . . . . . . . . . . . . . . . . . . 281
Remove Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Stopping and Disabling Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
Services are perhaps one of the most overlooked aspects of the Microsoft® Windows®
operating system when it comes to both manual and automated maintenance. Services
just quietly sit in the background doing their jobs; it’s easy to forget they’re there. When
you do need to manage services, doing so is difficult because Windows provides limited
means for graphically changing service parameters, and no means for changing them on
multiple computers.
265
266 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap14\ChangeServiceLogonAcct\ChangeServiceLogonAcct.wsf.
Description
This script, ChangeServiceLogonAcct.wsf, is designed to modify the user account
that a service uses to log on. You can specify either a local or a domain account, or
a built-in account such as LocalService or LocalSystem. This script is an excellent
way to change a service that has been using LocalSystem to a more manageable
domain or local account, for example. Typically, you would also need to use the
ChangeServiceLogonPassword.wsf script, discussed later in this chapter, to provide
the service with the correct password for its new account. ChangeServiceLogonAcct.wsf
does not perform both tasks because when changing to an account such as Local-
System, no password is required.
Example
This script allows you to target one computer or multiple computers. If you wanted to
use it to target a single remote computer named ServerA, you would use this code:
Note the convention used to specify the new account: domain\account. Also note that
the service name must be the service’s registered internal name (the Service Name
listed on the General tab of the service’s Properties dialog box), such as Messenger; it
does not refer to the service’s executable name, nor does it refer to the service’s
caption, which is what you will find listed under the Services node of the Computer
Management console.
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one
additional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3, “Working with VBScript.”
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to
/container:name
target an organizational unit within Microsoft Active
Directory®.
/recurse When used with /container, also targets computers con-
tained within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce
the timeout wait when one or more computers cannot be
reached on the network.
268 Part IV: Security and Network Management Tasks
You can run this script with the /? parameter to display the command’s syntax.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to perform the task. This situation is
unusual if you’re running the script as an administrator, but the script will detect this
error, display a message or error code, and continue running.
Chapter 14: Service Management Tasks 269
The most common error, however, is specifying a service name that is incorrect or a
user account that is improperly formatted. In the first case, the script will seem to do
nothing, because it is unable to retrieve instances of a service that does not exist. In
the second case, the script will display an error message because it will be unable to
properly retrieve the user account specified.
To Learn More
■ Find more service management samples in Microsoft Visual Basic® Script
(VBScript) at http://www.microsoft.com/technet/scriptcenter/scripts/os/services
/default.mspx.
■ Read more about Windows services management in Windows online Help and
Support Center.
270 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap14\ChangeServiceLogonPassword\ChangeServiceLogonPassword.wsf.
Description
This script, ChangeServiceLogonPassword.wsf, is designed to modify the user
account password that a service uses to log on. This is an excellent task to perform on
a regular basis: change the account’s password in your domain, and then update your
services to use the new password.
Example
This script allows you to target one computer or multiple computers. If you wanted to
use it to target a single remote computer named ServerA, you would use this code:
Note that the service name must be the service’s registered internal name (the Service
Name listed on the General tab of the service’s Properties dialog box), such as Mes-
senger; the service name does not refer to the service’s executable name, nor does it
refer to the service’s caption, which is what you will find listed under the Services node
of the Computer Management console.
Chapter 14: Service Management Tasks 271
You can also target a list of computers from a text file. The text file is expected to con-
tain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use
/computer:name /list to target a list of computers contained within a text file.
Use /computer to target a single computer. Use /container to
/container:name
target an organizational unit within Active Directory.
/recurse When used with /container, also targets computers
contained within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce
the timeout wait when one or more computers cannot be
reached on the network.
/log:path Logs unreachable computer names to the specified file. This
file can then be used later, along with the /list argument, to
retry these computers. Note that a log is created only when
used in conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step
status messages.
/service:name Specifies the service to change.
/password:password Specifies the new password to use.
You can run this script with the /? parameter to display the command’s syntax.
272 Part IV: Security and Network Management Tasks
Note that this script requires that you know which service you want to change; it does
not allow you to target all services running under a particular user account. If you use
a given account to run more than one service, a useful modification of the script might
be to change the password for all services using the specified user account. A quick
way to make this modification would be to specify the user account name in the
/service argument when running the script, and to modify the script as follows:
This change retrieves all instances of the Win32_Service class for which the logon
account is the one specified in the /service argument. The password change is applied
to each instance returned by the query.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to perform the task. This situation is
unusual if you’re running the script as an administrator, but the script will detect this
error, display a message or error code, and continue running.
Chapter 14: Service Management Tasks 273
The most common error, however, is specifying a service name that is incorrect. In
this case, the script will seem to do nothing, because it is unable to retrieve instances
of a service that does not exist.
To Learn More
■ Find more service management samples in VBScript at http://
www.microsoft.com/technet/scriptcenter/scripts/os/services/default.mspx.
■ Read more about Windows services management in Windows online Help and
Support Center.
274 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap14\ChangeServiceStartMode\ChangeServiceStartMode.wsf.
Description
This script, ChangeServiceStartMode.wsf, is designed to change a service’s startup on
multiple computers to Automatic, Manual, or Disabled. This is a useful way of tempo-
rarily disabling an unwanted service, setting a new service to have an appropriate
startup mode, and so forth.
Example
This script allows you to target one computer or multiple computers. If you want to
use it to target a single remote computer named ServerA, you would use this code:
Note that the service name must be the service’s registered internal name (the Service
Name listed on the General tab of the service’s Properties dialog), such as Messenger.
The service name does not refer to the service’s executable name, nor does it refer to
the service’s caption, which is what you will find listed under the node section of the
Computer Management console. Valid values for the /mode argument include man-
ual, automatic, and disabled.
Chapter 14: Service Management Tasks 275
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to
/container:name
target an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce
the timeout wait when one or more computers cannot be
reached on the network.
/log:path Logs unreachable computer names to the specified file. This
file can then be used later, along with the /list argument, to
retry these computers. Note that a log is created only when
used in conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step
status messages.
/service:name Specifies the service to change.
/mode:[ manual | Specifies the new startup mode for the account.
automatic | disabled ]
You can run this script with the /? parameter to display the command’s syntax.
276 Part IV: Security and Network Management Tasks
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to perform the task. This situation is
unusual if you’re running the script as an administrator, but the script will detect
this error, display a message or error code, and continue running.
The most common error, however, is specifying a service name that is incorrect. In
this case, the script will simply seem to do nothing because it is unable to retrieve
instances of a service that does not exist.
To Learn More
■ Find more service management samples in VBScript at http://
www.microsoft.com/technet/scriptcenter/scripts/os/services/default.mspx.
■ Read more about Windows services management in Windows online Help and
Support Center.
Chapter 14: Service Management Tasks 277
On the CD The sample script can be found on the CD that accompanies this book
at \Chap14\ListComputersUsingService\ListComputerUsingService.wsf.
Description
This script, ListComputerUsingService.wsf, is designed to target multiple computers
and determine which ones are hosting a particular service. This is a useful task when
performing a network inventory or audit, or for removing an unneeded service from
all computers that are running it. For example, you could use this script to quickly
determine which domain computers are running Microsoft Internet Information
Services (IIS) to ensure that those computers receive the proper patches for IIS when
they become available.
Example
This script allows you to target one computer or multiple computers. If you want to
use it to target a single remote computer named ServerA, you would use this code:
Note that the service name must be the service’s registered internal name (the Service
Name listed on the General tab of the service’s Properties dialog box), such as Mes-
senger; the service name does not refer to the service’s executable name, nor does it
refer to the service’s caption, which is what you will find listed under the Services node
of the Computer Management console. Used in the fashion shown, the script will out-
278 Part IV: Security and Network Management Tasks
You can also target a list of computers from a text file. The text file is expected to con-
tain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Notice that this command writes the information to a file named C:\Usage.csv, as
specified in the /output argument.
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to
/container:name
target an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be
reached on the network.
/log:path Logs unreachable computer names to the specified file. This
file can then be used later, along with the /list argument, to
retry these computers. Note that a log is created only when
used in conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
Chapter 14: Service Management Tasks 279
You can run this script with the /? parameter to display the command’s syntax.
One important issue with this script’s function is that it cannot differentiate between
targeted computers that are unreachable, computers for which you don’t have permis-
sions, and computers that do not contain the service specified. In all three cases, the
WMI query returns an empty result set. You can specify the /ping and /log arguments
to create a list of computers that could not be contacted, which allows you to more
easily target only those computers again at a later time.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to perform the task. This situation is
unusual if you’re running the script as an administrator, but the script will detect this
error, display a message or error code, and continue running.
280 Part IV: Security and Network Management Tasks
The most common error, however, is specifying a service name that is incorrect. In
this case, the script will seem to do nothing, because it is unable to retrieve instances
of a service that does not exist.
To Learn More
■ Find more service management samples in VBScript at http://
www.microsoft.com/technet/scriptcenter/scripts/os/services/default.mspx.
■ Read more about Windows services management in Windows online Help and
Support Center.
Chapter 14: Service Management Tasks 281
On the CD The sample script can be found on the CD that accompanies this book
at \Chap14\ListServicesUsingAcct\ListServicesUsingAccount.wsf.
Description
This script, ListServicesUsingAccount.wsf, is designed to list all services on all tar-
geted computers that are using a specified user account to log on. This is a very useful
task for a security audit and allows you to, for example, quickly identify all services
that are using the powerful LocalSystem account or a specified domain user account.
Example
This script allows you to target one computer or multiple computers. If you want to
use it to target a single remote computer named ServerA, you would use this code:
Note the convention used to specify the new account: domain\account. If you are
targeting a local account such as LocalSystem, you would exclude the domain name in
the argument. This particular command will display the list of computers and services
at the command line.
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Notice that this command writes the information to a file named C:\Usage.csv, as
specified by the /output argument.
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
You can run this script with the /? parameter to display the command’s syntax.
Chapter 14: Service Management Tasks 283
One important issue about this script’s function is that it cannot differentiate between
targeted computers that are unreachable, computers for which you don’t have permis-
sions, and computers that do not contain a service using the account you specified. In
all three cases, the WMI query returns an empty result set. You can specify the /ping
and /log arguments to create a list of computers that could not be contacted, which
allows you to more easily target only those computers again at a later time.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to perform the task. This situation is
unusual if you’re running the script as an administrator, but the script will detect this
error, display a message or error code, and continue running.
The most common error, however, is specifying a user account that is improperly for-
matted. In that case, the script will display an error message because it will be unable
to properly retrieve the user account specified.
284 Part IV: Security and Network Management Tasks
To Learn More
■ Find more service management samples in VBScript at http://
www.microsoft.com/technet/scriptcenter/scripts/os/services/default.mspx.
■ Read more about Windows services management in Windows online Help and
Support Center.
Chapter 14: Service Management Tasks 285
Remove Services
On the CD The sample script can be found on the CD that accompanies this book
at \Chap14\RemoveService\RemoveService.wsf.
Description
This script, RemoveService.wsf, removes a designated service from all targeted comput-
ers that contain that service. This script provides an excellent way to clean up older ser-
vices that are no longer in use. Although stopping and disabling the unneeded service is
a good first step, doing so does not ensure that the service will not be re-enabled; for
maximum security, unused services should be removed from the computer.
Example
This script allows you to target one computer or multiple computers. If you want to
use it to target a single remote computer named ServerA, you would use this code:
Note that the service name must be the service’s registered internal name (the Service
Name listed on the General tab of the service’s Properties dialog box), such as Mes-
senger; the service name does not refer to the service’s executable name, nor does it
refer to the service’s caption, which is what you will find listed under the Services node
of the Computer Management console.
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use
/computer:name /list to target a list of computers contained within a text file.
Use /computer to target a single computer. Use /container to
/container:name
target an organizational unit within Active Directory.
/recurse When used with /container, also targets computers con-
tained within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be
reached on the network.
/log:path Logs unreachable computer names to the specified file. This
file can then be used later, along with the /list argument, to
retry these computers. Note that a log is created only when
used in conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step
status messages.
/service:name Specifies the service to remove.
You can run this script with the /? parameter to display the command’s syntax.
In order to help avoid errors, the script first tries to stop the service, along with its
dependent services, so that Windows will permit the service to be removed. The ser-
vice might remain visible in the Services console until after a reboot, and if clicked, it
might report that it has been marked for deletion.
Neither Windows nor this script provides any means of restoring the service once it
has been removed; you will need to reinstall the service’s software or manually recon-
struct the service’s registry entries. Because undoing the results of this script can be so
complex, I recommend using the next script, StopDisableService.wsf, to first stop and
disable any service you think is a candidate for removal. This will allow you to operate
for several weeks with the service turned off, to see if any problems arise. Re-enabling
a service is much easier than reinstalling it! If no problems arise and the disabled ser-
vice is still a candidate for removal, you can use this script to automate the task.
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to perform the task. This situation is
unusual if you’re running the script as an administrator, but the script will detect this
error, display a message or error code, and continue running.
288 Part IV: Security and Network Management Tasks
The most common error, however, is simply specifying a service name that is incor-
rect. In this case, the script will simply seem to do nothing, because it is unable to
retrieve instances of a service that does not exist.
To Learn More
■ Find more service management samples in VBScript at http://
www.microsoft.com/technet/scriptcenter/scripts/os/services/default.mspx.
■ Read more about Windows services management in the Windows online Help
and Support Center.
Chapter 14: Service Management Tasks 289
On the CD The sample script can be found on the CD that accompanies this book
at \Chap14\StopDisableService\StopDisableService.wsf.
Description
This script, StopDisableService.wsf, is designed to stop a service (and any dependent
services it may have) and set the service’s startup type to Disabled. This is a good first
step to take in removing an unnecessary service, because it allows you to quickly
return the service to operation if it turns out the service is necessary after all.
Example
This script allows you to target one computer or multiple computers. If you want to
use it to target a single remote computer named ServerA, you would use this code:
Note that the service name must be the service’s registered internal name (the Service
Name listed on the General tab of the service’s Properties dialog box), such as Messenger;
it does not refer to the service’s executable name, nor does it refer to the service’s
caption, which is what you will find listed under the Services node of the Computer
Management console.
290 Part IV: Security and Network Management Tasks
You can also target a list of computers from a text file. The text file is expected to
contain one computer name per line and no other information. Assuming the file is
named C:\Computers.txt, you would use this syntax:
Finally, you can target an entire organizational unit of computer accounts. If your
domain contains an OU named West, you would use the following syntax:
Note that the /container argument will work against only the default domain of the
computer running the script. In other words, the OU specified must exist within the
same domain as that of the computer running the script. If the specified OU has
nested OUs, you can include their computer accounts as well by specifying one addi-
tional argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to
attempting a connection. Using this argument will reduce the
timeout wait when one or more computers cannot be reached
on the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/service:name Specifies the service to change.
You can run this script with the /? parameter to display the command’s syntax.
Chapter 14: Service Management Tasks 291
Troubleshooting
As with most scripts, this script can run into a couple of common errors. First, one or
more targeted computers might not be available, a condition the script can handle
properly. You can reduce the script’s execution time by including the /ping argument,
which tests connectivity prior to trying to execute the WMI query. The second possi-
ble error is that you won’t have permission to perform the task. This situation is
unusual if you’re running the script as an administrator, but the script will detect this
error, display a message or error code, and continue running.
The most common error, however, is simply specifying a service name that is incor-
rect. In this case, the script will seem to do nothing because it is unable to retrieve
292 Part IV: Security and Network Management Tasks
instances of a service that does not exist. You might also run into an instance where
the specified service cannot be stopped; the script will in those cases display an error
message and continue processing.
To Learn More
■ Find more service management samples in VBScript at http://
www.microsoft.com/technet/scriptcenter/scripts/os/services/default.mspx.
■ Read more about Windows services management in Windows online Help and
Support Center.
Chapter 15
User Account Management
Tasks
In this chapter:
Add Users from a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
Add Contacts from a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Change an Attribute for Multiple Users. . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Disable Old User Accounts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
Delete Published User Certificates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Expire Passwords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Expire User Accounts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
List Accounts with Old Passwords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Unlock Locked Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
293
294 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap15\AddUsers\AddUsers.wsf.
Description
This script, AddUsers.wsf, is designed to read user account information from a
Microsoft Excel spreadsheet or a Microsoft Access database and create new user
accounts based on that information. New accounts can be created in a specified orga-
nizational unit (OU), and you can set a wide variety of attributes for the new accounts.
Tip If you have user account information in a different format, such as a Microsoft
SQL Server™ database, export the information to a comma-separated values (CSV)
file, which can be opened by using Excel. Save the file again as a native Excel spread-
sheet to use it with this script.
Example
This script has three required arguments, which are used as follows:
The file:/ argument specifies the file to be read (a sample Excel file is included on the
CD). The type:/ argument must be either Excel or Access, indicating the file being
opened. The /table: argument specifies the Access table name or Excel sheet name
containing your data. In the case of Excel, note the special formatting for the sheet
name: enclosed in square brackets ([]) and followed by a dollar sign ($). Excel spread-
sheets must have column names as the first row of the sheet.
■ givenName
■ initials
■ displayName
■ description
■ mail
■ wWWHomePage
■ streetAddress
■ postalCode
■ st (state or province)
■ l (lowercase letter L; stands for locality and is used for the city name)
■ profilePath
■ scriptPath
■ homeDirectory
■ homePhone
■ pager
■ mobile
■ fascimileTelephoneNumber
■ iPPhone
■ info
■ title
■ department
■ company
Chapter 15: User Account Management Tasks 297
By default, new accounts are created in the root of the domain. To specify a specific
container or OU, include the /ou: argument:
To provide better security, all new accounts are disabled when created. You will need
to enable the accounts when they are ready to be used.
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
You can run this script with the /? parameter to display the command’s syntax.
Case Else
WScript.Echo "** Unknown file type specified"
wscript.quit
End Select
'open connection
On Error Resume Next
Dim oCN
Verbose "Opening connection to data file..."
Set oCN = CreateObject("ADODB.Connection")
oCN.Open sConn
If Err <> 0 Then
WScript.Echo "** Error opening file"
WScript.Echo Err.Description
WScript.Quit
End If
On Error goto 0
The following code creates the connection to the domain or the specified OU:
Notice that the end result of this code is a variable named oOU, which represents the
connected object (the domain or a specific OU). A subsequent line of code utilizes
this variable to create the new object:
The resulting variable, oUser, is used to set the specified properties for the new account.
Chapter 15: User Account Management Tasks 299
Troubleshooting
A number of errors can occur during the execution of this script. First and foremost,
you must have permission to create new objects of this type within the domain or
specified OU. You must also take care to provide the proper table name, and in the
case of an Excel spreadsheet, ensure that the first row contains the appropriate
column names. The script attempts to check all of these things and displays an
appropriate error message if necessary.
It’s also possible for you to specify an invalid value for one or more object properties.
If you do, the script will generally display a generic error indicating that the property
could not be properly set. You might also specify an invalid property name (a com-
mon mistake is to use “city” instead of “l”); in this case, the script will display the same
generic error message for this condition. In the event that an error is displayed when
setting a property, first verify that you have permission to write the property in ques-
tion, that the property name is correctly spelled, and that the value you provided is
valid for that property.
Incorrect permissions can cause a number of errors, especially if you allow the script to
create accounts in the root of the domain. I recommend always selecting a destination
OU and specifying it by using the /ou argument, rather than create accounts in the root
of the domain.
To Learn More
■ Read more about ADO on the Microsoft Data Access home page at http://
msdn.microsoft.com/data/Default.aspx.
■ Read more about ADSI at http://www.microsoft.com/windows2000/techinfo/
howitworks/activedirectory/adsilinks.asp.
300 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap15\AddContacts\AddContacts.wsf.
Description
This script, AddContacts.wsf, is designed to read contact account information from an
Excel spreadsheet or an Access database and create new contact accounts based on
that information. New accounts can be created in a specified organizational unit
(OU), and you can set a wide variety of attributes for the new contacts.
Tip If you have user account information in a different format, such as a SQL Server
database, export the information to a comma-separated values (CSV) file, which can
be opened by Excel. Save the file again as a native Excel spreadsheet to use it with
this script.
Example
This script has three required arguments, which are used as follows:
The file:/ argument specifies the file to be read (a sample Excel file is included on the
CD). The type:/ argument must be either Excel or Access, indicating the file being
opened. The /table: argument specifies the Access table name or Excel sheet name
containing your data. In the case of Excel, note the special formatting for the sheet
name: enclosed in square brackets and followed by a dollar sign. The first sheet of an
Excel spreadsheet must have column names.
■ givenName
■ initials
■ displayName
■ description
■ mail
■ wWWHomePage
■ streetAddress
■ postalCode
■ st (state or province)
■ l (lowercase letter L; stands for locality and is used for the city name)
■ homePhone
■ pager
■ mobile
■ fascimileTelephoneNumber
■ iPPhone
■ info
■ title
■ department
■ company
By default, new contact accounts are created in the root of the domain. To specify a
specific container or OU, include the /ou: argument:
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3, “Working with VBScript.”
You can run this script with the /? parameter to display the command’s syntax.
'open connection
On Error Resume Next
Dim oCN
Verbose "Opening connection to data file..."
Set oCN = CreateObject("ADODB.Connection")
oCN.Open sConn
If Err <> 0 Then
WScript.Echo "** Error opening file"
WScript.Echo Err.Description
Chapter 15: User Account Management Tasks 303
WScript.Quit
End If
On Error goto 0
The following code creates the connection to the domain or the specified OU:
Notice that the end result of this code is a variable named oOU, which represents the
connected object (the domain or a specific OU). A subsequent line of code utilizes
this variable to create the new object:
The resulting variable, oContact, is used to set the specified properties for the new
account.
Troubleshooting
A number of errors can occur during the execution of this script. First and foremost,
you must have permission to create new objects of this type within the domain or
specified OU. You must also take care to provide the proper table name, and in the
case of an Excel spreadsheet, ensure that the first row contains the appropriate
column names. The script attempts to check all these things and displays an
appropriate error message if necessary.
304 Part IV: Security and Network Management Tasks
It’s also possible for you to specify an invalid value for one or more object properties.
If you do, the script will generally display a generic error message indicating that the
property could not be properly set. You might also specify an invalid property name (a
common mistake is to use “city” instead of “l”); the script will display the same generic
error message for this condition. In the event that an error is displayed for setting a
property, first verify that you have permission to write the property in question, that
the property name is correctly spelled, and that the value you provided is valid for that
property.
To Learn More
■ Read more about ADO on the Microsoft Data Access home page at http://
msdn.microsoft.com/data/Default.aspx.
■ Read more about ADSI at http://www.microsoft.com/windows2000/techinfo
/howitworks/activedirectory/adsilinks.asp.
Chapter 15: User Account Management Tasks 305
On the CD The sample script can be found on the CD that accompanies this book
at \Chap15\ChangeAttrib\ChangeAttrib.wsf.
Description
This script, ChangeAttrib.wsf, is designed to change a single Active Directory user
attribute for a group of users. For example, if an organizational unit (OU) full of users
moves to a new office, you might use this script to quickly change their mailing
address information within Active Directory.
Example
This script has two required arguments, which are used as follows:
This will change the “l” attribute (which stands for locality) to “Las Vegas” for all
domain users. The script can also be targeted to a specific OU:
This will change the “l” attribute for all users in the West OU. Note that the script
automatically includes child OUs and all users within those child OUs to an infinite
level. The script does not provide a way to target a single OU and ignore any child
OUs it might have.
306 Part IV: Security and Network Management Tasks
Attribute names must be exactly as defined within Active Directory; you can use the
Active Directory Schema console to explore available attributes. Examples include:
■ givenName
■ initials
■ displayName
■ description
■ mail
■ wWWHomePage
■ streetAddress
■ postalCode
■ st (state or province)
■ l (lowercase letter L; stands for locality and is used for the city name)
■ homePhone
■ pager
■ mobile
■ fascimileTelephoneNumber
■ iPPhone
■ info
■ title
■ department
■ company
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/ou:ou Optional. Specifies an OU that the script should target. Must take
the form ou:“ou=West”.
/attrib:attribute Specifies the attribute to change.
/value:newvalue Specifies the new value for the attribute. Values that contain
spaces must be contained within double quotation marks.
/verbose Displays detailed status messages as the script executes.
You can run this script with the /? parameter to display the command’s syntax.
Chapter 15: User Account Management Tasks 307
The remainder of the script’s code handles the initial connection to Active Directory
(either at the root of the domain or in a specific OU) and the process of iterating
through the available users and any child OUs.
Troubleshooting
The most common error this script can encounter is a lack of permissions to make the
appropriate changes in Active Directory. It’s also possible for Active Directory to refuse
to change the attribute. This can generally occur for newly created user accounts that
have not completely replicated throughout the domain, and it can also occur in cer-
tain rare conditions when the Active Directory database is in an inconsistent state.
In all cases, the script will display an error message and continue. You can try the
operation again later, if necessary, after account replication is completed or any Active
Directory problems are corrected.
If you experience a condition in which the script is unable to change attributes for any
user, and it displays an error message for each user attempted, the problem is either
related to permissions or to the condition of the Active Directory database. Ensure
that you can make changes to the attribute in question by using the graphical user
interface, because doing so eliminates permissions as a potential problem.
To Learn More
■ Read more about ADSI at http://www.microsoft.com/windows2000/techinfo/
howitworks/activedirectory/adsilinks.asp.
■ Find more Microsoft Visual Basic® Script (VBScript) samples related to user
management at http://www.microsoft.com/technet/scriptcenter/scripts/ad/users/
default.mspx.
308 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap15\DisableOldUsers\DisableOldUsers.wsf.
Description
This script, DisableOldUsers.wsf, will disable all user accounts that have not been
used in a specified number of days. This is a useful script to run on a regular basis to
disable unused security accounts. It allows you to easily review those accounts to
determine whether they can be removed from the domain.
Warning This script relies on an Active Directory attribute that is replicated prop-
erly only in a Windows Server 2003 Active Directory domain, which has only Windows
Server 2003 domain controllers. Earlier versions of Active Directory set this attribute
on a per-domain controller basis rather than replicate it, which results in this script
incorrectly disabling active user accounts.
Example
This script has only one required argument, which is used as follows:
DisableOldUsers.wsf /age:90
This example will disable all user accounts that have not been used in 90 days. You
can limit the script to the users contained within a single organizational unit (OU)
and its child OUs by specifying the OU name:
You can also have the script create a file that lists the user accounts that were disabled:
Finally, you can have the script run in a report-only mode. In this mode, the script
creates the same output of users whose accounts have not been used in the specified
number of days, but the script will not disable any accounts. The syntax for this
option is:
I recommend using the /checkonly argument the first time you run the script to see
how many user accounts would be disabled. Doing so allows you to provide a
common-sense check of the script’s results to ensure that accounts aren’t disabled
unnecessarily.
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/ou:ou Optional. Specifies an OU that the script should target. Must take
the form ou:“ou=West”.
/checkonly Optional. Forces the script to check user accounts but not
disable any.
/age:days Required. Specifies the minimum number of inactive days a user
account must have to be considered old.
/verbose Specifies that the script display detailed status messages as the
script executes.
/output:file Optional. Specifies that the script’s output be written to the
specified file.
You can run this script with the /? parameter to display the command’s syntax.
Else
Verbose " - " & dLast
If DateDiff("d",dLast,Date) > CInt(WScript.Arguments.named("age")) Then
Output oADObject.Get("sAMAccountName") & " last logged in on " & dLast & " ("
& DateDiff("d",dLast,Date) & " days ago)"
if not wscript.Arguments.Named.Exists("checkonly") Then
oADObject.Put "userAccountControl",
oADObject.Get("userAccountControl") Or 2
End If
End If
End If
The script uses the Active Directory LastLogin property. All domain controllers—even
as far back as Microsoft Windows NT®—populated this attribute with the current date
each time a user logged on, but prior to Windows Server 2003, this attribute was not
replicated across domain controllers. In other words, the only domain controller with
the correct LastLogin property was the domain controller that most recently authenti-
cated the user. In Windows Server 2003, domain controllers replicate this attribute
along with most other attributes so that each domain controller (after replication
completes) has the correct LastLogin information.
Note that the script is designed to target organizational units only; containers—such as
the built-in Users and Computers containers—are not supported.
Troubleshooting
As always, permissions represent a potential problem for this script. You must have
permission to query the Active Directory information as well as disable the user
account (unless /checkonly is specified).
The most likely problem is that the domain controller the script uses (which is
determined by the computer running the script) does not have the correct LastLogin
information for all user accounts. In a Windows Server 2003 Active Directory with
only Windows Server 2003 domain controllers, this indicates a replication failure;
prior to Windows Server 2003, this condition is by design and cannot be avoided.
In any case, always run the script with /checkonly first so that you can verify a few
known accounts to make sure they are not targeted for disabling. Then you can run
the script without /checkonly to actually disable old accounts.
To Learn More
■ Read more about ADSI at http://www.microsoft.com/windows2000/techinfo/
howitworks/activedirectory/adsilinks.asp.
■ Find more VBScript samples related to user management at http://
www.microsoft.com/technet/scriptcenter/scripts/ad/users/default.mspx.
Chapter 15: User Account Management Tasks 311
On the CD The sample script can be found on the CD that accompanies this book
at \Chap15\DeletePubCerts\DeletePubCerts.wsf.
Description
This script, DeletePubCerts.wsf, will delete all certificates that have been published in
Active Directory for users. You might use this script to quickly remove certificates that
have been incorrectly published, or use it in a test environment to delete all certifi-
cates so that you can conduct additional issuing tests.
Example
This script has no required arguments. The script can be used as follows:
DeletePubCerts.wsf
Running this code deletes all published certificates for all users. You can limit the
effect of the script to a single organizational unit (OU) and its nested OUs by specify-
ing an additional argument naming the OU:
DeletePubCerts.wsf /ou:"ou=West"
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
312 Part IV: Security and Network Management Tasks
/ou:ou Optional. Specifies an OU that the script should target. Must take the
form ou:”ou=West”.
/verbose Specifies that the script display detailed status messages as the script
executes.
You can run this script with the /? parameter to display the command’s syntax.
Troubleshooting
Lack of permissions will cause the script to display an error message and stop run-
ning. An inconsistent or corrupt Active Directory database can also cause the same
problem, although this is rare. In the event of any error, an error message will provide
a clue as to the source of the problem. Try to correct the source of the problem before
running the script again.
To Learn More
■ Read more about ADSI at http://www.microsoft.com/windows2000/techinfo/
howitworks/activedirectory/adsilinks.asp.
■ Find more VBScript samples related to user management at http://
www.microsoft.com/technet/scriptcenter/scripts/ad/users/default.mspx.
Chapter 15: User Account Management Tasks 313
Expire Passwords
On the CD The sample script can be found on the CD that accompanies this book
at \Chap15\ExpirePasswords\ExpirePasswords.wsf.
Description
This script, ExpirePasswords.wsf, will set all targeted user account passwords to
expired (except accounts that are configured to have passwords that never expire).
This script can be used to quickly force all users to change their passwords the next
time they log on.
On a Windows Server 2003 domain controller, you can perform this task for multiple
users within the same organizational unit (OU)—simply select multiple users instead
of a single user. However, there is no way to simultaneously target all users in the
domain or users in any nested OUs.
Example
This script has no required arguments and can be run as follows:
ExpirePasswords.wsf
314 Part IV: Security and Network Management Tasks
You can limit the effects of the script to a single OU and its child OUs by specifying
the /ou: argument:
ExpirePasswords.wsf /ou:"ou=West"
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/ou:ou Optional. Specifies an OU that the script should target. Must take the
form ou:“ou=West”.
/verbose Specifies that the script display detailed status messages as the script
executes.
You can run this script with the /? parameter to display the command’s syntax.
Sub WorkWithObject(oContainer)
Dim oADObject
For Each oADObject in oContainer
Select Case oADObject.Class
Case "user"
Verbose oADObject.Name
oADObject.Put "pwdLastSet",0
oADObject.SetInfo
Case "organizationalUnit" , "container"
'oADObject is an OU or container...
'go through its objects
WorkWithObject(oADObject)
Chapter 15: User Account Management Tasks 315
End Select
Next
End Sub
Sub Verbose(sMsg)
If WScript.Arguments.Named.Exists("verbose") Then
WScript.Echo " " & sMsg
End If
End Sub
This script connects to the root of the domain or, if specified, a specific OU, and iter-
ates through each user account and OU contained within it.
Troubleshooting
This script’s most likely problem is insufficient permissions to query the information
from Active Directory or to set the necessary attributes in Active Directory. Should this
occur, the script will display an error message and stop running.
To Learn More
■ Read more about ADSI at http://www.microsoft.com/windows2000/techinfo/
howitworks/activedirectory/adsilinks.asp.
■ Find more VBScript samples related to user management at http://
www.microsoft.com/technet/scriptcenter/scripts/ad/users/default.mspx.
316 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap15\ExpireUsers\ExpireUsers.wsf.
Description
This script, ExpireUsers.wsf, will set all targeted user accounts to expired. This script
can be used to quickly expire all accounts within a specified organizational unit (OU),
such as contractor accounts within an OU after that contract has ended.
Note that this script will not immediately stop the targeted user accounts from work-
ing. Account expiration takes place at the end of the current day, and takes effect only
after the specified accounts have logged off.
On a Windows Server 2003 domain controller, you can perform this task for multiple
users within the same organizational unit (OU): just select multiple users instead of a
single user. However, there is no way to simultaneously target all users in the domain
or users in any nested OUs.
Example
This script has no required arguments and can be run as follows:
ExpireUsers.wsf
Chapter 15: User Account Management Tasks 317
You can limit the effects of the script to a single OU and its nested OUs by specifying
the /ou: argument:
ExpireUsers.wsf /ou:"ou=West"
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
/ou:ou Optional. Specifies an OU that the script should target. Must take the
form ou:“ou=West”.
/verbose Specifies that the script display detailed status messages as the script
executes.
You can run this script with the /? parameter to display the command’s syntax.
Sub WorkWithObject(oContainer)
Dim oADObject
For Each oADObject in oContainer
Select Case oADObject.Class
Case "user"
Verbose oADObject.Name
oADObject.Put "accountExpirationDate", Now
oADObject.SetInfo
Case "organizationalUnit" , "container"
'oADObject is an OU or container...
'go through its objects
WorkWithObject(oADObject)
318 Part IV: Security and Network Management Tasks
End Select
Next
End Sub
Sub Verbose(sMsg)
If WScript.Arguments.Named.Exists("verbose") Then
WScript.Echo " " & sMsg
End If
End Sub
This script connects to the root of the domain or, if specified, to a specific OU, and
iterates through each user account and OU contained within it.
Troubleshooting
This script’s most likely problem is insufficient permissions to query the information
from Active Directory or to set the necessary attributes in Active Directory. Should this
occur, the script will display an error message and stop running.
To Learn More
■ Read more about ADSI at http://www.microsoft.com/windows2000/techinfo/
howitworks/activedirectory/adsilinks.asp.
■ Find more VBScript samples related to user management at http://
www.microsoft.com/technet/scriptcenter/scripts/ad/users/default.mspx.
Chapter 15: User Account Management Tasks 319
On the CD The sample script can be found on the CD that accompanies this book
at \Chap15\OldPasswords\OldPasswords.wsf.
Description
This script, OldPasswords.wsf, will list all user accounts that have not changed their
passwords in a specified number of days. This script can be useful as a security audit-
ing tool, and also as a preliminary check before changing domain password policy on
maximum password age. For example, if you are considering a change to make the
maximum password age 45 days rather than 90, this script will tell you how many
users will be immediately affected.
Example
This script has one required argument, which is used as follows:
OldPasswords.wsf /age:90
This lists all user accounts whose passwords are older than 90 days. You can also tar-
get a specific organizational unit (OU):
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
320 Part IV: Security and Network Management Tasks
/ou:ou Optional. Specifies an OU that the script should target. Must take
the form ou:“ou=West”.
/age:days Required. Specifies the maximum password age, causing the script
to list user accounts with a password age greater than this figure.
/verbose Specifies that the script display detailed status messages as the
script executes.
You can run this script with the /? parameter to display the command’s syntax.
The script checks the PasswordLastChanged attribute to determine the date on which
the password was last changed, and then calculates the password’s age in days based
on the current system date.
Troubleshooting
This script has only one opportunity for a problem: when you do not have permis-
sions in Active Directory to query the necessary attributes. If you have permissions,
this script should not run into any problems.
To Learn More
■ Read more about ADSI at http://www.microsoft.com/windows2000/techinfo/
howitworks/activedirectory/adsilinks.asp.
■ Find more VBScript samples related to user management at http://
www.microsoft.com/technet/scriptcenter/scripts/ad/users/default.mspx.
Chapter 15: User Account Management Tasks 321
On the CD The sample script can be found on the CD that accompanies this book
at \Chap15\UnlockLockedUsers\UnlockLockedUsers.wsf.
Description
This script, UnlockLockedUsers.wsf, will unlock all targeted user accounts. This can
be useful when a large number of accounts were locked by accident, or when a large
number of accounts were locked because of some failure.
Example
This script has no required arguments and can be run as follows:
UnlockLockedUsers.wsf
UnlockLockedUsers.wsf /ou:"ou=West"
Syntax
This script can be executed as a command-line utility. Set CScript.exe to be your
default script processor, as described in Chapter 3.
322 Part IV: Security and Network Management Tasks
/ou:ou Optional. Specifies an OU that the script should target. Must take the
form /ou:“ou=West”.
/verbose Specifies that the script display detailed status messages as the script
executes.
You can run this script with the /? parameter to display the command’s syntax.
The script simply reverses the IsAccountLocked attribute whenever that attribute is set
to True. You should carefully review the script’s output to ensure no accounts were
unlocked that should be locked.
Troubleshooting
This script has only one opportunity for a problem: when you do not have permis-
sions in Active Directory to query the necessary attributes. If you have permissions,
this script should not run into any problems.
To Learn More
■ Read more about ADSI at http://www.microsoft.com/windows2000/techinfo/
howitworks/activedirectory/adsilinks.asp.
■ Find more VBScript samples related to user management at http://
www.microsoft.com/technet/scriptcenter/scripts/ad/users/default.mspx.
Chapter 16
Login Script Tasks
In this chapter:
Check Group Membership . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
Write an Event Log Entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
Pause the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
Display a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Retrieve User Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
Map a Drive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Map a Printer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Set the Default Printer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
This chapter is a bit different from others in this book. In this chapter, I assume that
you’re writing your own logon scripts in Microsoft® Visual Basic® Script (VBScript),
and that you’re looking for shortcuts so that you can perform common logon-related
tasks. Even though many common tasks are easily accomplished using some of the
Microsoft Windows® Script Host’s built-in objects, I provide you with easy-to-use
subroutines and functions that you can paste into your logon scripts and start using.
323
324 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap16\CheckGroupMembership.vbs.
Description
This script, CheckGroupMembership.vbs, contains a single function that checks to
see whether a given user is a member of a specified group. The function returns a True
or False value, allowing your logon script to execute tasks—such as mapping drives—
based on the user’s membership in a particular group.
Example
Use this script as follows:
If IsMember("cn=DonJ,ou=West,dc=company,dc=com","SalesUsers") Then
'the user is a member – do something appropriate
Else
'the user is not a member – do something appropriate
End If
Note that the user must be identified using a complete, fully qualified Lightweight
Directory Access Protocol (LDAP) reference.
Syntax
This script is intended to be included in, and called from, a larger VBScript-based
logon script. This script’s syntax is as follows:
IsMember(sUser,sGroup)
sUser Specifies the user to check. Must be a fully qualified LDAP reference.
sGroup Specifies the name of the group to check.
Chapter 16: Login Script Tasks 325
Function IsMember(sUser,sGroup)
'sUser must be a complete LDAP string:
' cn=DonJ,ou=West,dc=company,dc=com
'
arrMemberOf = oUser.GetEx("memberOf")
If Err.Number = PROPERTY_NOT_FOUND Then
IsMember = False
Exit Function
Else
For Each Group in arrMemberOf
If Group = sGroup Then
IsMember = True
Exit Function
End If
Next
End If
IsMember = False
End Function
Troubleshooting
Provided you use a fully qualified LDAP reference for the user, you shouldn’t have any
problems using this script. Although the script will run under the user’s security con-
text (as do all logon scripts), users have permission to query their own group mem-
bership information from the domain.
326 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap16\WriteEvent.vbs.
Description
This script, WriteEvent.vbs, contains a single subroutine that writes an event log entry
to the local Application event log.
Example
Use this script as follows:
The second argument specifies the type of event to be written, such as an error or a
warning. See the next “Syntax” section for a list of possible values.
Syntax
This script is intended to be included in, and called from, a larger VBScript-based
logon script. This script’s syntax is as follows:
Troubleshooting
Provided the user running the logon script has permission to log events (which she
does by default), this script should not encounter any problems.
328 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap16\Pause.vbs.
Description
This script, Pause.vbs, pauses the script for a specified period of time. You might
use this to cause the logon script to wait for a few seconds while other events are
processing.
Example
Use this script as follows:
Pause 10
The script accepts one argument, which is the number of seconds you want the script
to pause.
Syntax
This script is intended to be included in, and called from, a larger VBScript-based
logon script. This script’s syntax is as follows:
Pause iSeconds
Sub Pause(iSeconds)
WScript.Sleep(iSeconds * 1000)
End Sub
The script multiplies your specified number of seconds by 1,000 to achieve the correct
delay period in milliseconds.
Chapter 16: Login Script Tasks 329
Troubleshooting
This script is unlikely to encounter any problems. If you encounter an error when
using a large value for iSeconds, try using a smaller value and calling the subroutine
multiple times (each time using that smaller value) to achieve the desired pause
duration.
330 Part IV: Security and Network Management Tasks
Display a Message
On the CD The sample script can be found on the CD that accompanies this book
at \Chap16\ShowMessage.vbs.
Description
This script, ShowMessage.vbs, utilizes the Windows Script Host’s built-in ability to
show pop-up messages. These messages can be simple dialog boxes with an OK
button, or they can be more complex and offer the user a choice of buttons to click.
The messages can also be timed to disappear automatically, making them ideal for use
as a logon script welcome message.
Example
Use this script as follows:
The last argument controls the icon and buttons displayed in the message box. See the
following section titled “Syntax” for details about possible values. iVar will contain a
value indicating which button the user clicked:
■ –1 No button was clicked. The dialog box was automatically cancelled after the
number of seconds specified.
■ 1 OK was clicked.
■ 2 Cancel was clicked.
■ 3 Abort was clicked.
■ 4 Retry was clicked.
■ 5 Ignore was clicked.
■ 6 Yes was clicked.
■ 7 No was clicked.
Chapter 16: Login Script Tasks 331
Syntax
This script is intended to be included in, and called from, a larger VBScript-based
logon script. This script’s syntax is as follows:
Troubleshooting
Remember that the function will return -1 if you specify a number of seconds and the
user does not click a button before the message box is automatically cancelled.
332 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap16\GetUserInfo.vbs.
Description
This script, GetUserInfo.vbs, contains three functions that can be used to retrieve
the currently logged-on user’s name, the logon domain, and the name of the local
computer.
Example
Use this script as follows:
sUsername = GetUserName()
sDomain = GetUserDomain()
sComputer = GetComputerName()
Syntax
This script is intended to be included in, and called from, a larger VBScript-based
logon script. This script’s three functions have no required or optional arguments;
simply assign the result of these functions to a variable to populate the variable with
the desired information.
Function GetUserName()
Dim oNetwork
Set oNetwork = CreateObject("WScript.Network")
GetUserName = oNetwork.UserName
End Function
Function GetUserDomain()
Dim oNetwork
Set oNetwork = CreateObject("WScript.Network")
Chapter 16: Login Script Tasks 333
GetUserDomain = oNetwork.UserDomain
End Function
Function GetComputerName()
Dim oNetwork
Set oNetwork = CreateObject("WScript.Network")
GetComputerName = oNetwork.ComputerName
End Function
Troubleshooting
The Network object will not function properly unless run on a computer that is a
member of a Windows domain (Windows NT® or Active Directory). Using this script
on client computers that log on to only a NetWare directory tree, for example, will
result in error messages.
334 Part IV: Security and Network Management Tasks
Map a Drive
On the CD The sample script can be found on the CD that accompanies this book
at \Chap16\MapDrive.vbs.
Description
This script, MapDrive.vbs, contains a single subroutine that maps a network drive to
a specified Universal Naming Convention (UNC) path.
Example
Use this script as follows:
MapDrive "Z:","\\Server\Share"
Note that the drive letter must be one that is not currently in use; if it is, an error will
occur.
Syntax
This script is intended to be included in, and called from, a larger VBScript-based
logon script. This script’s syntax is as follows:
Sub MapDrive(sLetter,sUNC)
Dim oNetwork
Set oNetwork = WScript.CreateObject("WScript.Network")
oNetwork.MapNetworkDrive sLetter,sUNC
End Sub
Chapter 16: Login Script Tasks 335
Troubleshooting
An error will occur when the user does not have permission to the destination
UNC, when the user’s client computer does not contain a redirector capable of
connecting to the destination UNC, or when the destination UNC is unreachable
at the time.
336 Part IV: Security and Network Management Tasks
Map a Printer
On the CD The sample script can be found on the CD that accompanies this book
at \Chap16\MapPrinter.vbs.
Description
This script, MapPrinter.vbs, contains a single subroutine that adds a Windows printer
connection to a specified printer. On computers running Windows 2000 and later,
the printer driver does not need to be installed on the client computer; the client is
capable of downloading the driver from the print server, provided the print server
is also running Windows 2000 or later. This script is not intended to add printer
connections to printers that are not hosted on print servers running Windows 2000
(or later).
Example
Use this script as follows:
Note that the second argument should contain the full name of the printer to be
added.
Syntax
This script is intended to be included in, and called from, a larger VBScript-based
logon script. This script’s syntax is as follows:
sUNC Specifies the Universal Naming Convention (UNC) path of the printer
share.
sName Specifies the complete name of the printer driver associated with the
printer being mapped.
Chapter 16: Login Script Tasks 337
Sub MapPrinter(sUNC,sName)
Dim oNetwork
Set oNetwork = CreateObject("WScript.Network")
oNetwork.AddWindowsPrinterConnection sUNC,sName
End Sub
Troubleshooting
The user must have permission to use the printer mapped; if it does not, an error will
occur. Errors will also occur when the UNC specified is not reachable at the time or
the printer driver name is incorrect.
338 Part IV: Security and Network Management Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap16\SetDefaultPrinter.vbs.
Description
This script, SetDefaultPrinter.vbs, contains a single subroutine that sets a specified
printer—which must already be connected—to be the system’s default printer.
Example
Use this script as follows:
SetDefaultPrinter "Network Printer 1"
The single argument must be the name of the printer as defined on the computer
where the script is running. You can see an example of this name by looking in the
computer’s Printers and Faxes folder.
Syntax
This script is intended to be included in, and called from, a larger VBScript-based
logon script. This script’s syntax is as follows:
SetDefaultPrinter sName
sName Specifies the name of the printer that will be made the default.
Troubleshooting
An error will occur when the specified printer is not already mapped or connected on
the computer.
Part V
IIS 6.0 Tasks
Chapter 17
IIS Web Site Management
Tasks
In this chapter:
Create Web Sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
Create FTP Virtual Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
Modify Web Site Settings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
Replicate Web Site Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
Copy Web Site Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
List Virtual Directories with Execute or Script Permissions. . . . . . . . . . . 353
341
342 Part V: IIS 6.0 Tasks
Description
This script, Iisweb.vbs, is included with IIS 6.0 and performs a number of Web-related
administration tasks. Its simpler functions include starting, stopping, and pausing
the Web services within IIS. It can also be used to create new Web sites. If you need
to target multiple servers at one time, use the script Iismultiany.wsf in Chapter 19
instead of Iisweb.vbs.
Example
The following example creates a new Web site that uses C:\Inetpub\Wwwroot as its
root path, 80 as its TCP port, and all unassigned IP addresses:
Note that this script is intended to be run from the CScript host. From a command
line, you can make CScript the default by running CScript //h:Cscript.
Syntax
This script’s syntax for creating a new FTP site is as follows:
Path Required. Specifies the root path for the new FTP site.
Sitename Required. Specifies the name of the new FTP site as it appears in
the Internet Information Services console.
/b port You must specify /b, /i, or some combination of these. The /b
/I address argument specifies the TCP port the new FTP site will use; the
default is 80. The /i argument specifies the IP address the new
FTP site will use; the default is to use all unassigned IP addresses.
Each FTP site you create must have a unique port/address
combination.
Chapter 17: IIS Web Site Management Tasks 343
Troubleshooting
To ensure this script doesn’t run into any major errors, either have the permissions
necessary to perform the script’s task or provide alternate credentials that have the
appropriate permissions. One common mistake is to specify as new a site name that
already exists, or to specify a port/address/hostname combination that is already in use
by another Web site. Both of these scenarios will result in an error, and you’ll need to
rerun the script with different values for the appropriate arguments.
344 Part V: IIS 6.0 Tasks
Description
This script, Iisvdir.vbs, is included with IIS 6.0 and performs a number of administra-
tion tasks related to Web virtual directories. If you need to target multiple servers at
one time, use the script Iismultiany.wsf in Chapter 19 instead of Iisvdir.vbs. Before
you can work with Web virtual directories, you must first create a Web site (see the
previous script for a way to automate that task).
Note Iisvdir.vbs will create a single virtual directory; if you need to create a batch of
virtual directories, include Iisvdir.vbs in a normal batch (.bat) file.
Example
The following example creates a new Web virtual directory in a Web site named
“Web Site.” The virtual directory points to the physical path C:\inetpub\ftpuploads,
and the virtual directory alias will be \Downloads.
Note that the physical path C:\Inetpub\downloads will be created by this script if the
path does not already exist.
If you already have a virtual path named \Uploads\Users, and you want to add a new
virtual directory named Private to the end of this path—for a path of \Uploads\
Users\Private—you would use the following:
This new virtual directory would have the physical path C:\Inetpub\Privateroot.
Chapter 17: IIS Web Site Management Tasks 345
Syntax
This script’s syntax for creating a new Web virtual directory is as follows:
Troubleshooting
To ensure this script doesn’t run into any major errors, either have the permissions
necessary to perform the script’s task or provide alternate credentials that have the
appropriate permissions. One common mistake is to specify a site name that doesn’t
exist or a virtual path that doesn’t exist. Both the site name and virtual path must exist
for the command to complete.
346 Part V: IIS 6.0 Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap17\ModWeb.wsf.
Description
This script, ModWeb.wsf, will change properties for a Web virtual server (also called
a Web site). The script will also list available Web virtual servers, and can target
multiple computers. This script is a good way to reconfigure multiple servers to have
a consistent configuration.
Example
Use this script as follows:
This will list all Web sites on Server2. You will need a service instance name in order
to make any modifications to the service:
This modifies the service named Service1 on the server Server2, setting its AllowKeepAlive
property to False. Available properties are:
■ AllowKeepAlive
■ ConnectionTimeout
■ DontLog
■ ServerComment
■ MaxConnections
■ MaxBandwidth
■ ContentIndexed
Tip You can learn about these properties and their purposes, as well as the valid
range of values for them, in the MSDN® Library. Look for “IisWebServiceSetting” in
the Index.
Chapter 17: IIS Web Site Management Tasks 347
This script can also be used to target multiple servers listed in a file or an entire
organizational unit (OU) of servers. To target servers listed in a file:
Syntax
This script’s syntax is as follows:
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to attempt-
ing a connection. Using this argument will reduce the timeout wait
when one or more computers cannot be reached on the network.
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/listsites Lists all Web services on the targeted computers so that you can
determine the names of the available services.
/site:service These arguments must be used together. Specifies the name of
/prop:property the Web service to target (/svc), the property to change (/prop),
and the new value for the property (/val).
/val:new_value
Troubleshooting
Other than the obvious problems that can arise if you try to use this script without
having the necessary permissions, or if you run the script against a server that doesn’t
have IIS 6.0 installed and a Web virtual server configured, only one scenario can cause
a major problem in this script: specifying an invalid value for a property. Many prop-
erties, such as ContentIndexed, accept only a Boolean (True or False) value. Specifying
a string or an integer might result in an error or in unexpected behavior.
Chapter 17: IIS Web Site Management Tasks 349
Description
Robocopy.exe is a command-line utility that provides robust file copy capabilities. It
can be used to replicate Web content from one Web server to multiple destination
servers. Creating a batch file that runs Robocopy against multiple destinations pro-
vides single-command replication to an entire Web farm. The batch file can also be
scheduled to ensure content is replicated on a regular basis, if desired.
Robocopy differs significantly from the built-in Windows Xcopy command in that
Robocopy is better built for over-the-network copying. Robocopy ensures that files are
copied, and it does not recopy a file if the source and destination files’ timestamps are
the same. Also, in general, it takes additional steps to confirm that a file is correctly
copied when using Robocopy.
Example
A simple Robocopy command is as follows:
This command copies all files and subfolders from the local path C:\inetpub\wwwroot to
the remote path \\server2\c$\inetpub\wwwroot. Files are copied in a restartable mode,
allowing Robocopy to restart the copy if it fails. All file attributes, including security, own-
ership, and auditing attributes, are copied; this will work only when the security attributes
on a file are assigned only to domain or built-in user accounts (such as Administrator).
Syntax
This command’s basic syntax is as follows:
Troubleshooting
Robocopy will provide detailed error messages if any errors occur. Typically, the most
common problem is copying security, ownership, or auditing attributes out of their
context. In other words, do not copy these attributes unless all files and folders have
only security permissions assigned to domain or local built-in user and group
accounts.
Chapter 17: IIS Web Site Management Tasks 351
Description
This script, Iiscnfg.vbs, is included with IIS 6.0 and performs a number of IIS-related
administration tasks. One of its functions can copy a local IIS server’s configuration to
other IIS servers.
Example
The following example copies a local IIS configuration to a server named Server2:
Syntax
This script’s basic syntax for copying settings is as follows:
Troubleshooting
To ensure this script doesn’t run into any major errors, either have the permissions
necessary to perform the script’s task or provide alternate credentials that have the
appropriate permissions. One common mistake is to copy the IIS configuration to a
server that can’t support it. For example, copying the entire IIS configuration from a
server that hosts FTP and Web sites to a server that does not have FTP installed will
result in an impartial configuration on the destination server. Similarly, copying an IIS
configuration does not include copying content: If the source server’s Web site uses
C:\Inetpub\wwwroot as its root path, this path must already exist on the destination
server or a misconfiguration will result.
Chapter 17: IIS Web Site Management Tasks 353
On the CD The sample script can be found on the CD that accompanies this book
at \Chap17\VDirCheck.wsf.
Description
This script, VDirCheck.wsf, will list all Web virtual directories that have Script or
Execute permissions assigned. These virtual directories represent potential security
risks. The script will call special attention to virtual directories that also have Write
permissions, which could potentially allow users or attackers to upload and execute
malicious scripts or executables.
Example
Use this script as follows:
VDirCheck.wsf /computer:server2
This will list all virtual directories having Script or Execute permissions on Server2.
This script can also be used to target multiple servers listed in a file or an entire
organizational unit (OU) of servers. To target servers listed in a file:
VDirCheck.wsf /list:c:\list.txt
VDirCheck.wsf /ou:West
Syntax
This script’s syntax is as follows:
/list:path One and only one of these is required by the script. Use /list
/computer:name to target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to
/container:name
target an organizational unit within Active Directory.
354 Part V: IIS 6.0 Tasks
Troubleshooting
Other than the obvious problems that can arise if you try to use this script without
having the necessary permissions, or if you run the script against a server that doesn’t
have IIS 6.0 installed and at least one Web virtual directory configured, this script
shouldn’t run into any problems.
Chapter 18
FTP and SMTP Site
Management Tasks
In this chapter:
Create FTP Sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Create FTP Virtual Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
Modify SMTP Domain Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
This chapter covers the automation of administration for the File Transfer Protocol
(FTP) and Simple Mail Transport Protocol (SMTP) features of Microsoft® Internet
Information Services (IIS) 6.0. Automating administration tasks is important when
you have more than one server configured identically (such as in a server farm), when
you need to deploy new servers quickly, or when you need to simplify the management
of remote servers.
Most of the scripts in this chapter are provided by Microsoft and are included with
Microsoft Windows Server™ 2003 when IIS 6.0 is installed. For more information about
using these scripts for other administrative tasks (most of them have quite a bit of
functionality built in), consult the Help and Support Center in Windows Server 2003.
355
356 Part V: IIS 6.0 Tasks
Description
This script, Iisftp.vbs, is included with IIS 6.0 and performs a number of FTP-related
administration tasks. Its simpler functions include starting, stopping, and pausing the
FTP services within IIS, and it can also be used to create new FTP sites. If you need to
target multiple servers at one time, use the script Iismultiany.vbs in Chapter 19,
“General IIS Management Tasks,” instead of Iisweb.vbs.
Example
The following example creates a new FTP site that uses C:\Inetpub\Ftproot as its root
path, 21 as its TCP port, and all unassigned IP addresses:
Syntax
This script’s syntax for creating a new FTP site is as follows:
Root Required. Specifies the root path for the new FTP site.
Name Required. Specifies the name of the new FTP site as it appears
in the Internet Information Services console.
/b port You must specify either /b, /i, or both. The /b argument spec-
/i address ifies the TCP port the new FTP site will use; the default is 21.
The /i argument specifies the IP address the new FTP site will
use; the default is to use all unassigned IP addresses. Each
FTP site you create must have a unique port/address
combination.
/s servername Specifies a remote IIS server to target.
/u username Specifies alternate credentials to use when connecting to a
/p password remote IIS server.
Chapter 18: FTP and SMTP Site Management Tasks 357
/dontstart Creates the new FTP site but doesn’t start it. This allows you
to create the site and then set up your desired security
permissions before making the site active.
/isolation Local | AD Sets the new site’s isolation mode to either Local or AD
(Active Directory).
/ADAdmin username When specifying /isolation AD, specifies the Microsoft Active
/ADPass password Directory® user name and password.
Troubleshooting
To ensure that this script doesn’t run into any major errors, have the permissions nec-
essary to perform the script’s task or provide alternate credentials that have the appro-
priate permissions. One common mistake is to specify as a new site name a site that
already exists or to specify a port/address combination that is already used by another
FTP site. Both of these scenarios will result in an error, in which case you’ll need to
rerun the script with different values for the appropriate arguments.
358 Part V: IIS 6.0 Tasks
Description
This script, Iisftpdr.vbs, is included with IIS 6.0 and performs a number of administra-
tion tasks related to FTP virtual directories. If you need to target multiple servers at
one time, use the script Iismultiany.vbs in Chapter 19 instead of Iisftpdr.vbs. Before
you can work with FTP virtual directories, you must first create an FTP site. (See the
previous script for a way to automate that task.)
Note Iisftpdr.vbs will create a single virtual directory. If you need to create a batch
of virtual directories, include Iisftpdr.vbs in a normal batch (.bat) file.
Example
The following example creates a new FTP virtual directory in an FTP site named “FTP
Site”. The virtual directory points to the physical path C:\Inetpub\Ftpuploads, and
the virtual directory alias is \Uploads.
Note that the physical path will be created by this script if the path does not already
exist.
If you already have a virtual path named \Uploads\Users, and you want to add a new
virtual directory named Private to the end of this path—for a path of \Uploads\Users\
Private—you would use the following code:
This new virtual directory would have the physical path C:\Inetpub\Privateroot.
Chapter 18: FTP and SMTP Site Management Tasks 359
Syntax
This script’s syntax for creating a new FTP site is as follows:
Troubleshooting
To ensure that this script doesn’t run into any major errors, have the permissions
necessary to perform the script’s task or provide alternate credentials that have the
appropriate permissions. One common mistake is to specify a site name that doesn’t
exist or a virtual path that doesn’t exist. Both the site name and virtual path must exist
for the command to complete.
360 Part V: IIS 6.0 Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap18\ModSMTP.wsf.
Description
This script, ModSMTP.wsf, will change properties for an SMTP virtual server. The
script will also list available SMTP virtual servers and can target multiple computers.
This script is a good way to reconfigure multiple servers to have a consistent
configuration.
Example
Use this script as follows:
This code will list all SMTP service instances on Server2. You will need a service
instance name to make any modifications to the service:
Note that the service name is case-sensitive. This code modifies the service named
Service1 on the server Server2, setting its AuthAnonymous property to False. Available
properties are:
■ AuthAnonymous
■ AuthBasic
■ AuthMD5
■ AuthNTLM
■ AuthPassport
■ ConnectionTimeout
■ DefaultLogonDomain
■ MaxBandwidth
Chapter 18: FTP and SMTP Site Management Tasks 361
■ MaxConnections
■ MaxEndpointConnections
■ ServerAutoStart
■ SmtpLocalDelayExpireMinutes
■ EnableReverseDNSLookup
■ HopCount
■ MasqueradeDomain
■ SmartHost
■ SmartHostType
Tip You can learn about these properties and their purposes, as well as the valid range
of values for them, in the Microsoft MSDN® Library. Look for “IisSmtpServiceSetting” in
the index.
This script can also be used to target multiple servers listed in a file or an entire
organizational unit (OU) of servers. To target servers listed in a file, use this code:
Syntax
This script’s syntax is as follows:
/list:path One and only one of these is required by the script. Use /list to
/computer:name target a list of computers contained within a text file. Use
/computer to target a single computer. Use /container to target
/container:name
an organizational unit within Active Directory.
/recurse When used with /container, also targets computers contained
within nested OUs.
/ping Verifies the connectivity to all targeted computers prior to attempt-
ing a connection. Using this argument will reduce the timeout wait
when one or more computers cannot be reached on the network.
362 Part V: IIS 6.0 Tasks
/log:path Logs unreachable computer names to the specified file. This file
can then be used later, along with the /list argument, to retry
these computers. Note that a log is created only when used in
conjunction with the /ping argument.
/verbose Causes the script to display more detailed, step-by-step status
messages.
/listsvc Lists all SMTP services on the targeted computers so that you can
determine the names of the available services.
/svc:service These arguments must be used together. Specifies the name of the
/prop:property SMTP service to target (/svc), the property to change (/prop), and
the new value for the property (/val).
/val:new_value
Case "authpassport"
oItem.AuthPassport = WScript.Arguments.Named("val")
Case "connectiontimeout"
oItem.ConnectionTimeout = WScript.Arguments.Named("val")
Case "defaultlogondomain"
oItem.DefaultLogonDomain = WScript.Arguments.Named("val")
Case "maxbandwidth"
oItem.MaxBandwidth = WScript.Arguments.Named("val")
Case "maxconnections"
oItem.MaxConnections = WScript.Arguments.Named("val")
Case "maxendpointconnections"
oItem.MaxEndpointConnections = WScript.Arguments.Named("val")
Case "serverautostart"
oItem.ServerAutoStart = WScript.Arguments.Named("val")
Case "smtplocaldelayexpireminutes"
oItem.SMTPLocalDelayExpireMinutes = WScript.Arguments.Named("val")
Case "enablereversednslookup"
oItem.EnableResverDNSLookup = WScript.Arguments.Named("val")
Case "hopcount"
oItem.HopCount = WScript.Arguments.Named("val")
Case "masqueradedomain"
oItem.MasqueradeDomain = WScript.Arguments.Named("val")
Case "smarthost"
oItem.SmartHost = WScript.Arguments.Named("val")
Case "smarthosttype"
oItem.SmartHystType = WScript.Arguments.Named("val")
End Select
oItem.Put_
If Err <> 0 Then
WScript.Echo " ** Error setting property on " & sName
End If
End if
End If
Next
End If
End if
Troubleshooting
Other than the obvious problems that can arise if you try to use this script without
having the necessary permissions, or if you run the script against a server that doesn’t
have IIS 6.0 installed and an SMTP virtual server configured, you can create a problem
for this script in only one major way—by specifying an invalid value for a property.
Many properties, such as AuthAnonymous, accept only a Boolean (True or False) value.
Specifying a string or integer might result in an error or in unexpected behavior.
Chapter 19
General IIS Management
Tasks
In this chapter:
Run IIS Commands Against Multiple Servers . . . . . . . . . . . . . . . . . . . . . . 366
Back Up the IIS Metabase. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Pause the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Batch-Create POP3 Service Mailboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
This chapter shows you how to automate general Microsoft® Internet Information
Services (IIS) management tasks, particularly across multiple computers. In fact, the
first task I’ll cover in this chapter is how to run almost any IIS task—such as those
presented in Chapter 17, “IIS Web Site Management Tasks,” and Chapter 18, “FTP and
SMTP Site Management Tasks”—against multiple IIS computers that are listed by
name in a text file.
365
366 Part V: IIS 6.0 Tasks
On the CD The sample script can be found on the CD that accompanies this book
at \Chap19\Iismultiany.vbs.
Description
This script, Iismultiany.vbs, is designed to run one of the main IIS 6.0 command-line
tools against multiple computers, making it easier to provision, configure, and man-
age multiple IIS servers that have identical settings (such as those in a Web farm). This
script requires you to modify two elements before running it. This script is designed to
be run on computers running Windows Server 2003, with IIS 6.0 installed.
This script is designed to work with the following Windows Server 2003 IIS manage-
ment commands:
■ Iisback
■ Iiscnfg
■ Iisext
■ Iisftp
■ Iisftpdr
■ Iisvdir
■ Iisweb
Example
Use this script by opening it in a text editor and modifying the information that
appears in boldface here:
Dim sCommand
sCommand = "INSERT IIS COMMAND HERE"
Dim sFile
sFile = "c:\ListOfIISservers.txt"
Chapter 19: General IIS Management Tasks 367
You can include the string %name% in your command syntax. This will be replaced
with the name of the currently targeted server. For example, suppose you want to run
a backup operation using the following command:
Simply insert this string into the script. When the script is used to target a server
named Server1, for example, the actual command executed will be:
This allows the backup name to be customized to match the server name.
Syntax
This script has no command-line syntax. It is intended to be modified as just
described and then executed as is.
Dim sCommand
sCommand = "INSERT IIS COMMAND HERE"
Dim sFile
sFile = "c:\ListOfIISservers.txt"
Troubleshooting
Be sure to test independently each command you intend to use before including it in
this script, because any errors this script encounters will be errors resulting from the
command you specify.
Chapter 19: General IIS Management Tasks 369
Description
This script, Iisback.vbs, is designed to back up the IIS metabase. The metabase
contains all the configuration settings of IIS. Backing up the metabase allows you to
more quickly restore a failed IIS server by recreating your Web sites, FTP sites, and
other configuration items.
Iisback.vbs can be used with the first script in this chapter to back up the metabase on
multiple IIS computers.
Example
Use this script as follows:
You can specify a number of optional arguments (detailed in the next “Syntax” section)
to customize the script’s behavior.
Syntax
This script’s syntax is as follows:
Troubleshooting
Provided the user running the logon script has permission to back up IIS, or that
alternate credentials with those permissions are specified, this script should not
encounter any problems.
Chapter 19: General IIS Management Tasks 371
On the CD The sample script can be found on the CD that accompanies this book
at \Chap19\Pause.vbs.
Description
This script, Pause.vbs, pauses the script for a specified period of time. You might use
this script to cause a logon or other administrative script to wait for a few seconds
while other events are processing.
Example
Use this script as follows:
Pause 10
The script accepts one argument, which is the number of seconds you want it to
pause.
Syntax
This script is intended to be included in, and called from, a larger script based on
Microsoft Visual Basic® Script (VBScript). This script’s syntax is as follows:
Pause iSeconds
Sub Pause(iSeconds)
WScript.Sleep(iSeconds * 1000)
End Sub
The script multiplies your specified number of seconds by 1,000 to achieve the correct
delay period in milliseconds.
372 Part V: IIS 6.0 Tasks
Troubleshooting
This script is unlikely to encounter any problems. If you encounter an error when
using a large value for iSeconds, try using a smaller value and calling the subroutine
multiple times (each time with that smaller value) to achieve the desired pause
duration.
Chapter 19: General IIS Management Tasks 373
On the CD The sample script can be found on the CD that accompanies this book
at \Chap19\BatchPOP.wsf.
Description
This script, BatchPOP.wsf, uses the Windows Server 2003 command-line tool Win-
pop to batch-create new POP3 Service mailbox accounts. This script can be used with
a POP3 service that uses integrated (Microsoft Active Directory® or local) accounts as
well as services that use nonintegrated accounts (in which passwords are stored in an
encrypted file). In the latter case, you must specify a new password that will be used
for all batch-created accounts.
Example
Use this script as follows:
BatchPOP /file:C:\mailboxes.txt
This reads new mailbox names, which must be in the format user@domain, from a file
named C:\mailboxes.txt. To create nonintegrated accounts, specify a password:
Syntax
This script’s syntax is as follows:
/file:filename Required. Specifies the file containing the new user names.
This file must have one user name per line, and names must
be in the format user@domain.
/password:password Optional. Forces the creation of nonintegrated accounts and
assigns the specified password to all new accounts.
374 Part V: IIS 6.0 Tasks
'open file
Dim oFSO, oTS, sName
Set oFSO = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set oTS = oFSO.OpenTextFile(WScript.Arguments.Named("file"))
If Err <> 0 Then
WScript.Echo "** Error opening file."
WScript.Quit
End If
sName = oTS.ReadLine
If WScript.Arguments.Named.Exists("password") then
Set oExec = oShell.Exec("winpop add " & sName & "
/createuser " & WScript.Arguments.Named("password"))
Else
Set oExec = oShell.Exec("winpop add " & sName)
End If
Do While oexec.Status <> 0
WScript.Echo "Creating sName: Status is " & oExec.ExitCode
Loop
Loop
oTS.Close
WScript.Echo "Command completed."
Troubleshooting
If you experience problems, try running the Winpop command manually to create
one new mailbox. You must resolve any problems that occur before this script will
function. Any errors you do find will most likely be an error returned by the Winpop
command, such as those stating that the user specified a password that does not meet
minimum requirements or specified a new mailbox name that already exists. The
script will display this error information when available and continue executing.
Part VI
Advanced Scripting Tools
Chapter 20
User Interface and Databases
In this chapter:
Display HTML Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
Connect to a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
Query a Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
Change Information in a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
Add Information to a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
In this chapter, rather than show you how to automate entire administrative tasks,
I provide you with some functions that you can use to write more advanced scripts of
your own. The functions and subroutines in this chapter are designed to be pasted
into your own scripts, giving your scripts some advanced capabilities without you
needing to write complex scripts yourself.
377
378 Part VI: Advanced Scripting Tools
On the CD The sample script can be found on the CD that accompanies this book
at \Chap20\DisplayHTMLMessage.vbs.
Description
This script, DisplayHTMLMessage.vbs, contains a single function that displays an
HTML-formatted message for a specified number of seconds. The function uses Internet
Explorer to render and display the HTML, and it programmatically controls Internet
Explorer to give you a good deal of control over the message’s appearance and behavior.
Example
Use this script as follows:
This code will display a message box containing the phrase “PLEASE WAIT,” which
will be displayed in red, centered text. The message box will be displayed 10 pixels
below the top of the screen and 15 pixels from the left side of the screen, and will be
200 pixels wide and 150 pixels high. The message will be displayed for 10 seconds.
Syntax
This script is intended to be included in, and called from within, a larger script. This
script’s syntax is as follows:
sHTML Specifies the HTML to display. You can use an HTML editor such as
Microsoft FrontPage to create the HTML for your message.
iTop Specifies the position, in pixels, of the top edge of the window in
relation to the top edge of the screen.
Chapter 20: User Interface and Databases 379
iLeft Specifies the position, in pixels, of the left edge of the window in
relation to the left edge of the screen.
iWidth Specifies the width of the window in pixels.
iHeight Specifies the height of the window in pixels.
iSeconds Specifies the number of seconds the message will display.
The Internet Explorer toolbar and Address Bar are automatically hidden so that the
window’s appearance has the same style as a dialog box.
Troubleshooting
This script will only work if Internet Explorer has not been removed or permanently
disabled; any error messages relating to problems with the Internet Explorer installa-
tion will be associated with line 2 of the subroutine. These errors can be corrected by
properly installing or enabling Internet Explorer.
Note Using the Set Program Access and Defaults utility to disable access to Internet
Explorer will not remove Internet Explorer and will not prevent this script from running.
Internet Explorer does not need to be your default Web browser for this script to function
properly. However, this script works only with Internet Explorer and will not substitute an
alternate Web browser, even if you have specified one as your default Web browser.
380 Part VI: Advanced Scripting Tools
Connect to a Database
On the CD The sample script can be found on the CD that accompanies this book
at \Chap20\ConnectDB.vbs.
Description
This script, ConnectDB.vbs, contains a single subroutine that connects to a Microsoft
Excel, Microsoft Access, or Microsoft SQL Server™ database. This script is intended to
be used in conjunction with QueryDB.vbs, ChangeDB.vbs, and InsertDB.vbs, which
are covered later in this chapter.
Example
Use this script as follows:
The first argument specifies a SQL Server database (as opposed to an Excel or Access
database); the second argument indicates the SQL Server name. The third argument
specifies the database to connect to, and the fourth and fifth specify the user creden-
tials to utilize. The last three arguments are used only when connecting to a SQL
Server database; Excel and Access require only the first two arguments.
Syntax
This script is intended to be included in, and called from within, a larger script. This
script’s syntax is as follows:
sType Specifies the database type. Valid values include sql, access, and excel.
sFile For an Access or Excel database, specifies the file name to open. For a
SQL Server database, specifies the server name to connect to.
sDatabase Used only for SQL Server connections (pass an empty string for Access or
Excel); specifies the database name to open.
Chapter 20: User Interface and Databases 381
sUser Used only for SQL Server connections (pass an empty string for Access or
Excel); specifies the user name to use for the connection.
sPwd Used only for SQL Server connections (pass an empty string for Access
or Excel); specifies the password to use for the connection.
End Sub
Because of the way Microsoft Visual Basic® Script (VBScript) handles object references,
such as the ADO Connection object, you must first declare the variable oConnection and
set it equal to the ADODB.Connection COM object ID. Then you can call the ConnectDB
subroutine. The following code demonstrates proper use of this subroutine:
Dim oConnection
Set oConnection = CreateObject("ADODB.Connection")
ConnectDB "sql","server", "database","user","password"
Troubleshooting
Connecting to Excel or Access databases will rarely result in a problem as long as the
file you specify exists and is accessible to the script. Connecting to a SQL Server data-
base can be more complex; this script is designed to work when the user name and
password are defined as local logons on the SQL Server. Other conditions might
work—for example, to use Windows Integrated authentication with SQL Server, you
might be able to pass empty strings for the user name and password. If you encounter
errors when using the ConnectDB subroutine, contact your SQL Server system admin-
istrator for more information about accessing the server from within a script.
Chapter 20: User Interface and Databases 383
Query a Database
On the CD The sample script can be found on the CD that accompanies this book
at \Chap20\QueryDB.vbs.
Description
This script, QueryDB.vbs, queries information from a database. You must first estab-
lish a connection to the database, which can be done using the ConnectDB.vbs script
described earlier in this chapter.
Example
Use this script as follows:
Dim oRecordset
Set oRecordset = CreateObject("ADODB.Recordset")
QueryDB oConnection, "Titles", "*", ""
This example queries all columns and all records from the Titles table (or Excel
sheet), using a previously opened connection referenced in variable oConnection.
The following example (which is included on the CD that accompanies this book in
Chap20\DatabaseExample.vbs) shows how QueryDB can be used in conjunction
with ConnectDB to list all columns and all rows from a specified SQL Server database
table:
' ***************************************************************
' Using ConnectDB to connect to the database
' ***************************************************************
Dim oConnection
Set oConnection = CreateObject("ADODB.Connection")
ConnectDB "sql","don-laptop", "mydatabase","sqluser","password"
' ***************************************************************
' Using QueryDB to query the database
' ***************************************************************
Dim oRecordset
Set oRecordset = CreateObject("ADODB.Recordset")
QueryDB oConnection, "Titles", "*", ""
384 Part VI: Advanced Scripting Tools
' ***************************************************************
' The functions and subroutines - no need to modify these
' ***************************************************************
Dim sQuery
sQuery = "SELECT " & sColumns & " FROM " & sTable
If sCondition <> "" Then
sQuery = sQuery & "WHERE " & sCondition
End If
End Sub
Note that both the ConnectDB and QueryDB subroutines have been copied and pasted
into this example script.
Chapter 20: User Interface and Databases 385
Syntax
This script is intended to be included in, and called from within, a larger script. This
script’s syntax is as follows:
Dim sQuery
sQuery = "SELECT " & sColumns & " FROM " & sTable
If sCondition <> "" Then
sQuery = sQuery & "WHERE " & sCondition
End If
Because of the way VBScript handles object reference variables, you must declare vari-
able oRecordset and set it equal to the ADODB.Recordset COM object ID prior to calling
QueryDB.
Troubleshooting
Used properly, this script should not run into any problems. If you encounter errors,
ensure that you’re specifying valid table or sheet names (Excel sheet names must
often be specified as “[name$]” to work properly), valid column names (in Excel, the
column name is specified in the first row of the spreadsheet), and valid comparison
conditions. Typically, error messages are specific about what needs to be changed, if
anything goes wrong.
386 Part VI: Advanced Scripting Tools
On the CD The sample script can be found on the CD that accompanies this book
at \Chap20\ChangeDB.vbs.
Description
This script, ChangeDB.vbs, changes information in a database. You must first estab-
lish a connection to the database, which can be done using the ConnectDB.vbs script
described earlier in this chapter.
Example
Use this script as follows:
This example changes the table MyTable, updating a column named ZIP to have the
value 89123. This change occurs for all database rows where the ZIP column contains
89122. Variable oConnection is a previously declared and opened ADODB.Connection
object.
Syntax
This script is intended to be included in, and called from within, a larger script. This
script’s syntax is as follows:
Dim sQuery
sQuery = "UPDATE " sTable & " SET " & sChange
If sCondition <> "" Then
sQuery = sQuery & "WHERE " & sCondition
End If
oConn.Execute sQuery
End Sub
Troubleshooting
Used properly, this script should not run into any problems. If you encounter errors,
ensure that you’re specifying valid table or sheet names (Excel sheet names must
often be specified as “[name$]” to work properly), valid column names (in Excel, the
column name is specified in the first row of the spreadsheet), and valid comparison
conditions. Typically, error messages are specific about what needs to be changed if
anything goes wrong.
388 Part VI: Advanced Scripting Tools
On the CD The sample script can be found on the CD that accompanies this book
at \Chap20\InsertDB.vbs.
Description
This script, InsertDB.vbs, adds information to a database. You must first establish a
connection to the database, which can be done using the ConnectDB.vbs script
described earlier in this chapter.
Example
Use this script as follows:
This example adds a new row to the table MyTable, setting the Name column to be
Don, the ZIP column to be 89123, and the State column to be NV. Note that string
values must be included within single quotation marks, and that all values must be
comma-delimited.
Syntax
This script is intended to be included in, and called from within, a larger script. This
script’s syntax is as follows:
Dim sQuery
sQuery = "INSERT INTO " sTable & " (" & sColumns & ") VALUES (" & sValues & ")"
oConn.Execute sQuery
End Sub
Troubleshooting
Used properly, this script should not run into any problems. If you encounter errors,
ensure that you’re specifying valid table or sheet names (Excel sheet names must
often be specified as “[name$]” to work properly), valid column names (in Excel, the
column name is specified in the first row of the spreadsheet), and valid comparison
conditions. Typically, error messages are specific about what needs to be changed, if
anything goes wrong.
The most common mistake when inserting data into a database is to leave out one
or more columns for which a value is required; the database will not accept the new
row of data unless every required (called non-Nullable) column has a value. Another
common mistake is to provide data of an incorrect type. If the database is expecting
a numeric value for a column, for example, specifying a string value will result in
an error.
Chapter 21
Wrapper Script
In this chapter:
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
Most of the scripts presented in this book were written from a script template, or
wrapper, which provides a consistent set of functionality across these scripts. In this
chapter, I’ll show you how to use that wrapper script to write your own scripts,
helping save time and energy.
On the CD You’ll find the wrapper script on the CD that accompanies this book in
\Chap21\wrapper.wsf.
The wrapper has a number of built-in functions that you can take advantage of:
■ It can query and target all computer names from a specified organizational unit
(OU) in Microsoft Active Directory®. Use the /container: argument to specify the
target OU.
■ When you instruct the script to target an OU, you can include child OUs in it as
well. Include the /recurse argument to have it do so.
■ The script can target all computers listed in a file. Use the /list: argument to
specify the file name containing the computer names to target.
■ The script can target a single computer by using the /computer: argument to
specify the computer name.
391
392 Part VI: Advanced Scripting Tools
■ The script can attempt to ping all targeted computers before attempting to connect
to them. This improves script execution time when one or more computers are
unreachable. Use the /ping argument to activate this feature.
■ In conjunction with the /ping argument, the script can log unreachable com-
puters to a file, and then can be used (along with the /list: argument) to retry
those computers later. Use the /log: argument to activate this feature and
specify a log file name. Within the script, you can log a bad connection using
the LogBadConnect subroutine.
■ The script supports verbose output. Run it with the /verbose argument to
activate this feature, and use the Verbose subroutine within the script to output
verbose text.
■ The script includes built-in functions named QueryWMI() and QueryADSI()
that can be used to query Windows Management Instrumentation (WMI) or
Active Directory Services Interface (ADSI).
■ The script includes built-in functionality for writing information to a text log file.
This functionality is provided by the LogFile subroutine.
Chapter 21: Wrapper Script 393
Overview
Here is the wrapper script in its entirety (only the Microsoft Visual Basic® Script, or
VBScript, portion). The XML formatting associated with the WSF file format has been
left out of this listing:
Sample wrapper.wsf
'make sure we're running from CScript, not WScript
If LCase(Right(WScript.FullName,11)) <> "cscript.exe" Then
If MsgBox("This script is designed to work with CScript, but you are running
it under WScript. " & _
"This script may produce a large number of dialog boxes when running under
WScript, which you may " & _
"find to be inefficient. Do you want to continue anyway?",4+256+32,"Script
host warning") = 7 Then
WScript.Echo "Tip: Run ""Cscript //h:cscript"" from a command-line to make
CScript the default scripting host."
WScript.Quit
End If
End If
'count arguments
Dim iArgs
If WScript.Arguments.Named.exists("computer") Then iArgs = iArgs + 1
If WScript.Arguments.Named.exists("container") Then iArgs = iArgs + 1
If WScript.Arguments.Named.exists("list") Then iArgs = iArgs + 1
If iArgs <> 1 Then
WScript.Echo "Must specify either /computer, /container, or /list arguments."
WScript.Echo "May not specify more than one of these arguments."
WScript.Echo "Run command again with /? argument for assistance."
WScript.Quit
End If
End If
' ----------------------------------------------------------------------
' Sub WorkWithOU
'
' Iterates child objects in OU; calls itself to handle sub-OUs If
' /recurse argument supplied
' ----------------------------------------------------------------------
Sub WorkWithOU(oObject)
For Each oChild In oObject
Select Case oChild.Class
Case "computer"
TakeAction Right(oChild.Name,len(oChild.name)-3)
Case "user"
Case "organizationalUnit"
If WScript.Arguments.Named.Exists("recurse") Then
'recursing sub-OU
Verbose "Working In " & oChild.Name
WorkWithOU oChild
End If
End Select
Next
End Sub
' ----------------------------------------------------------------------
' Sub TakeAction
'
' Makes connection and performs command-specific code
' ----------------------------------------------------------------------
Sub TakeAction(sName)
'verbose output?
Verbose "Connecting to " & sName
'#############################################
'# COMMAND CODE GOES HERE #
'#-------------------------------------------#
'# #
'# #
'#-------------------------------------------#
'# END COMMAND CODE #
'#############################################
End Sub
396 Part VI: Advanced Scripting Tools
' ----------------------------------------------------------------------
' Sub LogBadConnect
'
' Logs failed connections to a log file. Will append if file already exists.
' ----------------------------------------------------------------------
Sub LogBadConnect(sName)
If WScript.arguments.Named.Exists("log") Then
Dim oLogFSO, oLogFile
Set oLogFSO = WScript.CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set oLogFile = oLogFSO.OpenTextFile(WScript.Arguments.Named("log"),8,True)
If Err <> 0 Then
WScript.Echo " *** Error opening log file to log an unreachable computer"
WScript.Echo " " & Err.Description
Else
oLogFile.WriteLine sName
oLogFile.Close
Verbose " Logging " & sName & " as unreachable"
End If
End If
End Sub
' ----------------------------------------------------------------------
' Function TestPing
'
' Tests connectivity to a given name or address; returns true or False
' ----------------------------------------------------------------------
Function TestPing(sName,bPingAvailable)
If Not bPingAvailable Then
WScript.Echo " Ping functionality not available prior to Windows XP"
Exit Function
End If
Dim cPingResults, oPingResult
Verbose " Pinging " & sName
Set cPingResults = GetObject("winmgmts://./root/cimv2").ExecQuery("SELECT *
FROM Win32_PingStatus WHERE Address = '" & sName & "'")
For Each oPingResult In cPingResults
If oPingResult.StatusCode = 0 Then
TestPing = True
Verbose " Success"
Else
TestPing = False
Verbose " *** FAILED"
End If
Next
End Function
' ----------------------------------------------------------------------
' Sub Verbose
'
' Outputs status messages if /verbose argument supplied
' ----------------------------------------------------------------------
Chapter 21: Wrapper Script 397
Sub Verbose(sMessage)
If WScript.Arguments.Named.Exists("verbose") Then
WScript.Echo sMessage
End If
End Sub
' ----------------------------------------------------------------------
' Sub LogFile
'
' Outputs specified text to specified logfile. Set Overwrite=True To
' overwrite existing file, otherwise file will be appended to.
' Each call to this sub is a fresh look at the file, so don’t Set
' Overwrite=True except at the beginning of your script.
' ----------------------------------------------------------------------
Sub LogFile(sFile,sText,bOverwrite)
Dim oFSOOut,oTSOUt,iFlag
If bOverwrite Then
iFlag = 2
Else
iFlag = 8
End If
Set oFSOOut = WScript.CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set oTSOUt = oFSOOut.OpenTextFile(sFile,iFlag,True)
If Err <> 0 Then
WScript.Echo "*** Error logging to " & sFile
WScript.Echo " " & Err.Description
Else
oTSOUt.WriteLine sText
oTSOUt.Close
End If
End Sub
' ----------------------------------------------------------------------
' Function QueryWMI
'
' Executes WMI query and returns results. User and Password may be
' passed as empty strings to use current credentials; pass just a blank
' username to prompt for the password
' ----------------------------------------------------------------------
Function QueryWMI(sName,sNamespace,sQuery,sUser,sPassword)
Dim oWMILocator, oWMIService, cInstances
On Error Resume Next
'create locator
Set oWMILocator = CreateObject("WbemScripting.SWbemLocator")
Else
'user specified
If sUser <> "" And sPassword = "" Then
'execute query
If sQuery <> "" Then
Set cInstances = oWMIService.ExecQuery(sQuery,,48)
If Err <> 0 Then
WScript.Echo "*** Error executing query "
WScript.Echo " " & sQuery
WScript.Echo " " & Err.Description
Set QueryWMI = Nothing
Chapter 21: Wrapper Script 399
Exit Function
Else
Set QueryWMI = cInstances
End If
Else
Set QueryWMI = oWMIService
End If
End Function
' ----------------------------------------------------------------------
' Function QueryADSI
'
' Executes ADSI query. Expects variable sQuery to include a COMPLETE
' query beginning with the provider LDAP:// or WinNT://. The query String
' may include a placeholder for the computer name, such as "%computer%".
' Include the placeholder in variable sPlaceholder to have it replaced
' with the current computer name. E.g.,
' sQuery = "WinNT://%computer%/Administrator,user"
' sPlaceholder = "%computer%
' Will query each computer targeted by the script and query their local
' Administrator user accounts.
' ----------------------------------------------------------------------
Function QueryADSI(sName,sQuery,sPlaceholder)
Dim oObject
sQuery = Replace(sQuery,sPlaceholder,sName)
On Error Resume Next
Verbose " Querying " & sQuery
Set oObject = GetObject(sQuery)
If Err <> 0 Then
WScript.Echo " *** Error executing ADSI query"
WScript.Echo " " & sQuery
WScript.Echo " " & Err.Description
Set QueryADSI = Nothing
Else
Set QueryADSI = oObject
End If
End Function
400 Part VI: Advanced Scripting Tools
Capabilities
The wrapper script’s /list:, /container:, /computer:, /recurse, /ping, and /log: function-
ality requires no coding on your part. Simply locate the following sections of the
wrapper script:
'#############################################
'# COMMAND CODE GOES HERE #
'#-------------------------------------------#
'# #
'# #
'#-------------------------------------------#
'# END COMMAND CODE #
'#############################################
Then place your code in between these two sections. The variable sName is predefined
and will contain the currently targeted computer. Your code will be called once for
each targeted computer, and your code must use sName to connect to the targeted
computer. If /ping is used, your code will not be called for unreachable computers.
Within your code, you can use any of the script’s four built-in functions and subroutines
to make your scripting job a bit easier.
Querying WMI
You can quickly query WMI by using the QueryWMI function. Its basic syntax is this:
QueryWMI(sName,sNamespace,sQuery,sUser,sPassword)
The sName argument should be replaced by the variable sName, passing the name of
the currently targeted computer. The argument sNamespace is the WMI namespace,
such as root\cimv2. The argument sQuery stands for the WMI query you want to
execute. Arguments sUser and sPassword can be passed as empty strings to use the
current user’s credentials; specify a user name in sUser and leave sPassword empty to
have the script prompt for the user’s password. Here is an example:
This code will query all instances of Win32_Process from the root\cimv2 namespace,
connecting to each targeted computer using the account DOMAIN\User and prompting
for the password on each connection. You can then add code similar to the following:
This code will output the processes running on each targeted computer.
Chapter 21: Wrapper Script 401
Querying ADSI
The QueryADSI function works similarly to the QueryWMI function:
QueryADSI(sName,sQuery,sPlaceholder)
Use the variable sName in place of the sName argument to pass the current computer
name. Your ADSI query goes in the sQuery argument. You might also pass a string in
sPlaceholder; any occurrences of sPlaceholder in sQuery will be replaced with sName.
For example, suppose you call the function as follows:
Your query will be run for each targeted computer. If the first targeted computer is
ServerA, your query will execute as LDAP://cn=ServerA,ou=Computers,dc=company,
dc=com, with the %comp% placeholder replaced with the currently targeted computer’s
name.
Specify a complete path and file name for sFile as well as the log message for sText. If
you specify True for bOverwrite, any existing file of the same name will be overwritten.
If you specify False, the script will attempt to append the new entry to a file if one
exists.
The wrapper script does not include an argument that enables the script user to
specify a log file. If you would like an /output: argument added, locate the following
section of the script:
This code illustrates how to use the LogBadConnect subroutine: simply pass it the
sName variable to add the currently targeted computer to the bad connection log,
provided the script was run with the /log: argument.
Verbose Output
If the user running the script specifies the /verbose argument, she will expect the
script to output detailed status and progress information. To add this capability to
your script, use the Verbose subroutine, as shown in this example:
This code will provide notification that the script is attempting a connection. This
notification is displayed only if the /verbose argument is supplied when the script
is run.
Part VII
Appendixes
Appendix A
URLs for Online Materials
This appendix contains URLs for additional scripting materials that you can find
online. Note that Web URLs often change; in the event that any of the URLs listed in
this appendix are inaccessible, try searching for the resources using a search engine
such as Google or MSN®.
In this appendix:
Scripting-Related Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Scripting-Related Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
Scripting-Related Resources
■ http://www.ScriptingAnswers.com My own Web site containing sample
scripts, discussions related to scripting and automation, tutorials, training vid-
eos, and so forth
■ http://www.microsoft.com/technet/scriptcenter/default.mspx The Microsoft
Script Center, which contains hundreds of sample scripts, tutorials, access to
scripting-related webcasts, and other scripting resources
■ http://myitforum.techtarget.com An open forum with a number of scripting-
related resources
■ http://cwashington.netreach.net/main/default.asp?topic=news A repository
of sample scripts written in various scripting languages
■ http://desktopengineer.com Contains a variety of tools related to administra-
tion, including scripts and command-line tools
■ http://groups.msn.com/windowsscript/_homepage.msnw?pgmarket=en-us A
discussion forum, on MSN Groups, focused on Microsoft® Windows® scripting
topics
405
406 Part VII: Appendixes
Scripting-Related Downloads
■ http://www.microsoft.com/technet/scriptcenter/tools/wmimatic.mspx Script-
omatic, a tool that writes sample WMI scripts
■ http://www.microsoft.com/technet/scriptcenter/tools/admatic.mspx ADSI
Scriptomatic, a tool that writes sample ADSI scripts
■ http://www.microsoft.com/technet/scriptcenter/tools/twkmatic.mspx Tweak-
omatic, a tool that writes scripts that tweak various operating system settings
■ http://www.microsoft.com/technet/scriptcenter/tools/logparser
/default.mspx Log Parser, a tool that extracts information from various types
of log files
■ http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sdbug
/Html/sdbug_1.asp The Microsoft Script Debugger
■ http://www.microsoft.com/downloads/details.aspx?FamilyId=C717D943-
7E4B-4622-86EB-95A22B832CAA&displaylang=en Windows Script Host ver-
sion 5.6
■ http://www.microsoft.com/downloads/details.aspx?FamilyId=E7877F67-
C447-4873-B1B0-21F0626A6329&displaylang=en The Windows Script
Encoder
■ http://www.microsoft.com/downloads/details.aspx?FamilyId=408024ED-
FAAD-4835-8E68-773CCC951A6B&displaylang=en The Windows Script
Component Wizard
■ http://www.microsoft.com/downloads/details.aspx?FamilyId=01592C48-
207D-4BE1-8A76-1C4099D7BBB9&displaylang=en The Windows Script 5.6
Documentation
Appendix B
Troubleshooting Common
Problems
In this appendix:
Checking the Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
Modifying Remote Profile-Specific Information . . . . . . . . . . . . . . . . . . . 408
Checking Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
Even though I’ve provided relevant troubleshooting information with each script or
tool discussed in this book, I offer a few basic additional troubleshooting steps in this
appendix that you can follow to help solve virtually any problem related to scripting
or automation.
All the scripts in this book have been successfully tested in the target environment
(usually a Microsoft® Windows Server™ 2003 environment with Microsoft Windows®
XP Professional client computers), but variations in the configuration of your environ-
ment might result in problems running particular scripts.
If you’re receiving an error message of any kind, ensure that you can perform the exact
same task manually, using the same computers and user credentials that the script was
using. For example, if you’re trying to run a script on your computer running Windows
XP to add users to a Microsoft Active Directory® domain, attempt to perform the same
407
408 Part VII: Appendixes
task manually: open the necessary administrative tool on your computer running
Windows XP and try to add a user to the same Active Directory domain. If you cannot
perform the task manually, the script is also unlikely to succeed.
Avoid testing under circumstances different from those the script runs under. For
example, if you are running a script that attempts to remotely change the local Admin-
istrator password on a specific computer, and that script is having problems, you can-
not accurately test the situation by manually changing the Administrator password
directly on the specified remote computer. The fact that you are not manually per-
forming the task remotely, as the script is trying to do, changes the circumstances and
will change your results.
Checking Permissions
Problems with permissions cause the most errors when running scripts. Remember
that the user account used to run the script (which would be your logged-on user
account or, if you use a tool like Runas to specify alternate credentials, the account
represented by those credentials) must have permission to accomplish the task the
script is trying to perform. Often, this means having local Administrator permissions
on each computer targeted by the script. When in doubt, always attempt to remotely
perform the task the script is trying to perform to ensure that you have sufficient per-
missions to do so.
Getting Help
If you need additional help troubleshooting a particular script-related problem, con-
sider posting a message in the Forums on http://www.ScriptingAnswers.com. The
Forums are freely accessible (registration is required) and consist of a large commu-
nity of users with varying levels of scripting experience. Generally, someone can help
figure out the problem, offer a workaround, or offer a better solution.
Index
A
Access user accounts
adding contact accounts, 300 adding contact accounts, 302–303
adding user accounts, 295 adding from database, 297–298
database changing attributes for multiple users, 307
changing information, 386–387 deleting published certificates, 312
connection, 380–382 disabling, 309–310
inserting information, 388–389 expiring, 317–318
querying, 383–385 expiring passwords, 314–315
accounts listing unchanged passwords, 320
contact, adding from database, 300–304 unlocking locked users, 322
local, changing passwords, 125–128 wrapper script querying, 401
user Advanced Attributes dialog box, 172
adding from database, 295–299 Advanced Security Settings dialog box, 168
attribute change for multiple users, 305–307 antivirus software, script blocking, 15
deleting published certificates, 311–312 ArchiveLogs.wsf script, 243–246
disabling, 308–310 archiving security logs, 243–246
expiring, 313–318 attributes, user accounts, changing for multiple users,
old password listing, 319–320 305–307
unlock locked users, 321–322 auditing
Active Directory, user accounts, deleting published installed hardware, 85–88
certificates, 311–312 Internet Explorer configuration, 89–92
Active Directory Services Interface. See ADSI (Active listing event logs, 81–84
Directory Services Interface) listing installed hotfixes, 77–80
adapters, network, listing configuration, 93–96 network adapter configuration listing, 93–96
AddContacts.wsf script, 300–304 scheduled tasks list, 101–104
AddUsers.wsf script, 295–299 security logs, archiving, 243–246
Adersoft Web site, 28 service packs installed, 97–100
Adersoft VBSEdit Web site, 7, 28 software installed, 105–108
Admin Script Editor Web site, 7, 29 automation, 3–4
administrators command-line tools, 7–8
automation, 3–4 WSH (Windows Script Host), 4–7
command-line tools, 7–8
WSH (Windows Script Host), 4–7
files, taking ownership, 168–171 B
ADO, user accounts backups
adding contact accounts, 302–303 CA (Certificate Authority), 247
adding from database, 297–298 command-line arguments, 248
ADSI (Active Directory Services Interface), 17, 225 database, 253–255
computer names, 42 example, 250
FSMO roles, listing domain controller holders, function, 248
225–226 manually, 247
logon scripts, checking user group membership, 325 resources, 249
passwords, changing for local accounts, 127 troubleshooting, 249
IIS metabase, 369–370
409
410 batch-create POP3 Service mailbox accounts