Archive

Posts Tagged ‘Scripts’

Service and Scheduled Task User Manager

July 19, 2010 35 comments

Sometimes, SOX regulations, customer agreement or your boss, forces you to have the password periodically changed for all service accounts and/or accounts running scheduled tasks. So either you have a detailed list of who (the user account) runs what (the service or scheduled task) where (on which computer), and manually change the password at the GUI, or you create a script to help you do the job.

A friend of mine, asked me to help him out and write the script he needed. I thought of creating a script that asks the user for input (account name, new password and a list of computers) and then runs against all the computers in the list and changes the password accordingly… but wouldn’t it be nicer to have a nifty application that does all that, and that you wouldn’t have to edit a text file, or type-in all the parameters each time you want to run the process but with a different set of arguments?

So I decided to write the application. The list of requirements included:

  • The computer list should be easy to manage, and the user should be able to easily add a computer to the list, or a pre-created list from a text file, or even directly from an Active Directory container.
  • The process results should be easy to understand, and even available to export and save for future references.
  • Have an option to manage only services, only scheduled tasks or both.
  • Have an option to restart the services after the password was changed.
  • Have an option to change the user account running the services and/or scheduled tasks.
  • Have a “dry-run” option that would only show the objects (services and scheduled tasks) that their credentials would have been changed.
  • Have an option to quickly connect using Remote Desktop to a selected computer in the list, and to edit the properties of scheduled task listed in the results.

The result from this list, together with other ideas and suggestions that came along the way is SSTUM (Service and Scheduled Task User Manager).

I think it’s easy to use, and the GUI is pretty much self explanatory:

Service and Scheduled Task User Manager

AddComputers ContextMenu

 

1. Add computers to the list. you can add a specific computer name, a list of computers from an Active Directory container or from a csv or text file) using the buttons in the Computer List box, right-click the list area and use the context menu, or drag-and-drop a csv or a text file to the computers list area.

 

Note: When using the specific computer option you can use a comma (“,”) to add many computers or an asterisk (“*”) to be used with a search filter to add computers from Active Directory. As a combined example: by typing in “SQL*,*TEST” in the Add a specific computer box, you will be adding to the list all computer accounts in Active Directory that start with “SQL” and all computer accounts that end with “TEST”.

2. Type-in the Current User that you want to change it’s password on all the listed computers, type in the New User if you want the change the user account running the services and scheduled tasks (or type-in the same account as in the current user text box, to leave the account information unchanged)

3. Enter the new password, and type it again in the validate field.

4. Select to Manage Scheduled Tasks, Manage Services and whether to Restart the services after the password was changed or not.

5. Click the Report Objects for a “dry-run”, or the Change Credentials to run the process and actually change the credentials for the selected objects (Services and Scheduled Tasks) on the listed computers.

Note: For the Report Objects option, you need only the Current User information.

Results ContextMenu

 

6. You can right-click the Results pane to quickly connect to a computer using Remote Desktop, to open the Task Properties window, or to export the results report to a CSV or an XML file to be later opened as an XML table in Excel.

 

 

SSTUM uses TaskScheduler.dll from http://www.codeproject.com/KB/cs/tsnewlib.aspx and dsuiext.dll from the Active Directory Service Interfaces, both included in the downloadable zipped file.

Download SSTUM.zip
Please note it requires you to have at least .NET Framework 2.0 installed

Script: Exchange Mailbox Statistics Report

April 25, 2010 13 comments

A colleague asked me if I had any script in my repository that will create him a detailed report of users, mailboxes and their quota limits. I didn’t have one, so I told him I’d write it for him.

The first thing that came into my mind was the Get-MailboxStatistics PowerShell cmdlet. But then he said that the environment he needed the script for, was a Windows 2003 Domain with Exchange 2003. So I decided I’d do it VBS style.

The details he needed for the report were not only from the Exchange Mailbox but also from the Active Directory:

Property Where to get it from
Account Name Active Directory: samAccountName
User Principal Name Active Directory: userPrincipalName
Display Name Active Directory: displayName
Email Address Active Directory: mail
Issue Warning Active Directory: mDBStorageQuota *
Prohibit Send Active Directory: mDBOverQuotaLimit *
Prohibit Send and Receive Active Directory: mDBOverHardQuotaLimit *
Limit Status Exchange: StorageLimitInfo
Mailbox Size Exchange: Size
Total Items Exchange: TotalItems
Mailbox Location Exchange: ServerName + StorageGroupName + StoreName

 

So I started with an ADSI query to the configurationNamingContext to get the Exchange Servers listed in Active Directory.

(&(objectCategory=msExchExchangeServer)(objectClass=msExchExchangeServer))

For each server, a WMI query to the Exchange_Mailbox Class under the  /root/MicrosoftExchangeV2 namespace to get the StorageLimitInfo, Size, TotalItems, ServerName, StorageGroupName, StoreName and the MailboxDisplayName.

And for each mailbox, query the Active Directory for the additional required details (samAccountName, userPrincipalName, displayName, mail, mDBStorageQuota, mDBOverQuotaLimit and the mDBOverHardQuotaLimit). I used the legacyExchangeDN to match the mailbox to the user account in Active Directory.

(&(ObjectClass=user)(ObjectCategory=person)(legacyExchangeDN=" & legacyExchangeDN & "))

* But then, It got to me that the user may not have specific quota limits set to his user in the Active Directory, and that those settings would be inherited from the mailbox store.

So I added an ADSI query to get the information from the Mailbox Stores,

(&(objectClass=msExchPrivateMDB)(!objectClass=msExchPrivateMDBPolicy))

and put the needed values (mDBStorageQuota, mDBOverQuotaLimit and mDBOverHardQuotaLimit) into to a key-paired Dictionary Object (like a Hashtable). Then, when a user had the mDBUseDefaults set to true, I’d pull the information from the dictionary using his homeMDB property. Actually what I used was the value of:

GetObject("LDAP://" & oRs.Fields("homeMDB")).cn

 

After a few dry runs, I came across mailboxes that failed to be fully reported. I did some debugging (wscript.echo this and wscript.echo that), and noted that I forgot to handle disconnected mailboxes. So by checking if the DateDiscoveredAbsentInDS property had a value I was able to separate the “connected” from the “disconnected” mailboxes.

The script could still be tweaked for better performance and could use a bit more of logging, but I think it’s good enough to share here and definitely meets my colleague needs.

You can download the full script from here or here.

Just remember to run it using the cscript engine:

cscript //NoLogo ExchMailBoxStats.vbs

 

Notes:

  • You will need administrative rights on the Exchange Server to connect to it using WMI.
  • The CSV report will be created in the format of ExchMailBoxStats.yyyyMMdd.csv and located on the same folder as the ExchMailBoxStats.vbs is on.

Windows PowerShell Quick Reference

April 23, 2010 Leave a comment

Windows PowerShell Quick Reference

 

Microsoft has released a Quick-reference guide to commonly-used Windows PowerShell commands.

For best results, open the file in Microsoft Word, print the contents to legal-sized paper (8 inches by 14 inches), and fold the resulting printout in half, making a four-page booklet.

 

Download: Windows PowerShell Quick Reference.

 

Related Download:
Windows PowerShell 1.0 Graphical Help File (including cmdlet help and the About topics) in a fully-searchable, graphical format (a standard Windows .chm file). Also included in the help file is the VBScript to Windows PowerShell Conversion Guide and a collection of PowerShell Tips of the Week.

 

Related Video:
How Do I: Windows PowerShell 2.0?
Explore how Windows PowerShell 2.0 can help increase the productivity of IT professionals by providing a powerful, complete scripting language to automate repetitive tasks and conduct remote troubleshooting. It delivers a growing set of cmdlets that can be used to manage Windows–based PCs and servers, and it can be easily extended.

 

PowerShell Code Repositories:

 

Happy scripting.

VBScript Tools and Links

March 6, 2010 Leave a comment

 

VBScript

Here are a bunch of tools and links you’ll find useful if you are (or want to get) into scripting in VBS.

 

Code Collections:

TechNet Script Center Sample Scripts
Sample scripts found in the TechNet Script Center Repository.

Script Center All-in-One
Script Center All-in-One features over 160 scripting-related articles collected in a single .CHM file. This collection features all of the Tales From the Script and Office Space columns.

Sesame Script, 2005-2007
The complete collection of Sesame Script, the beginning scripting column published in the TechNet Script Center in a fully-searchable help file, with individual topics arranged by category.

SMS 2003 Scripting Guide
The SMS 2003 Scripting Guide provides over 40 scripts, ranging from tasks such as creating advertisements to running queries. It explains the basics of SMS objects, WMI, and VBScript through a series of ‘How To’ examples.

 

Code Generators:

Scriptomatic 2.0
Utility that helps you write WMI scripts for system administration.
Scriptomatic 2.0 isn’t limited to writing just VBScript scripts; instead, Scriptomatic 2.0 can write scripts in Perl, Python, or JScript as well. In addition, Scriptomatic 2.0 gives you a host of new output formats to use when running scripts, including saving data as plain-text, as a stand-alone Web page, or even as XML. Scriptomatic 2.0 handles arrays, it converts dates to a more readable format, and it works with all the WMI classes on your computer; on top of all that, it also writes scripts that can be run against multiple machines.

ADSI Scriptomatic
The ADSI Scriptomatic is designed to help you write ADSI scripts; that is, scripts that can be used to manage Active Directory. The ADSI Scriptomatic also teaches you an important point about ADSI scripting: like WMI, there are consistent patterns to ADSI scripts.

WMI Code Creator v1.0
The WMI Code Creator tool allows you to generate VBScript, C#, and VB .NET code that uses WMI to complete a management task such as querying for management data, executing a method from a WMI class, or receiving event notifications using WMI.
The tool is meant to help IT Professionals quickly create management scripts and to help developers learn WMI scripting and WMI .NET. The tool helps take the complexity out of writing code that uses WMI and helps developers and IT Professionals understand how powerful and useful WMI can be for managing computers.
Using the tool, you can query for management information such as the name and version of an operating system, how much free disk space is on a hard drive, or the state of a service. You can also use the tool to execute a method from a WMI class to perform a management task. For example, you can create code that executes the Create method of the Win32_Process class to create a new process such as Notepad or another executable. The tool also allows you to generate code to receive event notifications using WMI. For example, you can select to receive an event every time a process is started or stopped, or when a computer shuts down.
The tool also allows you to browse through the available WMI namespaces and classes on the local computer to find their descriptions, properties, methods, and qualifiers

HTA Helpomatic
The HTA Helpomatic is a utility that helps script writers create HTML Applications (HTAs). HTAs enable you to provide a graphical user interface for your scripts, an interface that can include anything from list boxes to radio buttons to checkboxes. The HTA Helpomatic includes sample VBScript code and sample HTML code showing you how to do things like add a button to an HTA. Equally important, the Helpomatic also shows you how you can run a script any time that button is clicked. As an added bonus, the Helpomatic enables you to modify the scripts and HTML code and test those modifications in the utility itself.

Tweakomatic
Tweakomatic is a utility that writes scripts that enable you to retrieve and/or configure Windows and Internet Explorer settings.

 

Language Documentation and References:

Windows Script 5.6 Documentation
Extensive reference and conceptual documentation for all of Microsoft Windows Script Technologies, including VBScript, JScript and WSH.

VBScript Quick Reference
Four-page booklet Word Document reference guide to commonly-used VBScript commands.

VBScript (Visual Basic Script)
Microsoft Visual Basic Scripting Edition (VBScript) is an easy-to-use scripting language that enables system administrators to create powerful tools for managing their Windows based computers.

WSH (Windows Script Host)
Windows Script Host (WSH), a feature of the Microsoft® Windows® 2000 family of operating systems, is a powerful multi-language scripting environment ideal for automating system administration tasks. Scripts running in the WSH environment can leverage the power of WSH objects and other COM-based technologies that support Automation, such as Windows Management Instrumentation (WMI) and Active Directory Service Interfaces (ADSI), to manage the Windows subsystems that are central to many system administration tasks.

WMI (Windows Management Instrumentation)
Windows Management Instrumentation (WMI) is the primary management technology for Microsoft Windows operating systems. It enables consistent and uniform management, control, and monitoring of systems throughout your enterprise. WMI allows system administrators to query, change, and monitor configuration settings on desktop and server systems, applications, networks, and other enterprise components.

ADSI (Active Directory Service Interfaces)
Administering a directory service often involves numerous repetitive tasks such as creating, deleting, and modifying users, groups, organizational units, computers, and other directory resources. Performing these steps manually by using graphical user interface (GUI) tools is time-consuming, tedious, and error prone. A key to reducing time consumption, tedium, and errors when administering a directory is automating repetitive tasks by using scripts.
Active Directory Service Interfaces (ADSI) is the technology that allows you to create custom scripts to administer directories. ADSI-enabled scripts are capable of performing a wide range of administrative tasks involving network directories such as the Active Directory directory service.

PerfMon BlackBox

February 20, 2010 5 comments

BlackBoxWhen an airplane crashes, the first thing to do (after searching for survivors of course) is to search for the “blackbox” since it would contain vital information about what might have caused the plane to crash. You can apply this technique on your servers as well.PerfMon

The “PerfMon BlackBox” is an always-running capture of key performance counters. So when a server crashes, hangs or starts to slow down significantly, you can take the collected data (the blg file) and analyze it for memory leaks or other unexpected resource consumption.

For this, you’ll need a set of two files. One (BlackBox_Counters.txt) containing the list of performance counters to be collected, and a second (BlackBox.cmd) containing the script set of commands to create the data collector using logman.exe.

BlackBox_Counters.txt:

\Cache\Dirty Pages
\Cache\Lazy Write Flushes/sec
\LogicalDisk(*)\% Free Space
\LogicalDisk(*)\% Idle Time
\LogicalDisk(*)\Avg. Disk Bytes/Read
\LogicalDisk(*)\Avg. Disk Bytes/Write
\LogicalDisk(*)\Avg. Disk Queue Length
\LogicalDisk(*)\Avg. Disk sec/Read
\LogicalDisk(*)\Avg. Disk sec/Write
\LogicalDisk(*)\Current Disk Queue Length
\LogicalDisk(*)\Disk Bytes/sec
\LogicalDisk(*)\Disk Reads/sec
\LogicalDisk(*)\Disk Transfers/sec
\LogicalDisk(*)\Disk Writes/sec
\LogicalDisk(*)\Free Megabytes
\Memory\% Committed Bytes In Use
\Memory\Available MBytes
\Memory\Cache Bytes
\Memory\Commit Limit
\Memory\Committed Bytes
\Memory\Free & Zero Page List Bytes
\Memory\Free System Page Table Entries
\Memory\Pages Input/sec
\Memory\Pages Output/sec
\Memory\Pages/sec
\Memory\Pool Nonpaged Bytes
\Memory\Pool Paged Bytes
\Memory\System Cache Resident Bytes
\Memory\Transition Pages RePurposed/sec
\Network Inspection System\Average inspection latency (sec/bytes)
\Network Interface(*)\Bytes Received/sec
\Network Interface(*)\Bytes Sent/sec
\Network Interface(*)\Bytes Total/sec
\Network Interface(*)\Current Bandwidth
\Network Interface(*)\Output Queue Length
\Network Interface(*)\Packets Outbound Errors
\Network Interface(*)\Packets Received/sec
\Network Interface(*)\Packets Sent/sec
\Network Interface(*)\Packets/sec
\Paging File(*)\% Usage
\PhysicalDisk(*)\Avg. Disk Queue Length
\PhysicalDisk(*)\Avg. Disk sec/Read
\PhysicalDisk(*)\Avg. Disk sec/Write
\PhysicalDisk(*)\Current Disk Queue Length
\PhysicalDisk(*)\Disk Bytes/sec
\PhysicalDisk(*)\Disk Reads/sec
\PhysicalDisk(*)\Disk Writes/sec
\Process(*)\% Privileged Time
\Process(*)\% Processor Time
\Process(*)\Handle Count
\Process(*)\ID Process
\Process(*)\IO Data Operations/sec
\Process(*)\IO Other Operations/sec
\Process(*)\IO Read Operations/sec
\Process(*)\IO Write Operations/sec
\Process(*)\Private Bytes
\Process(*)\Thread Count
\Process(*)\Virtual Bytes
\Process(*)\Working Set
\Processor Information(*)\% of Maximum Frequency
\Processor Information(*)\Parking Status
\Processor(*)\% DPC Time
\Processor(*)\% Interrupt Time
\Processor(*)\% Privileged Time
\Processor(*)\% Processor Time
\Processor(*)\% User Time
\Processor(*)\DPC Rate
\Server\Pool Nonpaged Failures
\Server\Pool Paged Failures
\System\Context Switches/sec
\System\Processor Queue Length
\System\System Calls/sec
\TCPv4\Connection Failures

BlackBox.cmd:

set “LogName=BlackBox”
set “LogsPath=D:\Perflogs”
set “CountersFile=BlackBox_Counters.txt”

logman query |find /i /c “%LogName%”
if ERRORLEVEL 1 goto CreateLog

:UpdateLog
logman update %LogName% -v nnnnnn -cf “%~dp0%CountersFile%” -si 00:01:00 -f bincirc -o “%LogsPath%\%LogName%_%COMPUTERNAME%” -max 1024
goto StartLog

:CreateLog
logman create counter %LogName% -v nnnnnn -cf “%~dp0%CountersFile%” -si 00:01:00 -f bincirc -o “%LogsPath%\%LogName%_%COMPUTERNAME%” -max 1024

:StartLog
logman start %LogName%

:ClearOldLogs
forfiles /p %LogsPath% /m *.blg /d -7 /c “cmd /c del /q @path”

Now you can set your server’s “PerfMon BlackBox” by putting both files in a folder under your %USERDOMAIN%\NETLOGON folder, then create a new GPO, and assign the BlackBox.cmd script as the computer startup script. This way, whenever a server boots up, it will cerate/update the BlackBox collector and run it.

Note: The last line of the script file (under ClearOldLogs) is responsible for deleting blg files older than 7 days, so your disk is not bloated with old and irrelevant counter files.

Before you go and analyze the counters using perfmon, I recommend you use a set of registry tweaks that will make your life working with PerfMon a little easier.

PerfMonTweaks.reg:

Windows Registry Editor Version 5.00

#http://support.microsoft.com/kb/281884
#The Process object in Performance Monitor can display Process IDs (PIDs)
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance]
“ProcessNameFormat”=dword:00000002

#http://support.microsoft.com/kb/300884
#Display Comma Separators in the Windows Performance Tool
[HKEY_CURRENT_USER\Software\Microsoft\SystemMonitor]
“DisplayThousandsSeparator”=dword:00000001

#http://support.microsoft.com/kb/283110
#Vertical lines are displayed in the Sysmon tool that obscure the graph view
[HKEY_CURRENT_USER\Software\Microsoft\SystemMonitor]
“DisplaySingleLogSampleValue”=dword:00000001

And if you don’t know how, you can always use PAL to analyze the performance logs. It generates an HTML based report which graphically charts important performance counters and show alerts when thresholds are exceeded. Just remember PAL is not a replacement of traditional performance analysis, but it automates the analysis of performance counter logs enough to save you time.

Performance Analysis of Logs (PAL) Tool

Related reading: