Sunteți pe pagina 1din 10

1

TABLE OF CONTENTS

LAB 2
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS
CREATING AND MANAGING ACTIVE DIRECTORY OBJECTS
CONFIGURING NETWORK SETTINGS ON WINDOWS SERVER
CREATING A WEB SITE
SELECTING, SORTING, AND DISPLAYING DATA
FILTERING OBJECTS AND ENUMERATING OBJECTS

DESCRIPTION
Because objects play such a central role in Windows PowerShell, there are several
native commands designed to work with arbitrary object types. The most important
one is the Get-Member command.

The simplest technique for analyzing the objects that a command returns is to pipe
the output of that command to the Get-Member cmdlet. The Get-
Member cmdlet shows you the formal name of the object type and a complete
listing of its members. The number of elements that are returned can sometimes
be overwhelming. For example, a process object can have over 100 members.

To see all the members of a Process object and page the output so you can view
all of it, type:

Get-Process | Get-Member | Out-Host -Paging

We can make this long list of information more usable by filtering for elements we
want to see. The Get-Member command lets you list only members that are
properties. There are several forms of properties. The cmdlet displays properties of
any type if we set the Get-Member MemberType parameter to the
value Properties. The resulting list is still very long, but a bit more manageable:

PS> Get-Process | Get-Member -MemberType Properties

Using Select-Object cmdlets

You can also use the Select-object cmdlet to create objects with custom properties

LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT


2

Select-Object @{n='firstname';e={'Alexa'}},@{n='Google';e={'Google'}} -
InputObject ''

OR

'' | Select-Object @{n='firstname';e={'Alexa'}},@{n='lastname';e={'Google'}}

Using New-Object and Add-Member

This is longer way to create PowerShell objects, first you instantiate class: PSObjectthen
you use Add-Member cmdlet to add member properties to the object. You can also add
methods using this method.

$obj = New-Object -TypeName psobject

$obj | Add-Member -MemberType NoteProperty -Name firstname -Value 'Alexa'

$obj | Add-Member -MemberType NoteProperty -Name lastname -Value 'Google'

$obj

# add a method to an object

$obj | Add-Member -MemberType ScriptMethod -Name "GetName" -Value


{$this.firstname +' '+$this.lastname}

Using New-Object and hashtables

PowerShell also allows you to create hashtables and assign it as property to New-Object
PSObject cmdlet.

# Using New-Object and hashtables

$properties = @{

firstname = 'Alexa'

lastname = 'Google'

$o = New-Object psobject -Property $properties; $o

New-Object

LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT


3

Creates an instance of a Microsoft .NET Framework or COM object.

New-Object New-Object

[-TypeName] <String> [-ComObject] <String>

[[-ArgumentList] <Object[]>] [-Strict]

[-Property <IDictionary>] [-Property <IDictionary>]

[<CommonParameters>] [<CommonParameters>]

Example 1: Create a System.Version object

This example creates a System.Version object using the "1.2.3.4" string as the
constructor.

You can specify either the type of a .NET Framework class or a ProgID of a COM object.
By default, you type the fully qualified name of a .NET Framework class and the cmdlet
returns a reference to an instance of that class. To create an instance of a COM object, use
the ComObject parameter and specify the ProgID of the object as its value.

New-Object -TypeName System.Version -ArgumentList "1.2.3.4"

Major Minor Build Revision

----- ----- ----- --------

1 2 3 4

Example 2: Create an Internet Explorer COM object

This example creates two instances of the COM object that represents the Internet
Explorer application. The first instance uses the Property parameter hash table to
call the Navigate2 method and set the Visible property of the object to $True to
make the application visible. The second instance gets the same results with
individual commands.

$IE1 = New-Object -COMObject InternetExplorer.Application -Property


@{Navigate2="www.microsoft.com"; Visible = $True}

Example 3: Use the Strict parameter to generate a non-terminating error

LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT


4

This example demonstrates that adding the Strict parameter causes the New-
Object cmdlet to generate a non-terminating error when the COM object uses an
interop assembly.

$A = New-Object -COMObject Word.Application -Strict -Property @{Visible =


$True}

Example 4: Create a COM object to manage Windows desktop

This example shows how to create and use a COM object to manage your Windows
desktop.

The first command uses the ComObject parameter of the New-Object cmdlet to
create a COM object with the Shell.Application ProgID. It stores the resulting
object in the $ObjShell variable. The second command pipes the $ObjShell variable
to the Get-Member cmdlet, which displays the properties and methods of the COM
object. Among the methods is the ToggleDesktop method. The third command
calls the ToggleDesktop method of the object to minimize the open windows on
your desktop.

$Objshell = New-Object -COMObject "Shell.Application"


$objshell | Get-Member

$objshell.ToggleDesktop()

Example 5: Pass multiple arguments to a constructor

This example shows how to create an object with a constructor that takes multiple
parameters. The parameters must be put in an array when
using ArgumentList parameter.

$array = @('One', 'Two', 'Three')


$parameters = @{
TypeName = 'System.Collections.Generic.HashSet[string]'
ArgumentList = ([string[]]$array,
[System.StringComparer]::OrdinalIgnoreCase)
}

$set = New-Object @parameters

LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT


5

PowerShell Snap-in: Creating Websites


Introduction

The IIS PowerShell namespace consists of items like Web-Sites, Apps, Virtual
Directories and Application Pools. Creating new namespace items and managing
them is very easy using the built-in PowerShell cmdlets.

Creating Web-Sites
If you are familiar with PowerShell you know that the New-Item cmdlet is used to
create new items in the various PowerShell namespaces. The command New-Item
c:\TestDirectory creates a new filesystem directory for example (most people use
the MD or MKDIR alias for New-Item however). New-Item is also used to create new
Web-Sites within the IIS PowerShell namespace.

The goal of this code eventually will be go get all other web pages within a folder
and create hyperlinks to file with the name of the files. This code mostly works but
puts all elements of the array on both links. I need help to separate them links to
1 per file (per element of array until all created)

New-Item web.htm -Type file -force // Create a new web page

Add-Content -Path web.htm -Value '<HTML>' // Put default opening html tag in file

$pages = @('web1.htm', 'web2.htm') //Create an array to contain web hyperlinks to create

foreach($page in $pages)
{
Add-Content -Path web.htm -Value "<a href=$page> $page</a><br />"
}
Add-Content -Path web.htm -Value '</HTML>' //Close the html file tag

Order Your Output by Easily Sorting Objects in PowerShell

Much of the time, there is no guarantee to the order in which Windows


PowerShell returns objects. This tutorial explains how to fix that issue.

Anyway, after the user group meeting, when we were all standing around,
one of the attendees came up to me and asked me in what order Windows
PowerShell returns information. The answer is that there is no guarantee of

LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT


6

return order in most cases. The secret sauce is to use the built-in sorting
mechanism from Windows PowerShell itself. In the image that follows, the
results from the Get-Process cmdlet appear to sort on
the ProcessName property.

One could make a good argument that the processes should sort on the
process ID (PID) or on the amount of CPU time consumed, or on the amount
of memory utilized. In fact, it is entirely possible that for each property
supplied by the Process object, someone has a good argument for sorting
on that particular property. Luckily, custom sorting is easy to accomplish in
Windows PowerShell. To sort returned objects in Windows PowerShell, pipe
the output from one cmdlet to the Sort-Object cmdlet. This technique is
shown here where the Sort-Object cmdlet sorts the Process objects that
are returned by the Get-Process cmdlet.

Get-Process | Sort-Object id

The command to sort the Process objects on the ID property and the
output associated with that command are shown in the image that follows.

Reversing the sort order


By default, the Sort-Object cmdlet performs an ascending sort—the
numbers range from small to large. To perform a descending sort requires
utilizing the Descending switch.

Note: There is no Ascending switch for the Sort-Object cmdlet because


that is the default behavior.

To arrange the output from the Get-Process cmdlet such that


the Process objects appear from largest process ID to the smallest (the
smallest PID is always 0—the Idle process), choose the ID property to sort
on, and use the Descending switch as shown here:

Get-Process | Sort-Object id –Descending

The command to perform a descending sort of processes based on the


process ID.

LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT


7

When you use the Sort-Object cmdlet to sort output, keep in mind that the
first position argument is the property or properties upon which to sort.
Because Property is the default means that using the name Property in the
command is optional. Therefore, the following commands are equivalent:

Get-Process | Sort-Object id –Descending

Get-Process | Sort-Object -property id –Descending

In addition to using the default first position for the Property argument,
the Sort-Object cmdlet is aliased by sort. By using gps as an alias for
the Get-Process cmdlet, sort as an alias for Sort-Object, and a partial
parameter of des for Descending, the syntax of the command is very short.
This short version of the command is shown here.

gps | sort id –des

Sorting multiple properties at once


The Property parameter of the Sort-Object cmdlet accepts an array (more
than one) of properties upon which to sort. This means that I can sort on the
process name, and then sort on the working set of memory that is utilized
by each process (for example). When supplying multiple property names, the
first property sorts, then the second property sorts.

The resulting output may not always meet expectations, and therefore, may
require a bit of experimentation. For example, the command that follows
sorts the process names in a descending order. When that sort completes,
the command does an additional sort on the WorkingSet (ws is the alias)
property. However, this second sort is only useful when there happen to be
multiple processes with the same name (such as the svchost process). The
command that is shown here is an example of sorting on multiple properties.

Get-Process | Sort-Object -Property name, ws –Descending

When the name and ws properties reverse order in the command, the
resulting output is not very useful because the only sorting of
the name property happens when multiple processes have an identical

LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT


8

working set of memory. The command that is shown here reverses the order
of the WorkingSet and the process name properties.

Get-Process | Sort-Object -Property ws, name –Descending

Sorting and returning unique items


At times, I might want to see how many different processes are running on
a system. To do this, I can filter duplicate process names by using
the Unique switch. To count the number of unique processes that are
running on a system, I pipe the results from the Sort-Object cmdlet to
the Measure-Object cmdlet. This command is shown here.

Get-Process | Sort-Object -Property name -Descending -Unique | measure-


object

To obtain a baseline that enables me to determine the number of duplicate


processes, I drop the Unique switch. This command is shown here.

Get-Process | Sort-Object -Property name -Descending | measure-object

Performing a case sensitive sort


One last thing to discuss when sorting items is the CaseSensitive switch.
When used, the CaseSensitive switch sorts lowercase letters first, then
uppercase. The following commands illustrate this.

$a = “Alpha”,”alpha”,”bravo”,”Bravo”,”Charlie”,”charlie”,”delta”,”Delta”

$a | Sort-Object –CaseSensitive

Use the PowerShell Group-Object Cmdlet to Display Data

How to use the Windows PowerShell Group-Object cmdlet to organize


data?

One cmdlet that allows this analysis is the Group-Object cmdlet. In its most
basic form, the Group-Object cmdlet accepts a property from objects in a

LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT


9

pipeline, and it gathers up groups that match that property and displays the
results. For example, to check on the status of services on a system, pipe the
results from the Get-Service cmdlet to the Group-Object cmdlet and use
the Status property. The command is shown here.

Get-Service | Group-Object -Property status

In the Group field of the output from the Group-Object cmdlet, the objects
that are grouped appear. The output indicates that each grouped object is
an instance of a ServiceController object. This output is a bit distracting.

In situations, where the grouping is simple, the Group output might actually
be useful. (Group is an alias for Group-Object).
PS C:\Windows\system32> 1,2,3,2,1,4 | group

If the grouping information does not add any value, omit it by using
the NoElement switched parameter. The revised command to display the
status of services and the associated output are shown in the image that
follows.
PS C:\Windows\system32> Get-Service | group status -NoElement

Here are the steps for using the Group-Object cmdlet to return a hash table
of information:

1. Pipe the objects to the Group-Object cmdlet.


2. Use the AsHashTable switched parameter and the AsString switched
parameter.
3. Store the resulting hash table in a variable.

An example of using these steps is shown in the code that follows.

$hash = Get-Service | group status -AsHashTable –AsString

After it is created, view the hash table by displaying the content that is stored
in the variable. This technique is shown here.

LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT


10

PS C:\> $hash

At this point, the output does not appear to be more interesting than a
simple grouping. But, the real power appears when accessing the key
properties (those stored under the Name column). To access the objects
stored in each of the key values, use dotted notation, as shown here.

$hash.running

I can index into the collection by using square brackets and selecting a
specific index number. This technique is shown here.

PS C:\> $hash.running[5]

If I am interested in a particular running service, I can pipe the results to


the Where-Object cmdlet (the question mark is an alias for Where-Object).
This technique is shown here.

PS C:\> $hash.running | ? {$_.name -match “bfe”}

In addition to being able to group directly by a property, such as running


services, it is also possible to group based on a script block. The script block
becomes sort of a where clause. To find the number of services that are
running, and support a stop command, use the Group-Object cmdlet and a
script block. This command is shown here.

PS C:\> Get-Service | group {$_.status -eq “running” -AND $_.canstop}

References:

1. https://serverfault.com/questions/683942/use-powershell-to-create-a-web-page-from-an-array
2. https://devblogs.microsoft.com/scripting/use-the-powershell-group-object-cmdlet-to-display-data/
3. https://docs.microsoft.com/en-us/powershell/module/nettcpip/set-netipaddress?view=win10-ps
4. https://devblogs.microsoft.com/scripting/order-your-output-by-easily-sorting-objects-in-
powershell/

LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT

S-ar putea să vă placă și