Windows IT Pro is the leading independent community for IT professionals deploying Microsoft Windows server and client applications and technologies.
  
  
  Advanced Search 


June 28, 2007

Dig Out by Digging Into PowerShell

Turn complex and repetitive tasks into simple operations
RSS
Subscribe to Windows IT Pro | See More Systems Administration Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!
SideBar    PowerShell Pointers

Download the Code Here

The Where-Object cmdlet filters the data based on the expression defined in the curly brackets. As with ForEach, you use $_ to reference the current object within the collection. In this case, the collection is made up of the event entries. You can also use $_ to reference specific properties within the object. For example, the expression uses $_ to reference the TimeGenerated property. You reference an object's properties by adding a period followed by the property name. The expression then uses the greater than (-gt) operator to compare the TimeGenerated property's value to the value in the $date variable. As a result, the $events variable includes only events generated within the last 24 hours.

Next, I use the $events variable to access the events. The statement in callout D passes the content in $events down the pipeline to a ForEach cmdlet. The ForEach expression consists of a Out-File cmdlet that outputs the event content to AppEvents.txt. The Out-File cmdlet includes the -Append option to ensure that each event is added to the file without overwriting any events. In addition, the cmdlet includes the -InputObject option, which uses the $_ symbol and property names to specify the types of data to save to the file. As a result, the output file includes only the timestamp, entry type, source, and message associated with each event.

Finally, the code in callout E calls the FormatEntryType function and passes the AppEvents.txt file's pathname to the function. As you saw earlier, this function retrieves the data from the first text file, updates the data, and adds it to the AppEvents_EntryTypes.txt file. Figure 1 shows a sample event from AppEvents_EntryTypes.txt.

To run RetrieveAppEvents.ps1 from the PowerShell command prompt, you simply need to type the script's pathname and press Enter. So, the command might look like

c:\scripts\retrieveappevents.ps1 

However, PowerShell prevents you from running scripts by default. To modify the default behavior, you must change the Power-Shell security settings. To get started, you can change the settings by entering the command

set-executionpolicy remotesigned 

Thereafter, you can run scripts that you create, but any other script must be digitally signed.

Now that you've seen your first script, you should be familiar with many of the basic PowerShell concepts. As you'll see, a lot of these concepts apply to other scripts.

DisableUser.ps1
DisableUser.ps1 in Listing 2 disables user accounts in AD. As callout A shows, I begin this script by using the Param keyword to define a parameter ($sam) that passes in the user account that's entered on the command line when the script is run. When using this keyword, you have several options:

  • You can use only the Param keyword and the name of the parameter in parentheses.

  • You can define a default value in case no value is specified when running the script.

  • You can use the Throw keyword (as I've done here) to return an error message when no value is specified. When returning an error message, you must enclose the Throw keyword and message in parentheses and precede the parentheses with a dollar sign.

The code at callout B locates the user account in AD. This code begins by creating an object that searches the directory. To create the object, I use the New-Object cmdlet with the DirectorySearcher class in the DirectoryServices namespace. (For information about the DirectoryServices namespace, go to http://msdn2.microsoft.com/en-us/library/ system.directoryservices.aspx.) I then assign the object to the $ds variable.

Next, I create a filter on the $ds object by setting the object's Filter property ($ds.filter). The filter is based on the Active Directory Service Interfaces (ADSI) attributes defined after the equal sign (=). The filter removes all values except those that conform to the attribute definitions. As a result, the filter returns a user account that is part of the person object category and the user object class and that has a SAM name that matches the one specified in the $sam parameter.

After creating the filter, I use the FindOne method of the $ds object ($ds.findOne()) to retrieve the user account. I assign the account to the $dn variable.

The code in callout C defines two variables. The first variable, $desc, stores the user account's description. To retrieve the description, I use the $dn variable to call the account's properties, then call the Description property ($dn.properties.description). The second variable, $date, stores the current datetime, which I obtain with the Get-Date cmdlet. Both these variables are used later in the script to update the user account's description.

The code in callout D disables the user account. The section is encased in an If statement block that runs when the If condition ($dn.path.length –gt 0) evaluates to true. The condition compares the length of the $dn object's Path property to 0. The Path property contains the LDAP location of the user account in AD. When the Path property contains a value, the If statement block runs.

The first command in the If statement block uses the Path property to create an ADSI object for the user account. The ADSI object, which is assigned to the $user variable, is used to access the object's properties and methods, including the AccountDisabled property.

In the next statement, I set the AccountDisabled property to true. Because AccountDisabled is stored in a binary collection in AD, I use the InvokeSet method on the PowerShell base object (psBase) to update the property. The InvokeSet method takes two arguments: the property name (AccountDisabled) and the new value. To set the AccountDisabled property to true, I use the built-in $true variable.

Now I'm ready to update the user account's description. To do so, I call the $user object's Put method, which takes two arguments: the property name (Description) and the value. In this case, the value is made up of a combination of the $desc and $date variables and the word disabled. The value takes the original description and appends the word disabled followed by the current datetime.

   Previous  1  [2]  3  Next 


Top Viewed ArticlesView all articles
WinInfo Short Takes: Week of November 9, 2009

An often irreverent look at some of the week's other news, including some more Windows 7 sales momentum, some Sophos stupidity, Microsoft's cloud computing self-loathing, more whining from the browser makers, Zoho's "Fake Office," and much, much more ...

Command Prompt Tricks

One reader shares his tip for setting up the command prompt to reflect a remote path. ...

Understanding File-Size Limits on NTFS and FAT

A general confusion about files sizes on FAT seems to stem from FAT32's file-size limit of 4GB and partition-size limit of 2TB. ...


Related Articles PowerShell 101, Lesson 2

PowerShell Scripting

Task Automation Whitepapers From Development to Production: Streamlining SharePoint Deployment with DocAve Deployment Manager

Will Your Next Generation Server System Meet Your Infrastructure Optimization Needs?

Continuous Data Protection and Recovery for Microsoft Exchange

Related Events WinConnections and Microsoft® Exchange Connections

Deep Dive into Windows Server 2008 R2 presented by John Savill

PowerShell 201 - eLearning Series with Paul Robichaux

Check out our list of Free Email Newsletters!

Task Automation eBooks Spam Fighting and Email Security for the 21st Century

A Guide to Windows Certification and Public Keys

Keeping Your Business Safe from Attack: Patch Management

Related Task Automation Resources Introducing Left-Brain.com, the online IT bookstore
Looking for books, CDs, toolkits, eBooks? Prime your mind at Left-Brain.com

Discover Windows IT Pro eLearning Series!
Clear & detailed technical information and helpful how-to's, all in our trademark no-nonsense format


Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro DevProConnections IT Job Hound
Left-Brain.com Technology Resource Directory asp.netPRO ITTV Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 © 2009 Penton Media, Inc. Terms of Use | Privacy Statement