Vous êtes sur la page 1sur 14

Microsoft Virtual Labs

Writing Scripts with Windows


PowerShell

Writing Scripts with Windows PowerShell

Table of Contents
Writing Scripts with Windows PowerShell ................................................................................ 1
Exercise 1 Adding Command-Line Arguments to a Script ...........................................................................................3
Exercise 2 Working with Arrays and with .NET Framework Classes ...........................................................................5
Exercise 3 Filtering Data ...............................................................................................................................................7
Exercise 4 Creating a Custom Table..............................................................................................................................8
Exercise 5 Extending the Custom Table ........................................................................................................................9
Exercise 6 Formatting Output ...................................................................................................................................... 10
Finished Script ............................................................................................................................................................. 11

Writing Scripts with Windows PowerShell

Writing Scripts with Windows PowerShell


Objectives
Scenario

After completing this lab, you will be better able to:


 Use Windows PowerShell to write system administration scripts
This virtual lab is designed to introduce you to script writing in Windows
PowerShell. In this lab you will write a script that, using a folder name as a
command-line argument, connects to that folder and uses the .NET Framework to
return file version information for all the .DLL files found in the folder. During
the course of the lab you will take that information and filter it, then display it in
a custom table; in addition, you will use the Get-Item Cmdlet to retrieve the size
of each .DLL file. The twist there? File size information is not found in the same
.NET Framework class as file version information. That means your final table
will actually combine information taken from two different classes.
Along the way you will also be introduced to basic scripting techniques such as
using an If statement and a For Each loop, populating an array, and even clearing
the Windows PowerShell console window.
Two things we should add regarding this lab. First, its not required that you
listen to the accompanying webcast; if you wish, you can try to complete the
virtual lab entirely on your own. (Suggested code is included at the end of each
exercise.) However, all of the scripting concepts required to complete the virtual
lab are included in the webcast; if you encounter difficulties anywhere in the lab
you will likely find the answer in the webcast.
Second, some of the code and some of the techniques introduced in this lab lean
towards the more advanced side of scripting; for beginners, these techniques
might even be a little bit too advanced. That is by design. The primary goal of
this virtual lab is to give you a taste of the kind of scripts you will, in no time, be
able to write using Windows PowerShell; we werent concerned with whether or
not you could write this kind of a script today. We could, of course, have shown
you a Hello, world kind of script and guaranteed that everyone would be able
to complete the lab successfully. However, we were afraid that we would also
guarantee that no one would learn anything particularly useful. By following
along with the webcast and by using the hints included in this manual, you
should be able to complete the lab with a minimal amount of difficulty. If you
cant, well, dont worry: scripting in Windows PowerShell can be a very
different experience, and it takes a little practice and a little getting used to.
Fortunately, you can repeat this lab as many times as needed, either online, or on
any computer running Windows PowerShell.
A Note About the Suggested Code. Due to line limitations in this document the
suggested code shown here might appear different than the code you write. In
many cases that will be due to the need to break lines within this document.
Remember, in Windows PowerShell the back tick character (`) is used to indicate
a line break. In Windows PowerShell this represents one line of code:
write-host "Hey, how's it going?"
Technically, this is also one line of code; it looks like two lines simply because
the back tick was used to break one line of code into two pieces:
write-host `
"Hey, how's it going?"

Page 1 of 12

Writing Scripts with Windows PowerShell


In order to display valid lines of code in this manual we probably used many
more line break characters than you did. Dont worry about that: feel free to
make lines as long (or as short) as you are comfortable with.

Prerequisites

A basic knowledge of Windows PowerShell scripting fundamentals is highly


recommended. For more information, see the TechNet Webcast New Kid on the
Scriptblock: Writing Scripts with Windows PowerShell.

Estimated Time to
Complete This Lab

90 Minutes

Computers used in this


Lab

Paris
The password for the Administrator account on all computers in this lab is:
pass@word1.

Page 2 of 12

Writing Scripts with Windows PowerShell

Exercise 1
Adding Command-Line Arguments to a Script
Scenario
In this first exercise you will write a Windows PowerShell script that can determine whether or not at least one
command-line argument was used when starting the script. If no such arguments were used the script should echo
back a message stating that the user must supply a folder name when starting the script and then terminate itself. If
at least one command-line argument was provided the script should take the value of the argument, append \*.dll,
and store the concatenated value in a variable named $strFolder. The value of that variable should be echoed back to
the screen.
To successfully complete this exercise you will need to do the following:

Use the arguments collection ($args) and the length property to determine if any command-line arguments
were supplied.

Use an If statement to take action based on whether or not command-line arguments were supplied.

Use the Write-Warning Cmdlet to write a message to the screen.

Use the break statement to terminate the script as needed.

Tasks

Detailed Steps

Start Notepad

Click Start and then click Run.


In the Run dialog box type notepad and then press ENTER.

Create a new script

After Notepad starts, write a script that does the following. If you run into problems,
the suggested code can be found at the end of this exercise. The script you write
should include the following features:

The script should store the number of command-line arguments in a variable


named $a.

The script should use an If statement to ensure that at least 1 argument was
passed to the script.

If no arguments were used the script should echo a warning that says, You
must supply a folder name. The script should then terminate.

If at least one command-line argument was supplied the script should


concatenate the value of the first command-line argument with the string
value \*.dll. That value should then be assigned to a variable named
$strFolder.

Save the script to C:\Scripts, and name it as Test.ps1. Do not close Notepad; we'll be
modifying this same script throughout the lab.
Verify that the script
works

If you havent already done so, start Windows PowerShell. This can be done by
double-clicking the Windows PowerShell shortcut on the desktop.
Type in command to enable executing scripts.
Set-ExecutionPolicy RemoteSigned
Navigate to folder C:\Scripts by typing in command:

Page 3 of 12

Writing Scripts with Windows PowerShell


Tasks

Detailed Steps
Chdir C:\Scripts
From within Windows PowerShell run the script C:\Scripts\Test.ps1. The first time,
try running the script without any command-line arguments. In other words, start the
script using this command:
.\test.ps1
You should receive a warning message telling you that you must supply a folder name.
Next, temporarily add the following line of code as the last line of Test.ps1 and then
save the script:
$strFolder
Run the script a second time, this time using C:\Windows as a command-line
parameter. The command for running the script should look like this:
.\test.ps1 c:\windows
You should not get an error message this time; instead, the script should echo back the
following: c:\windows\*.dll. Try running the script again, passing it the name of
another folder (it doesn't matter whether the folder actually exists).
When done, remove the temporary line of code ($strFolder) and save the script.

Exercise answer

Your script should look similar to this:


$a = $args.length
if ($a -eq 0)
{Write-warning "You must supply a folder name."; break}
else {$strFolder = $args[0] + "\*.dll"}

Page 4 of 12

Writing Scripts with Windows PowerShell

Exercise 2
Working with Arrays and with .NET Framework Classes
Scenario
In this exercise you will enhance the script you created in Exercise 1. To begin with, you will create an empty array
named $b; you will then use the Get-ChildItem Cmdlet to return a collection of all the .DLL files found in the
folder C:\Windows, a folder name that will be passed to the script as a command-line argument. The information
retrieved using Get-ChildItem will be stored in a variable named $c.
Once the file information has been returned you will set up a For Each loop that loops through the collection of files;
for each file in the collection you will use the .NET Framework class System.Diagnostics.FileVersionInfo to
retrieve file version information. This information will then be added to the array $b.
To successfully complete this exercise you will need to do the following:

Create an empty array.

Use the Get-ChildItem Cmdlet to retrieve file information

Use the .NET Framework class System.Diagnostics.FileVersionInfo to retrieve file version information.

Use the ForEach-Object Cmdlet (foreach) and the += operator to add new items to your array.

Tasks

Detailed Steps

Add code to your script

Add additional code to Test.ps1. That code should do the following:

Create an empty array named $b.

Use the Get-ChildItem Cmdlet to retrieve a list of all the files found in
$strFolder (the variable containing the command-line argument). The
information returned by Get-ChildItem should be stored in a variable named
$c.

Create a For Each loop that loops through all the items in $c. For each item
you need to do two things:

Use [system.diagnostics.fileversioninfo]::getversioninfo to retrieve the file


version information for the file.

Add each item to the array $b.

Save the file Test.ps1. Keep Notepad open.


If you run into problems, the suggested code can be found at the end of this exercise.
Verify that the script
works

In Windows PowerShell, run the script Test.ps1 using the following code:
.\test.ps1 c:\windows
If there are no errors, then temporarily make this the final line of code in the script:
$b
Re-run the script, again using the command .\test.ps1 c:\windows.
(Hint. Press the F3 to recall the last command.) This time the script should display file
version information for all the .dll files found in the folder C:\Windows.
Delete the last line of the script ($b) and save the file Test.ps1.
Page 5 of 12

Writing Scripts with Windows PowerShell


Tasks

Detailed Steps

Exercise answer

The code that you added to the script should look similar to this:
$b = @()
$c = get-childitem $strFolder
foreach ($i in $c)
{$b += [system.diagnostics.fileversioninfo]::
getversioninfo($i.fullname)}

Page 6 of 12

Writing Scripts with Windows PowerShell

Exercise 3
Filtering Data
Scenario
In this exercise you will modify your script so that it takes the file version information retrieved in Exercise 2 and
filters out all the .DLL files except for those created by the Microsoft Corporation. You will also use the script to
clear the Windows PowerShell console window.
To successfully complete this exercise you will need to do the following:

Use the Where-Object Cmdlet to filter out all the .DLL files except for those where the CompanyName
property is equal to (-eq) Microsoft Corporation.

Use the Clear-Host (cls) Cmdlet to clear the console window.

Tasks

Detailed Steps

Add code to your script

Add additional code to Test.ps1. That code should include the following:

A command that pipes the file version information ($b) to the Where-Object
Cmdlet. Where-Object should filter out all the items except for those where
the value of the CompanyName property is equal to Microsoft Corporation.
The filtered collection should be stored in a variable named $d.

A command to clear the screen.

Save the file Test.ps1. Keep Notepad open.


If you run into problems, the suggested code can be found at the end of this exercise.
Verify that the script
works

In Windows PowerShell, run the script Test.ps1 using the following code:
.\test.ps1 c:\windows
If there are no errors, then temporarily make this the final line of code in the script:
$d
Re-run the script, again using the command .\test.ps1 c:\windows.
(Hint. Press the F3 to recall the last command.) This time the script should clear the
screen, and then display file version information for the .dll files in the folder
C:\Windows that were created by the Microsoft Corporation.
Delete the last line of the script ($d) and save the file Test.ps1.

Exercise answer

The code you added to the script should look similar to this:
$d = ($b | where-object {$_.CompanyName -eq "Microsoft
Corporation"})
cls

Page 7 of 12

Writing Scripts with Windows PowerShell

Exercise 4
Creating a Custom Table
Scenario
In this exercise you modify your script so that the filtered file version information is displayed in a custom table.
To successfully complete this exercise you will need to do the following:

Pipe the filtered file version information to the Format-Table Cmdlet.

Use Format-Table to create a custom table consisting of three columns. You will need to provide a Label
and an Expression for each column in the table.

Tasks

Detailed Steps

Add code to your script

Add additional code to Test.ps1. That code should do the following:

Pipe the filtered file version information ($d) to the Format-Table Cmdlet.

Create a custom table with three columns:

Column 1 should have the label DLL File and the expression $_.FileName
(representing the file name for the DLL file in question).

Column 2 should have the label Company Name and the expression
$_.CompanyName (representing the file name for the DLL file in question).

Column 3 should have the label Version Number and the expression
$_.FileVersion (representing the version number of the DLL file in question).

Save the file Test.ps1. Keep Notepad open.


If you run into problems, the suggested code can be found at the end of this exercise.
Verify that the script
works

In Windows PowerShell, run the script Test.ps1 using the following code:
.\test.ps1 c:\windows
You should see a custom table consisting of three columns, one labeled DLL File;
another labeled Company Name; and the third labeled Version Number.

Exercise answer

The code that you added to the script should look similar to this:
$d | format-table @{Label="DLL
File";Expression={$_.FileName}},@{Label="Company
Name";Expression={$_.CompanyName}},@{Label="Version
Number";Expression={$_.FileVersion}}

Page 8 of 12

Writing Scripts with Windows PowerShell

Exercise 5
Extending the Custom Table
Scenario
In this exercise you will extend the custom table added to your script in Exercise 4. In particular, for each file in the
collection (and thus each row in the table) you will use the Get-Item Cmdlet to retrieve the size (Length) of the file.
This has the net effect of combining data from two separate classes in a single table. The file version information, of
course, is derived from the System.Diagnostics.FileVersionInfo class, while the information retrieved using GetItem comes from the System.IO.FileInfo class.
To successfully complete this exercise you will need to do the following:

Add a fourth column to your custom table, specifying a Label and Expression for the new column.

For the column Expression, use the Get-Item Cmdlet to retrieve the size (Length) of the file displayed in
each row of the table.

Tasks

Detailed Steps

Add code to your script

Add additional code to Test.ps1. That code should do the following:

Add a fourth column to the custom table created in Exercise 4. This column
should have the Label File Size. For the column Expression, use the GetItem Cmdlet to bind to the file in question and retrieve the value of the
Length property. In order to bind to the file you should use the same $_
special variable used in Exercise 4.

Save the file Test.ps1. Keep Notepad open.


If you run into problems, the suggested code can be found at the end of this exercise.
Verify that the script
works

In Windows PowerShell, run the script Test.ps1 using the following code:
.\test.ps1 c:\windows
You should see a custom table consisting of four columns, the three columns created
in Exercise 4 and a new column labeled File Size. This fourth column should display
the size of the file in bytes.

Exercise answer

The code that you added to the script should look similar to the code shown in
boldface:
$d |
format-table @{Label="DLL
File";Expression={$_.FileName}},@{Label="Company
Name";Expression={($_.CompanyName)}}, @{Label="Version
Number";Expression={$_.FileVersion}},@{Label="File
Size";Expression={(get-item $_.FileName).Length}}

Page 9 of 12

Writing Scripts with Windows PowerShell

Exercise 6
Formatting Output
Scenario
To successfully complete this exercise you will need to do the following:

Use .NET Framework formatting commands to format file sizes.

Use Format-Table parameters to auto-size the columns in the table, enabling all the text in each column to
be displayed.

Tasks

Detailed Steps

Add code to your script

Add additional code to Test.ps1. That code should do the following:

Use .NET Framework formatting commands to ensure that the file size
numbers are displayed with commas used as digit separators (e.g., 18,944).

Use the appropriate Format-Table parameter to auto-size the columns in the


table, enabling all the text in each column to be displayed.

Save the file Test.ps1. Keep Notepad open.


If you run into problems, the suggested code can be found at the end of this exercise.
Verify that the script
works

In Windows PowerShell, run the script Test.ps1 using the following code:
.\test.ps1 c:\windows
You should see a custom table consisting of four columns. The columns should be
sized so that all the text in each column can be displayed. In addition, the file sizes
should be displayed similar to this:
18,944
When you are finished, you can log off of the virtual lab.

Exercise answer

The code that you added to the script should look similar to the code shown in
boldface:
$d |
format-table @{Label="DLL
File";Expression={$_.FileName}},@{Label="Company
Name";Expression={($_.CompanyName)}}, @{Label="Version
Number";Expression={$_.FileVersion}},
@{Label="File Size";Expression={"{0:N0}"-f (get-item
$_.FileName).Length}} -autosize

Page 10 of 12

Writing Scripts with Windows PowerShell

Finished Script
Scenario
Tasks

Detailed Steps

Final Script

$a = $args.length
if ($a -eq 0) {Write-warning "You must supply a folder name."; break}
else {$strFolder = $args[0] + "\*.dll"}
$b = @()
$c = get-childitem $strFolder
foreach ($i in $c)
{$b += [system.diagnostics.fileversioninfo]::`
getversioninfo($i.fullname)}
$d = ($b | where-object {$_.CompanyName -eq `
"Microsoft Corporation"})
cls
$d |
format-table `
@{Label="DLL File";Expression={$_.FileName}},`
@{Label="Company Name";Expression={$_.CompanyName}},`
@{Label="Version Number";Expression={$_.FileVersion}},`
@{Label="File Size";Expression={"{0:N0}" `
-f (get-item $_.FileName).Length}} -autosize

Page 11 of 12

Writing Scripts with Windows PowerShell

For More Information


For more information about Windows PowerShell see the Scripting with Windows PowerShell page in the TechNet
Script Center: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx.

Page 12 of 12

Vous aimerez peut-être aussi