Creating New Objects


PowerShell doesn't limit you to its own objects. If you are experienced with any of Microsoft's development languages like C#, you can create your own objects from scratch. However, we will not discuss this process since it is outside the scope of this book.

For those of you familiar with VBScript, you can instantiate about any COM object as you would in VBScript. In a VBScript you may have used code like this:

 Set oIE=CreateObject("InternetExplorer.Application") 

In PowerShell you can create the same object this way using the New-Object cmdlet:

 PS C:\> $oIE=New-object -com InternetExplorer.Application 

We've created an object variable called $oIE that is an instance of Internet Explorer.

For this particular object you still need to set object properties and make it visible:

 PS C:\> $oIE.navigate2("www.sapienpress.com") PS C:\> $oIE.Visible=TRUE 

Since you probably don't navigate to SAPIENPress.com too often in an administrative script, you might prefer to use Internet Explorer as an output window:

 PS C:\> new-variable html PS C:\> $svc=get-service PS C:\> $oIE=New-object -com InternetExplorer.Application PS C:\> $oIE.navigate2("about:blank") PS C:\> $oIE.Visible=$TRUE PS C:\> foreach ($s in $svc) {$html=$html+$s.Displayname+": "+$s.status+"<br />"} PS C:\> $oIE.document.body.innerhtml=$html PS C:\> 

In this example, we created a new variable html that has no value. Next we create the Internet Explorer object and make it visible. Then, taking a service object array and the ForEach cmdlet, we build the value for $html by adding the current service's displayname and status. Armed with this, we set an Internet Explorer object property to display the HTML code. The resulting window is depicted in Figure 5-1.

image from book
Figure 5-1: Using an Internet Explorer Object

We could have used any type of HTML formatting such as font styles, color, tables, or text effects. PowerShell has a better cmdlet for creating HTML output that we'll discuss in Chapter 9. At this point we wanted to demonstrate how you can create additional objects in the shell.

Your Mileage May Vary

The Internet Explorer sample may not work as advertised for all users on all systems. It works for the authors and on some test systems but not on others. As a VBScript, the script always works. At least with the Internet Explorer COM object, PowerShell appears to have some inconsistencies.



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