Adding Features


Aliasing properties isn't really extending the functionality of a type; it just makes it more convenient or intuitive. However, you can extend a type's functionality. For example, we've added the following to our types.ps1xml file:

 <Type>   <Name>System.String</Name>   <Members>    <ScriptProperty>     <Name>IsEmail</Name>     <GetScriptBlock>     $regex=[regex]"^([\w-]+)(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$"     $var = $this     if ($regex.ismatch($var)) {      $true     } else {      $false     }     </GetScriptBlock>    </ScriptProperty>  </Members> </Type> 

This defines a brand-new property for the System.String type named IsEmail. In it we've performed a regular expression comparison that you may recognize from Chapter 7. The special $this variable contains whatever the instance of the type contains.

That's a bit complicated to read, so let's explain a bit. When you create a new variable and specify that it's a string, you're creating a new instance of the System.String type:

 PS C:\> [string]$var = "don@sapien.com" 

This new instance, named $var, contains the value "don@sapien.com", which is the value assigned to the variable. So, within the type extension, the special variable $this refers to "don@sapien.com" because that's the value inside this particular instance of the type.

The rest of our type extension code performs the regular expression match. If there's a match, the special variable $true is output for the IsEmail property; otherwise, $false is output. Here's how it works in the shell:

 PS C:\> [string]$var = "don@sapien.com" PS C:\> $var.isemail True PS C:\> 

Pretty cool, right? We've provided another example to prove it works when the value isn't an E-mail address:

 PS C:\> [string]$not = "hello!" PS C:\> $not.isemail False PS C:\> 

So we've added brand-new functionality to the System.String type within PowerShell just by adding a few lines of script to types.ps1xml. The downside to this approach is that your System.String type is only extended on your computer. This means if you write scripts that rely on this extension, the scripts will only run on your computer. To have this work elsewhere in your organization, you need to share your types.ps1xml file. Fortunately, that's easy to do since it's a normal text file. However, you may want to implement some procedures within your organization to control this file. For example, you might keep a centralized copy of it in a source control database such as Microsoft Visual SourceSafe so prior versions remain accessible. This will also ensure there's a single, central location from which all administrators can obtain the latest version.



Windows PowerShell. TFM
Internet Forensics
ISBN: 982131445
EAN: 2147483647
Year: 2004
Pages: 289

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net