SlideShare a Scribd company logo
1 of 10
Download to read offline
1
LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT
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
2
LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT
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
3
LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT
Creates an instance of a Microsoft .NET Framework or COM object.
New-Object
[-TypeName] <String>
[[-ArgumentList] <Object[]>]
[-Property <IDictionary>]
[<CommonParameters>]
New-Object
[-ComObject] <String>
[-Strict]
[-Property <IDictionary>]
[<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
4
LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT
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
5
LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT
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
6
LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT
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.
7
LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT
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
8
LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT
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
9
LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT
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:Windowssystem32> 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:Windowssystem32> 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.
10
LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT
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/

More Related Content

What's hot

JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play FrameworkKnoldus Inc.
 
Angular 2 Component Communication - Talk by Rob McDiarmid
Angular 2 Component Communication - Talk by Rob McDiarmidAngular 2 Component Communication - Talk by Rob McDiarmid
Angular 2 Component Communication - Talk by Rob McDiarmidAmrita Chopra
 
Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Mohan Arumugam
 
PowerShell Fundamentals
PowerShell FundamentalsPowerShell Fundamentals
PowerShell Fundamentalsmozdzen
 
Compress and decompress
Compress and decompressCompress and decompress
Compress and decompressSon Nguyen
 
Caching & validating
Caching & validatingCaching & validating
Caching & validatingSon Nguyen
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!DataArt
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax ApplicationsSiarhei Barysiuk
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Oscar Renalias
 
Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010Binh Nguyen
 
performancetestingjmeter-121109061704-phpapp02 (1)
performancetestingjmeter-121109061704-phpapp02 (1)performancetestingjmeter-121109061704-phpapp02 (1)
performancetestingjmeter-121109061704-phpapp02 (1)QA Programmer
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 

What's hot (20)

Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
 
Nativescript angular
Nativescript angularNativescript angular
Nativescript angular
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Angular 2 Component Communication - Talk by Rob McDiarmid
Angular 2 Component Communication - Talk by Rob McDiarmidAngular 2 Component Communication - Talk by Rob McDiarmid
Angular 2 Component Communication - Talk by Rob McDiarmid
 
Group111
Group111Group111
Group111
 
Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013
 
PowerShell Fundamentals
PowerShell FundamentalsPowerShell Fundamentals
PowerShell Fundamentals
 
Compress and decompress
Compress and decompressCompress and decompress
Compress and decompress
 
Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
 
Caching & validating
Caching & validatingCaching & validating
Caching & validating
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
 
QB Into the Box 2018
QB Into the Box 2018QB Into the Box 2018
QB Into the Box 2018
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
 
Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010
 
performancetestingjmeter-121109061704-phpapp02 (1)
performancetestingjmeter-121109061704-phpapp02 (1)performancetestingjmeter-121109061704-phpapp02 (1)
performancetestingjmeter-121109061704-phpapp02 (1)
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 

Similar to Order Objects in PowerShell Using Sort-Object

Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4JoeDinaso
 
Open microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletOpen microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletMitchinson
 
Learning .NET Attributes
Learning .NET AttributesLearning .NET Attributes
Learning .NET AttributesPooja Gaikwad
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributessonia merchant
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedureftz 420
 
Introduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinIntroduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinSimon Gauvin
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributessonia merchant
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
Salesforce, APEX Concepts
Salesforce, APEX ConceptsSalesforce, APEX Concepts
Salesforce, APEX ConceptsGaurish Goel
 
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...goodfriday
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupDavid Barreto
 
Parsing in ios to create an app
Parsing in ios to create an appParsing in ios to create an app
Parsing in ios to create an appHeaderLabs .
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontendHeiko Hardt
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGvraopolisetti
 
Microsoft Offical Course 20410C_04
Microsoft Offical Course 20410C_04Microsoft Offical Course 20410C_04
Microsoft Offical Course 20410C_04gameaxt
 
Tony Vitabile .Net Portfolio
Tony Vitabile .Net PortfolioTony Vitabile .Net Portfolio
Tony Vitabile .Net Portfoliovitabile
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4Naga Muruga
 
Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21Stamatis Zampetakis
 

Similar to Order Objects in PowerShell Using Sort-Object (20)

Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4
 
Open microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletOpen microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutlet
 
Learning .NET Attributes
Learning .NET AttributesLearning .NET Attributes
Learning .NET Attributes
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributes
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedure
 
Introduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinIntroduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon Gauvin
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Salesforce, APEX Concepts
Salesforce, APEX ConceptsSalesforce, APEX Concepts
Salesforce, APEX Concepts
 
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
 
Parsing in ios to create an app
Parsing in ios to create an appParsing in ios to create an app
Parsing in ios to create an app
 
Library Project
Library ProjectLibrary Project
Library Project
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontend
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUG
 
Microsoft Offical Course 20410C_04
Microsoft Offical Course 20410C_04Microsoft Offical Course 20410C_04
Microsoft Offical Course 20410C_04
 
Tony Vitabile .Net Portfolio
Tony Vitabile .Net PortfolioTony Vitabile .Net Portfolio
Tony Vitabile .Net Portfolio
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4
 
AD102 - Break out of the Box
AD102 - Break out of the BoxAD102 - Break out of the Box
AD102 - Break out of the Box
 
Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21
 

More from Hitesh Mohapatra

Virtualization: A Key to Efficient Cloud Computing
Virtualization: A Key to Efficient Cloud ComputingVirtualization: A Key to Efficient Cloud Computing
Virtualization: A Key to Efficient Cloud ComputingHitesh Mohapatra
 
Automating the Cloud: A Deep Dive into Virtual Machine Provisioning
Automating the Cloud: A Deep Dive into Virtual Machine ProvisioningAutomating the Cloud: A Deep Dive into Virtual Machine Provisioning
Automating the Cloud: A Deep Dive into Virtual Machine ProvisioningHitesh Mohapatra
 
Harnessing the Power of Google Cloud Platform: Strategies and Applications
Harnessing the Power of Google Cloud Platform: Strategies and ApplicationsHarnessing the Power of Google Cloud Platform: Strategies and Applications
Harnessing the Power of Google Cloud Platform: Strategies and ApplicationsHitesh Mohapatra
 
Scheduling in Cloud Computing
Scheduling in Cloud ComputingScheduling in Cloud Computing
Scheduling in Cloud ComputingHitesh Mohapatra
 
Load balancing in cloud computing.pptx
Load balancing in cloud computing.pptxLoad balancing in cloud computing.pptx
Load balancing in cloud computing.pptxHitesh Mohapatra
 
ITU-T requirement for cloud and cloud deployment model
ITU-T requirement for cloud and cloud deployment modelITU-T requirement for cloud and cloud deployment model
ITU-T requirement for cloud and cloud deployment modelHitesh Mohapatra
 
Reviewing basic concepts of relational database
Reviewing basic concepts of relational databaseReviewing basic concepts of relational database
Reviewing basic concepts of relational databaseHitesh Mohapatra
 
Advanced database protocols
Advanced database protocolsAdvanced database protocols
Advanced database protocolsHitesh Mohapatra
 
Involvement of WSN in Smart Cities
Involvement of WSN in Smart CitiesInvolvement of WSN in Smart Cities
Involvement of WSN in Smart CitiesHitesh Mohapatra
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its FundamentalsHitesh Mohapatra
 
Reinforcement Learning / E-Book / Part 1
Reinforcement Learning / E-Book / Part 1Reinforcement Learning / E-Book / Part 1
Reinforcement Learning / E-Book / Part 1Hitesh Mohapatra
 

More from Hitesh Mohapatra (20)

Virtualization: A Key to Efficient Cloud Computing
Virtualization: A Key to Efficient Cloud ComputingVirtualization: A Key to Efficient Cloud Computing
Virtualization: A Key to Efficient Cloud Computing
 
Automating the Cloud: A Deep Dive into Virtual Machine Provisioning
Automating the Cloud: A Deep Dive into Virtual Machine ProvisioningAutomating the Cloud: A Deep Dive into Virtual Machine Provisioning
Automating the Cloud: A Deep Dive into Virtual Machine Provisioning
 
Harnessing the Power of Google Cloud Platform: Strategies and Applications
Harnessing the Power of Google Cloud Platform: Strategies and ApplicationsHarnessing the Power of Google Cloud Platform: Strategies and Applications
Harnessing the Power of Google Cloud Platform: Strategies and Applications
 
Scheduling in Cloud Computing
Scheduling in Cloud ComputingScheduling in Cloud Computing
Scheduling in Cloud Computing
 
Cloud-Case study
Cloud-Case study Cloud-Case study
Cloud-Case study
 
RAID
RAIDRAID
RAID
 
Load balancing in cloud computing.pptx
Load balancing in cloud computing.pptxLoad balancing in cloud computing.pptx
Load balancing in cloud computing.pptx
 
Cluster Computing
Cluster ComputingCluster Computing
Cluster Computing
 
ITU-T requirement for cloud and cloud deployment model
ITU-T requirement for cloud and cloud deployment modelITU-T requirement for cloud and cloud deployment model
ITU-T requirement for cloud and cloud deployment model
 
Leetcode Problem Solution
Leetcode Problem SolutionLeetcode Problem Solution
Leetcode Problem Solution
 
Leetcode Problem Solution
Leetcode Problem SolutionLeetcode Problem Solution
Leetcode Problem Solution
 
Trie Data Structure
Trie Data Structure Trie Data Structure
Trie Data Structure
 
Reviewing basic concepts of relational database
Reviewing basic concepts of relational databaseReviewing basic concepts of relational database
Reviewing basic concepts of relational database
 
Reviewing SQL Concepts
Reviewing SQL ConceptsReviewing SQL Concepts
Reviewing SQL Concepts
 
Advanced database protocols
Advanced database protocolsAdvanced database protocols
Advanced database protocols
 
Measures of query cost
Measures of query costMeasures of query cost
Measures of query cost
 
Involvement of WSN in Smart Cities
Involvement of WSN in Smart CitiesInvolvement of WSN in Smart Cities
Involvement of WSN in Smart Cities
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
 
Reinforcement Learning / E-Book / Part 1
Reinforcement Learning / E-Book / Part 1Reinforcement Learning / E-Book / Part 1
Reinforcement Learning / E-Book / Part 1
 
5G
5G5G
5G
 

Recently uploaded

Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 

Recently uploaded (20)

Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 

Order Objects in PowerShell Using Sort-Object

  • 1. 1 LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT 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
  • 2. 2 LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT 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
  • 3. 3 LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT Creates an instance of a Microsoft .NET Framework or COM object. New-Object [-TypeName] <String> [[-ArgumentList] <Object[]>] [-Property <IDictionary>] [<CommonParameters>] New-Object [-ComObject] <String> [-Strict] [-Property <IDictionary>] [<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
  • 4. 4 LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT 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
  • 5. 5 LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT 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
  • 6. 6 LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT 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.
  • 7. 7 LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT 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
  • 8. 8 LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT 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
  • 9. 9 LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT 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:Windowssystem32> 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:Windowssystem32> 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.
  • 10. 10 LAB 2 // Hitesh Mohapatra // ACM // MCA // SCT 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/