MicrosoftВ® Windows PowerShell(TM) Step By Step (Step By Step (Microsoft))

The use of objects in Windows PowerShell provides many exciting opportunities to do things that are not “built into” the PowerShell. You may recall from using VBScript that there is an object called the wshShell object. If you are not familiar with this object, a drawing of the object model is shown in Figure 2-1.

Figure 2-1: The VBScript wshShell object contributes many easy-to-use methods and properties for the network administrator

Just the Steps 

To create a new instance of the wshShell object, use the New-Object cmdlet while specifying the -comobject argument and supplying the program ID of "wscript.shell". Hold the object created in a variable. Example:

$wshShell = new-object -comobject "wscript.shell":

After the object has been created and stored in a variable, you can directly use any of the methods that are provided by the object. This is shown in the two lines of code that follow:

$wshShell = new-object -comobject "wscript.shell" $wshShell.run("calc.exe")

In the previous code, we use the New-Object cmdlet to create an instance of the wshShell object. We then use the run method to launch Calculator. After the object is created and stored in the variable, you can use Tab Completion to suggest the names of the methods contained in the object. This is shown in Figure 2-2.

Figure 2-2: Tab Completion enumerates methods provided by the object

Creating the wshShell object

Start the Windows PowerShell by using Start | Run | Windows PowerShell. The PowerShell prompt will open by default at the root of your Documents And Settings.

Create an instance of the wshShell object by using the New-Object cmdlet. Supply the comobject argument to the cmdlet, and specify the program ID for the wshShell object, which is “wscript.shell”. Hold the object that is returned into a variable called $wshShell. The code to do this is as follows:

$wshShell = new-object -comobject "wscript.shell"

Launch an instance of Calculator by using the run method from the wshShell object. Use Tab Completion to avoid having to type the entire name of the method. To use the method, begin the line with the variable you used to hold the wshShell object, followed by a period and the name of the method. Then supply the name of the program to run inside parentheses and quotes, as shown here:

$wshShell.run("Calc.exe")

Use the ExpandEnvironmentStrings method to print out the path to the Windows directory. It is stored in an environmental variable called %windir%. The Tab Completion feature of Windows PowerShell is useful for this method name. The environment variable must be contained in quotation marks, as shown here:

$wshShell.ExpandEnvironmentStrings("%windir%")

This command reveals the full path to the Windows directory on your machine. On my computer, the output looks like the following:

C:\WINDOWS

Категории