SlideShare a Scribd company logo
Windows PowerShell An introduction to...
Dale Lane [email_address] IBM Hursley Park
What is Windows PowerShell? How does PowerShell work? How can I 'hack' PowerShell so that  it can be used with my product? Agenda
What is Windows PowerShell?
What is Windows PowerShell for?
What is Windows PowerShell for? ADMIN
What is Windows PowerShell for? ADMIN Building GUIs on  top of PowerShell
What is Windows PowerShell for? ADMIN Interactive  command shell
What is Windows PowerShell for? ADMIN Scripting
What is Windows PowerShell for? ADMIN COM Scripting  for WMI
What is Windows PowerShell for? ADMIN
How does PowerShell  work?
 
 
Get-Process
Get-Process
a verb a noun Get-Process
http://msdn2.microsoft.com/en-us/library/ms714428.aspx The verbs
The verbs Consistent Learnable Readable
 
Get-Process |  Where { $_.Handles -gt 500 } |  Sort Handles | Format-Table
HELP!
HELP! Get-Command Get-Help Get-PSDrive Get-Members
 
What command do I need?
 
How does it work?
How does it work?
How does it work?
How does it work?
How does it work?
 
 
 
 
 
 
 
Consistent Get-Process |  Where { $_.Handles -gt 500 } |  Sort Handles | Format-Table
 
What data stores are available?
 
Windows Registry
 
Certificates
 
Environment variables
 
Variables
'dir' ?
 
Aliases
 
 
Stopping a process kill -9 `ps -aef  | grep 'notepad'  | grep -v grep  | awk '{print $2}'`
Stopping a process kill -9 `ps -aef  | grep 'notepad'  | grep -v grep  | awk '{print $2}'` Why so complicated?
Stopping a process Get-Process notepad  | Stop-Process
Stopping a process Get-Process notepad  | Stop-Process Why so much easier?
 
 
 
 
 
 
 
 
 
Select Where Sort Compare
 
 
 
 
 
 
 
 
-Confirm -Verbose -WhatIf -Debug
 
 
 
 
Get-Process | Export-Csv
 
 
 
 
 
 
Using .NET
 
 
 
 
 
 
 
 
 
([xml](new-object Net.WebClient) .DownloadString ($bbc_news_rss_url)).rss.channel.item | Select title, Desc*, *date  -first 8
 
 
 
How can I  “ hack” PowerShell?
Why?
WebSphere MQ “ Queue” “ Message” “ Queue  Manager”
 
a verb a noun Get-Process
a verb product  name object  type http://msdn2.microsoft.com/en-us/library/ms714657.aspx Get-ProdObject
 
 
“ Some of the queues used by the sales team are getting a bit full. Can you increase the amount of space in them?”
“ Some of the queues used by the sales team are getting a bit full. Can you increase the amount of space in them?”
“ Some of the queues used by the sales team are getting a bit full. Can you increase the amount of space in them?”
“ Some of the queues used by the sales team are getting a bit full. Can you increase the amount of space in them?”
 
Get-Command Get-*WMQ*Queue
Get-WMQQueue
Where {$_.Name -like “SALES.*”  -and  $_.CurrentDepth -gt  ($_.MaximumDepth - 10)}
Select Name,  CurrentDepth,  MaximumDepth
 
 
ForEach-Object -process  {Set-WMQQueue $_  -MaximumDepth  ($_.MaximumDepth * 2)}
ForEach-Object -process  {Set-WMQQueue $_  -MaximumDepth  ($_.MaximumDepth * 2)}
 
 
Get-Member
 
 
Where {$_.CreationDateTime  -ge $(Get-Date -month 10 -day 15 -year 2007) -and  $_.CreationDateTime -le $(Get-Date -month 10 -day 20 -year 2007)}
“ Set the maximum depth for all cluster queues that start with a letter between 'D' and 'K'to 20.”
“ Set the maximum depth for all cluster queues that start with a letter between 'D' and 'K'to 20.” Get-WMQQueue * * | Where  {$_.Name -like "[D-K]*" -and $_.ClusterName -ne ''}  | Set-WMQQueue -MaximumDepth 20
“ Set the maximum depth for all cluster queues that start with a letter between 'D' and 'K'to 20.” Get-WMQQueue * * | Where  {$_.Name -like "[D-K]*" -and $_.ClusterName -ne ''}  | Set-WMQQueue -MAXDEPTH 20
“ Get a list of non-system sender channels, showing the name, connection name, transmission queue, SSL Cipher Spec, and the name of the queue manager it is on.”
“ Get a list of non-system sender channels, showing the name, connection name, transmission queue, SSL Cipher Spec, and the name of the queue manager it is on.” Get-WMQChannel * * | Where {$_.ChannelType -eq [IBM.WMQ.MQC]::MQCHT_SENDER -and $_.Name -match  "^(?!SYSTEM).*"} | Select Name, Conn*Name, Trans*Name, SSLCiph*, @{e={$_.QueueManager.Name};n='Host'}  Name  ConnectionName  TransmissionQueueName  SSLCipherSpec  Host  ----  --------------  ---------------------  -------------  ----  SECURE  dlane.hursley.ibm.com(9090)  TRANS1  NULL_MD5  post  SECURE.R  dlane.hursley.ibm.com(9091)  TRANSR  TRIPLE_DES_SHA_US  test
Export-CSV ConvertTo-HTML
How?
 
What can I do with PowerShell? Ad-hoc scripts Production scripts
What can I do with PowerShell? Ad-hoc scripts Production scripts
What can I do with PowerShell? Ad-hoc scripts Production scripts
What can I do with PowerShell? try stuff out in an interactive shell tie a few things together in utilities build commands up into a script generalize (parameterize, etc.) clean up and productize share!
Ad-hoc function Get-WMQQueue ($qmgr) { # display details of any WMQ errors encountered in this function Trap [IBM.WMQ.MQException] { Write-Error ("WMQ Exception: CC=" + $_.Exception.CompletionCode +    "  RC=" + $_.Exception.ReasonCode) continue } # if we have a connection to a queue manager... if ($qmgr -ne $null) { $qNames = Get-WMQQueueNames($qmgr) foreach ($queuename in $qNames) { $nextQueue = $qmgr.AccessQueue($queuename.Trim(), [IBM.WMQ.MQC]::MQOO_INQUIRE) Write-Output $nextQueue } } else { Write-Host "No queue manager connection" } }
Ad-hoc function Get-WMQQueue ($qmgr) { # display details of any WMQ errors encountered in this function Trap [IBM.WMQ.MQException] { Write-Error ("WMQ Exception: CC=" + $_.Exception.CompletionCode +    "  RC=" + $_.Exception.ReasonCode) continue } # if we have a connection to a queue manager... if ($qmgr -ne $null) { $qNames = Get-WMQQueueNames($qmgr) foreach ($queuename in $qNames) { $nextQueue = $qmgr.AccessQueue($queuename.Trim(), [IBM.WMQ.MQC]::MQOO_INQUIRE) Write-Output $nextQueue } } else { Write-Host "No queue manager connection" } }
Ad-hoc function Get-WMQQueue ($qmgr) { # display details of any WMQ errors encountered in this function Trap [IBM.WMQ.MQException] { Write-Error ("WMQ Exception: CC=" + $_.Exception.CompletionCode +    "  RC=" + $_.Exception.ReasonCode) continue } # if we have a connection to a queue manager... if ($qmgr -ne $null) { $qNames = Get-WMQQueueNames($qmgr) foreach ($queuename in $qNames) { $nextQueue = $qmgr.AccessQueue($queuename.Trim(), [IBM.WMQ.MQC]::MQOO_INQUIRE) Write-Output $nextQueue } } else { Write-Host "No queue manager connection" } }
Ad-hoc function Get-WMQQueue ($qmgr) { # display details of any WMQ errors encountered in this function Trap [IBM.WMQ.MQException] { Write-Error ("WMQ Exception: CC=" + $_.Exception.CompletionCode +    "  RC=" + $_.Exception.ReasonCode) continue } # if we have a connection to a queue manager... if ($qmgr -ne $null) { $qNames = Get-WMQQueueNames($qmgr) foreach ($queuename in $qNames) { $nextQueue = $qmgr.AccessQueue($queuename.Trim(), [IBM.WMQ.MQC]::MQOO_INQUIRE) Write-Output $nextQueue } } else { Write-Host "No queue manager connection" } }
Ad-hoc function Get-WMQQueueManager($name, $hostname, $port, $svrconn) { # display details of any WMQ errors encountered in this function Trap [IBM.WMQ.MQException] { Write-Error ("WMQ Exception: CC=" + $_.Exception.CompletionCode +    " RC=" + $_.Exception.ReasonCode) continue } # hashtable to describe the connection to the queue manager $connProperties = New-Object System.Collections.Hashtable if (($hostname -eq $null) -and ($port -eq $null) -and ($svrconn -eq $null)) { # user has not provided any information for a client connection #  so we default to a local bindings connection type  $connProperties.Add([string][IBM.WMQ.MQC]::TRANSPORT_PROPERTY, [string][IBM.WMQ.MQC]::TRANSPORT_MQSERIES_BINDINGS) }
Ad-hoc else { # user has provided some information for a client connection # # a future version of this should provide support for other #  connection types (e.g. managed or XA client) but for #  my initial purposes, bindings and client connections are #  sufficient $connProperties.Add([string][IBM.WMQ.MQC]::TRANSPORT_PROPERTY, [string][IBM.WMQ.MQC]::TRANSPORT_MQSERIES_CLIENT) if ($hostname -ne $null) { $connProperties.Add([string][IBM.WMQ.MQC]::HOST_NAME_PROPERTY, $hostname) }
Ad-hoc if ($svrconn -ne $null) { $connProperties.Add([string][IBM.WMQ.MQC]::CHANNEL_PROPERTY, $svrconn) } else { # use a sensible default #  this wont be to everyone's tastes, but will often be #  right for me, and will save me a lot of typing! $connProperties.Add([string][IBM.WMQ.MQC]::CHANNEL_PROPERTY, "SYSTEM.DEF.SVRCONN") }
Ad-hoc if ($port -ne $null) { $connProperties.Add([string][IBM.WMQ.MQC]::PORT_PROPERTY, $port) } else { # use a sensible default #  this wont be to everyone's tastes, but will often be #  right for me, and will save me a lot of typing! $connProperties.Add([string][IBM.WMQ.MQC]::PORT_PROPERTY, "1414") } } return New-Object IBM.WMQ.MQQueueManager($name, $connProperties) }
Ad-hoc function Get-WMQQueueNames($qmgr) { # display details of any WMQ errors encountered in this function Trap [IBM.WMQ.MQException] { Write-Error ("WMQ Exception: CC=" + $_.Exception.CompletionCode +    " RC=" + $_.Exception.ReasonCode) continue } # if we have a connection to a queue manager... if ($qmgr -ne $null) { # using PCF to access a list of queue names # # this is sort of cheating - this is an undocumented, unsupported # API, and I wrote this using tab-complete to identify what # seems like sensible method names # # please do *not* take this as any sort of IBM recommendation # or endorsement to use PCF in C# # [IBM.WMQ.PCF.PCFMessageAgent]$agent =  New-Object IBM.WMQ.PCF.PCFMessageAgent $agent.Connect($qmgr)
Ad-hoc [IBM.WMQ.PCF.PCFMessage]$request =  New-Object IBM.WMQ.PCF.PCFMessage([IBM.WMQ.MQC]::MQCMD_INQUIRE_Q_NAMES) $request.AddParameter([IBM.WMQ.MQC]::MQCA_Q_NAME,   "*") $request.AddParameter([IBM.WMQ.MQC]::MQIA_Q_TYPE,   [IBM.WMQ.MQC]::MQQT_LOCAL)   [IBM.WMQ.PCF.PCFMessage[]]$responses = $agent.Send($request, $TRUE) [IBM.WMQ.PCF.PCFParameter[]]$pcfParms = $responses[0].GetParameters() $queueNames = $pcfParms[0].GetValue() # we don't want to display temporary queues # (such as that which will have been created by the PCF command!) # so we filter the response array before returning it return $queueNames | Where-Object -FilterScript {$_ -notlike "AMQ.*"} } else { Write-Host "No queue manager" } }
Ad-hoc
http://channel9.msdn.com/ShowPost.aspx?PostID=256835 Production
Production “ How to Create a Windows PowerShell Cmdlet”  walkthrough http://msdn2.microsoft.com/en-us/library/ms714598.aspx
Production “ How to Create a Windows PowerShell Cmdlet”  walkthrough http://msdn2.microsoft.com/en-us/library/ms714598.aspx “ PowerShell Cmdlet guidelines”  http://msdn2.microsoft.com/en-us/library/ms714657.aspx
Production #region GetProcCommand /// <summary> /// This class implements a Get-Proc cmdlet that has no parameters. /// </summary> [Cmdlet(VerbsCommon.Get, &quot;Proc&quot;)] public class GetProcCommand : Cmdlet  { #region Cmdlet Overrides /// <summary> /// For each of the requested process names, retrieve and write /// the associated processes. /// </summary> protected override void ProcessRecord() { // Get the current processes Process[] processes = Process.GetProcesses(); // Write the processes to the pipeline making them available to the // next cmdlet. The second parameter tells PowerShell to enumerate the // array, and send one process at a time to the pipeline WriteObject(processes, true); } #endregion Overrides } #endregion GetProcCommand
Production
Production
Production
What can I do with PowerShell? try stuff out in an interactive shell tie a few things together in utilities build commands up into a script generalize (parameterize, etc.) clean up and productize share!
 
 
Extending function --> scripts and Cmdlets Extending data stores --> providers Extending PowerShell
 
What is Windows PowerShell? How does PowerShell work? How can I hack PowerShell so that  it can be used with my product? Recap
Dale Lane [email_address] IBM Hursley Park Windows PowerShell An introduction to...

More Related Content

PPTX
Lec 01_Linux System Administration (1).pptx
PDF
Powershell training material
PPT
Introduction to PowerShell
PPTX
PowerShell-1
PPTX
Presentation On Group Policy in Windows Server 2012 R2 By Barek-IT
PPTX
Linux Server vs Windows Server
PPTX
History of Windows Server
PPT
Chapter07 Advanced File System Management
Lec 01_Linux System Administration (1).pptx
Powershell training material
Introduction to PowerShell
PowerShell-1
Presentation On Group Policy in Windows Server 2012 R2 By Barek-IT
Linux Server vs Windows Server
History of Windows Server
Chapter07 Advanced File System Management

What's hot (20)

PPTX
Powershell Demo Presentation
PPTX
PowerShell: Automation for Everyone
ODP
Introduction to Nginx
PDF
Ansible
PPT
Docker introduction
PPTX
NGINX: High Performance Load Balancing
PPTX
Microsoft Azure - Introduction
PPTX
PDF
[오픈소스컨설팅] 쿠버네티스와 쿠버네티스 on 오픈스택 비교 및 구축 방법
PPT
Php Presentation
PDF
Introduction to PowerShell
PPTX
Introduction to docker
PDF
CouchDB
PPTX
WORDPRESS
PPTX
An introduction to Serverless
PDF
[OpenInfra Days Korea 2018] (Track 1) TACO (SKT All Container OpenStack): Clo...
PPTX
Jenkins tutorial
PPTX
IBM DataPower Gateways - What's new in 2016 v7.5.2
PDF
Docker vs VM | | Containerization or Virtualization - The Differences | DevOp...
PDF
CI/CD with Jenkins and Docker - DevOps Meetup Day Thailand
Powershell Demo Presentation
PowerShell: Automation for Everyone
Introduction to Nginx
Ansible
Docker introduction
NGINX: High Performance Load Balancing
Microsoft Azure - Introduction
[오픈소스컨설팅] 쿠버네티스와 쿠버네티스 on 오픈스택 비교 및 구축 방법
Php Presentation
Introduction to PowerShell
Introduction to docker
CouchDB
WORDPRESS
An introduction to Serverless
[OpenInfra Days Korea 2018] (Track 1) TACO (SKT All Container OpenStack): Clo...
Jenkins tutorial
IBM DataPower Gateways - What's new in 2016 v7.5.2
Docker vs VM | | Containerization or Virtualization - The Differences | DevOp...
CI/CD with Jenkins and Docker - DevOps Meetup Day Thailand
Ad

Viewers also liked (20)

PPTX
Introduction To Windows Power Shell
PDF
HBaseCon 2012 | HBase Schema Design - Ian Varley, Salesforce
PDF
[DSC x TAAI 2016] 林守德 / 人工智慧與機器學習在推薦系統上的應用
PDF
State of Startups 2016
PPT
Understanding text-structure-powerpoint
PDF
How To Become... LORD OF THE SLIDES
PPT
Cardiac cycle ppt (2)
PPTX
4. heredity and evolution
PPTX
Windows PowerShell
PDF
LTE Basics
PDF
The Ultimate Guide to Creating Visually Appealing Content
PPTX
The beauty of fashion.ppt
PPTX
Why apache Flink is the 4G of Big Data Analytics Frameworks
PDF
World Class Manufacturing:Plant Start Up and Commissioning Procedure
PPTX
Building an Empire with PowerShell
PDF
Business model canvas sw lisbon14
PPTX
Decision making between anterior skull base & lateral skull base
PPTX
Top 10 Global Future Trends 2015 - Roger James Hamilton
PPTX
Ancient Egypt PowerPoint
PPT
Core Java Slides
Introduction To Windows Power Shell
HBaseCon 2012 | HBase Schema Design - Ian Varley, Salesforce
[DSC x TAAI 2016] 林守德 / 人工智慧與機器學習在推薦系統上的應用
State of Startups 2016
Understanding text-structure-powerpoint
How To Become... LORD OF THE SLIDES
Cardiac cycle ppt (2)
4. heredity and evolution
Windows PowerShell
LTE Basics
The Ultimate Guide to Creating Visually Appealing Content
The beauty of fashion.ppt
Why apache Flink is the 4G of Big Data Analytics Frameworks
World Class Manufacturing:Plant Start Up and Commissioning Procedure
Building an Empire with PowerShell
Business model canvas sw lisbon14
Decision making between anterior skull base & lateral skull base
Top 10 Global Future Trends 2015 - Roger James Hamilton
Ancient Egypt PowerPoint
Core Java Slides
Ad

Similar to An Introduction to Windows PowerShell (20)

ODP
An introduction-to-windows-powershell-1193007253563204-3
PDF
IBM IMPACT 2014 - AMC-1883 - Where's My Message - Analyze IBM WebSphere MQ Re...
PDF
WMQ Toolbox: 20 Scripts, One-liners, & Utilities for UNIX & Windows
PDF
Websphere MQ (MQSeries) fundamentals
PDF
IBM MQ Appliance - Administration simplified
PDF
MQ V8004 Summary
PPTX
Introduction to powershell
PPTX
New Tools and Interfaces for Managing IBM MQ
PPTX
Wsv406 Advanced Automation Using Windows Power Shell2.0
PDF
MQ What's New Beyond V8 - V8003 level
PPT
WebSphere MQ introduction
PDF
OSMC 2009 | Windows monitoring - Going where no man has gone before... by Mic...
PDF
3450 - Writing and optimising applications for performance in a hybrid messag...
PDF
Where is My Message?: Use MQ Tools to Work Out What Applications Have Done
PDF
IBM MQ Basics
PDF
DataPower-MQ Integration Deep Dive
PDF
Mq ssl channels_on_windows
PPTX
Introducing PowerShell 3.0
PPSX
Sunil phani's take on windows powershell
PPTX
Powershell Tech Ed2009
An introduction-to-windows-powershell-1193007253563204-3
IBM IMPACT 2014 - AMC-1883 - Where's My Message - Analyze IBM WebSphere MQ Re...
WMQ Toolbox: 20 Scripts, One-liners, & Utilities for UNIX & Windows
Websphere MQ (MQSeries) fundamentals
IBM MQ Appliance - Administration simplified
MQ V8004 Summary
Introduction to powershell
New Tools and Interfaces for Managing IBM MQ
Wsv406 Advanced Automation Using Windows Power Shell2.0
MQ What's New Beyond V8 - V8003 level
WebSphere MQ introduction
OSMC 2009 | Windows monitoring - Going where no man has gone before... by Mic...
3450 - Writing and optimising applications for performance in a hybrid messag...
Where is My Message?: Use MQ Tools to Work Out What Applications Have Done
IBM MQ Basics
DataPower-MQ Integration Deep Dive
Mq ssl channels_on_windows
Introducing PowerShell 3.0
Sunil phani's take on windows powershell
Powershell Tech Ed2009

More from Dale Lane (20)

PDF
Describing Kafka security in AsyncAPI
PDF
Our NASA Space Apps Challenge 2019 entry
PDF
Useful Kafka tools
PDF
An intro to serverless and OpenWhisk for Kafka users
PDF
How to increase the social impact you make
PDF
Introducing Machine Learning to Kids
PDF
Introducing machine learning to kids
PPTX
Small Spaces, Big Ideas - our Space Apps Challenge
PDF
Owls
PDF
The skills implications of Cognitive Computing
PDF
Conversational Internet - Creating a natural language interface for web pages
PDF
Debugging Web Apps on Real Mobile Devices
PDF
GaianDB
PPT
Pushing, pulling or leaving the door open
PDF
Push notifications
PPT
Fire Eagle Guest Pass
PDF
Monitoring your electricity usage
PPT
CurrentCost
PPT
An introduction to Windows Mobile development
PPT
Mowing the lawn
Describing Kafka security in AsyncAPI
Our NASA Space Apps Challenge 2019 entry
Useful Kafka tools
An intro to serverless and OpenWhisk for Kafka users
How to increase the social impact you make
Introducing Machine Learning to Kids
Introducing machine learning to kids
Small Spaces, Big Ideas - our Space Apps Challenge
Owls
The skills implications of Cognitive Computing
Conversational Internet - Creating a natural language interface for web pages
Debugging Web Apps on Real Mobile Devices
GaianDB
Pushing, pulling or leaving the door open
Push notifications
Fire Eagle Guest Pass
Monitoring your electricity usage
CurrentCost
An introduction to Windows Mobile development
Mowing the lawn

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
A Presentation on Artificial Intelligence
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Modernizing your data center with Dell and AMD
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PPT
Teaching material agriculture food technology
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Unlocking AI with Model Context Protocol (MCP)
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
NewMind AI Weekly Chronicles - August'25 Week I
Agricultural_Statistics_at_a_Glance_2022_0.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Building Integrated photovoltaic BIPV_UPV.pdf
Approach and Philosophy of On baking technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
A Presentation on Artificial Intelligence
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
The AUB Centre for AI in Media Proposal.docx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Modernizing your data center with Dell and AMD
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Chapter 3 Spatial Domain Image Processing.pdf
NewMind AI Monthly Chronicles - July 2025
Teaching material agriculture food technology
Spectral efficient network and resource selection model in 5G networks
Unlocking AI with Model Context Protocol (MCP)

An Introduction to Windows PowerShell

  • 1. Windows PowerShell An introduction to...
  • 2. Dale Lane [email_address] IBM Hursley Park
  • 3. What is Windows PowerShell? How does PowerShell work? How can I 'hack' PowerShell so that it can be used with my product? Agenda
  • 4. What is Windows PowerShell?
  • 5. What is Windows PowerShell for?
  • 6. What is Windows PowerShell for? ADMIN
  • 7. What is Windows PowerShell for? ADMIN Building GUIs on top of PowerShell
  • 8. What is Windows PowerShell for? ADMIN Interactive command shell
  • 9. What is Windows PowerShell for? ADMIN Scripting
  • 10. What is Windows PowerShell for? ADMIN COM Scripting for WMI
  • 11. What is Windows PowerShell for? ADMIN
  • 13.  
  • 14.  
  • 17. a verb a noun Get-Process
  • 19. The verbs Consistent Learnable Readable
  • 20.  
  • 21. Get-Process | Where { $_.Handles -gt 500 } | Sort Handles | Format-Table
  • 22. HELP!
  • 23. HELP! Get-Command Get-Help Get-PSDrive Get-Members
  • 24.  
  • 25. What command do I need?
  • 26.  
  • 27. How does it work?
  • 28. How does it work?
  • 29. How does it work?
  • 30. How does it work?
  • 31. How does it work?
  • 32.  
  • 33.  
  • 34.  
  • 35.  
  • 36.  
  • 37.  
  • 38.  
  • 39. Consistent Get-Process | Where { $_.Handles -gt 500 } | Sort Handles | Format-Table
  • 40.  
  • 41. What data stores are available?
  • 42.  
  • 44.  
  • 46.  
  • 48.  
  • 51.  
  • 53.  
  • 54.  
  • 55. Stopping a process kill -9 `ps -aef | grep 'notepad' | grep -v grep | awk '{print $2}'`
  • 56. Stopping a process kill -9 `ps -aef | grep 'notepad' | grep -v grep | awk '{print $2}'` Why so complicated?
  • 57. Stopping a process Get-Process notepad | Stop-Process
  • 58. Stopping a process Get-Process notepad | Stop-Process Why so much easier?
  • 59.  
  • 60.  
  • 61.  
  • 62.  
  • 63.  
  • 64.  
  • 65.  
  • 66.  
  • 67.  
  • 68. Select Where Sort Compare
  • 69.  
  • 70.  
  • 71.  
  • 72.  
  • 73.  
  • 74.  
  • 75.  
  • 76.  
  • 78.  
  • 79.  
  • 80.  
  • 81.  
  • 83.  
  • 84.  
  • 85.  
  • 86.  
  • 87.  
  • 88.  
  • 90.  
  • 91.  
  • 92.  
  • 93.  
  • 94.  
  • 95.  
  • 96.  
  • 97.  
  • 98.  
  • 99. ([xml](new-object Net.WebClient) .DownloadString ($bbc_news_rss_url)).rss.channel.item | Select title, Desc*, *date -first 8
  • 100.  
  • 101.  
  • 102.  
  • 103. How can I “ hack” PowerShell?
  • 104. Why?
  • 105. WebSphere MQ “ Queue” “ Message” “ Queue Manager”
  • 106.  
  • 107. a verb a noun Get-Process
  • 108. a verb product name object type http://msdn2.microsoft.com/en-us/library/ms714657.aspx Get-ProdObject
  • 109.  
  • 110.  
  • 111. “ Some of the queues used by the sales team are getting a bit full. Can you increase the amount of space in them?”
  • 112. “ Some of the queues used by the sales team are getting a bit full. Can you increase the amount of space in them?”
  • 113. “ Some of the queues used by the sales team are getting a bit full. Can you increase the amount of space in them?”
  • 114. “ Some of the queues used by the sales team are getting a bit full. Can you increase the amount of space in them?”
  • 115.  
  • 118. Where {$_.Name -like “SALES.*” -and $_.CurrentDepth -gt ($_.MaximumDepth - 10)}
  • 119. Select Name, CurrentDepth, MaximumDepth
  • 120.  
  • 121.  
  • 122. ForEach-Object -process {Set-WMQQueue $_ -MaximumDepth ($_.MaximumDepth * 2)}
  • 123. ForEach-Object -process {Set-WMQQueue $_ -MaximumDepth ($_.MaximumDepth * 2)}
  • 124.  
  • 125.  
  • 127.  
  • 128.  
  • 129. Where {$_.CreationDateTime -ge $(Get-Date -month 10 -day 15 -year 2007) -and $_.CreationDateTime -le $(Get-Date -month 10 -day 20 -year 2007)}
  • 130. “ Set the maximum depth for all cluster queues that start with a letter between 'D' and 'K'to 20.”
  • 131. “ Set the maximum depth for all cluster queues that start with a letter between 'D' and 'K'to 20.” Get-WMQQueue * * | Where {$_.Name -like &quot;[D-K]*&quot; -and $_.ClusterName -ne ''} | Set-WMQQueue -MaximumDepth 20
  • 132. “ Set the maximum depth for all cluster queues that start with a letter between 'D' and 'K'to 20.” Get-WMQQueue * * | Where {$_.Name -like &quot;[D-K]*&quot; -and $_.ClusterName -ne ''} | Set-WMQQueue -MAXDEPTH 20
  • 133. “ Get a list of non-system sender channels, showing the name, connection name, transmission queue, SSL Cipher Spec, and the name of the queue manager it is on.”
  • 134. “ Get a list of non-system sender channels, showing the name, connection name, transmission queue, SSL Cipher Spec, and the name of the queue manager it is on.” Get-WMQChannel * * | Where {$_.ChannelType -eq [IBM.WMQ.MQC]::MQCHT_SENDER -and $_.Name -match &quot;^(?!SYSTEM).*&quot;} | Select Name, Conn*Name, Trans*Name, SSLCiph*, @{e={$_.QueueManager.Name};n='Host'} Name ConnectionName TransmissionQueueName SSLCipherSpec Host ---- -------------- --------------------- ------------- ---- SECURE dlane.hursley.ibm.com(9090) TRANS1 NULL_MD5 post SECURE.R dlane.hursley.ibm.com(9091) TRANSR TRIPLE_DES_SHA_US test
  • 136. How?
  • 137.  
  • 138. What can I do with PowerShell? Ad-hoc scripts Production scripts
  • 139. What can I do with PowerShell? Ad-hoc scripts Production scripts
  • 140. What can I do with PowerShell? Ad-hoc scripts Production scripts
  • 141. What can I do with PowerShell? try stuff out in an interactive shell tie a few things together in utilities build commands up into a script generalize (parameterize, etc.) clean up and productize share!
  • 142. Ad-hoc function Get-WMQQueue ($qmgr) { # display details of any WMQ errors encountered in this function Trap [IBM.WMQ.MQException] { Write-Error (&quot;WMQ Exception: CC=&quot; + $_.Exception.CompletionCode + &quot; RC=&quot; + $_.Exception.ReasonCode) continue } # if we have a connection to a queue manager... if ($qmgr -ne $null) { $qNames = Get-WMQQueueNames($qmgr) foreach ($queuename in $qNames) { $nextQueue = $qmgr.AccessQueue($queuename.Trim(), [IBM.WMQ.MQC]::MQOO_INQUIRE) Write-Output $nextQueue } } else { Write-Host &quot;No queue manager connection&quot; } }
  • 143. Ad-hoc function Get-WMQQueue ($qmgr) { # display details of any WMQ errors encountered in this function Trap [IBM.WMQ.MQException] { Write-Error (&quot;WMQ Exception: CC=&quot; + $_.Exception.CompletionCode + &quot; RC=&quot; + $_.Exception.ReasonCode) continue } # if we have a connection to a queue manager... if ($qmgr -ne $null) { $qNames = Get-WMQQueueNames($qmgr) foreach ($queuename in $qNames) { $nextQueue = $qmgr.AccessQueue($queuename.Trim(), [IBM.WMQ.MQC]::MQOO_INQUIRE) Write-Output $nextQueue } } else { Write-Host &quot;No queue manager connection&quot; } }
  • 144. Ad-hoc function Get-WMQQueue ($qmgr) { # display details of any WMQ errors encountered in this function Trap [IBM.WMQ.MQException] { Write-Error (&quot;WMQ Exception: CC=&quot; + $_.Exception.CompletionCode + &quot; RC=&quot; + $_.Exception.ReasonCode) continue } # if we have a connection to a queue manager... if ($qmgr -ne $null) { $qNames = Get-WMQQueueNames($qmgr) foreach ($queuename in $qNames) { $nextQueue = $qmgr.AccessQueue($queuename.Trim(), [IBM.WMQ.MQC]::MQOO_INQUIRE) Write-Output $nextQueue } } else { Write-Host &quot;No queue manager connection&quot; } }
  • 145. Ad-hoc function Get-WMQQueue ($qmgr) { # display details of any WMQ errors encountered in this function Trap [IBM.WMQ.MQException] { Write-Error (&quot;WMQ Exception: CC=&quot; + $_.Exception.CompletionCode + &quot; RC=&quot; + $_.Exception.ReasonCode) continue } # if we have a connection to a queue manager... if ($qmgr -ne $null) { $qNames = Get-WMQQueueNames($qmgr) foreach ($queuename in $qNames) { $nextQueue = $qmgr.AccessQueue($queuename.Trim(), [IBM.WMQ.MQC]::MQOO_INQUIRE) Write-Output $nextQueue } } else { Write-Host &quot;No queue manager connection&quot; } }
  • 146. Ad-hoc function Get-WMQQueueManager($name, $hostname, $port, $svrconn) { # display details of any WMQ errors encountered in this function Trap [IBM.WMQ.MQException] { Write-Error (&quot;WMQ Exception: CC=&quot; + $_.Exception.CompletionCode + &quot; RC=&quot; + $_.Exception.ReasonCode) continue } # hashtable to describe the connection to the queue manager $connProperties = New-Object System.Collections.Hashtable if (($hostname -eq $null) -and ($port -eq $null) -and ($svrconn -eq $null)) { # user has not provided any information for a client connection # so we default to a local bindings connection type $connProperties.Add([string][IBM.WMQ.MQC]::TRANSPORT_PROPERTY, [string][IBM.WMQ.MQC]::TRANSPORT_MQSERIES_BINDINGS) }
  • 147. Ad-hoc else { # user has provided some information for a client connection # # a future version of this should provide support for other # connection types (e.g. managed or XA client) but for # my initial purposes, bindings and client connections are # sufficient $connProperties.Add([string][IBM.WMQ.MQC]::TRANSPORT_PROPERTY, [string][IBM.WMQ.MQC]::TRANSPORT_MQSERIES_CLIENT) if ($hostname -ne $null) { $connProperties.Add([string][IBM.WMQ.MQC]::HOST_NAME_PROPERTY, $hostname) }
  • 148. Ad-hoc if ($svrconn -ne $null) { $connProperties.Add([string][IBM.WMQ.MQC]::CHANNEL_PROPERTY, $svrconn) } else { # use a sensible default # this wont be to everyone's tastes, but will often be # right for me, and will save me a lot of typing! $connProperties.Add([string][IBM.WMQ.MQC]::CHANNEL_PROPERTY, &quot;SYSTEM.DEF.SVRCONN&quot;) }
  • 149. Ad-hoc if ($port -ne $null) { $connProperties.Add([string][IBM.WMQ.MQC]::PORT_PROPERTY, $port) } else { # use a sensible default # this wont be to everyone's tastes, but will often be # right for me, and will save me a lot of typing! $connProperties.Add([string][IBM.WMQ.MQC]::PORT_PROPERTY, &quot;1414&quot;) } } return New-Object IBM.WMQ.MQQueueManager($name, $connProperties) }
  • 150. Ad-hoc function Get-WMQQueueNames($qmgr) { # display details of any WMQ errors encountered in this function Trap [IBM.WMQ.MQException] { Write-Error (&quot;WMQ Exception: CC=&quot; + $_.Exception.CompletionCode + &quot; RC=&quot; + $_.Exception.ReasonCode) continue } # if we have a connection to a queue manager... if ($qmgr -ne $null) { # using PCF to access a list of queue names # # this is sort of cheating - this is an undocumented, unsupported # API, and I wrote this using tab-complete to identify what # seems like sensible method names # # please do *not* take this as any sort of IBM recommendation # or endorsement to use PCF in C# # [IBM.WMQ.PCF.PCFMessageAgent]$agent = New-Object IBM.WMQ.PCF.PCFMessageAgent $agent.Connect($qmgr)
  • 151. Ad-hoc [IBM.WMQ.PCF.PCFMessage]$request = New-Object IBM.WMQ.PCF.PCFMessage([IBM.WMQ.MQC]::MQCMD_INQUIRE_Q_NAMES) $request.AddParameter([IBM.WMQ.MQC]::MQCA_Q_NAME, &quot;*&quot;) $request.AddParameter([IBM.WMQ.MQC]::MQIA_Q_TYPE, [IBM.WMQ.MQC]::MQQT_LOCAL) [IBM.WMQ.PCF.PCFMessage[]]$responses = $agent.Send($request, $TRUE) [IBM.WMQ.PCF.PCFParameter[]]$pcfParms = $responses[0].GetParameters() $queueNames = $pcfParms[0].GetValue() # we don't want to display temporary queues # (such as that which will have been created by the PCF command!) # so we filter the response array before returning it return $queueNames | Where-Object -FilterScript {$_ -notlike &quot;AMQ.*&quot;} } else { Write-Host &quot;No queue manager&quot; } }
  • 152. Ad-hoc
  • 154. Production “ How to Create a Windows PowerShell Cmdlet” walkthrough http://msdn2.microsoft.com/en-us/library/ms714598.aspx
  • 155. Production “ How to Create a Windows PowerShell Cmdlet” walkthrough http://msdn2.microsoft.com/en-us/library/ms714598.aspx “ PowerShell Cmdlet guidelines” http://msdn2.microsoft.com/en-us/library/ms714657.aspx
  • 156. Production #region GetProcCommand /// <summary> /// This class implements a Get-Proc cmdlet that has no parameters. /// </summary> [Cmdlet(VerbsCommon.Get, &quot;Proc&quot;)] public class GetProcCommand : Cmdlet { #region Cmdlet Overrides /// <summary> /// For each of the requested process names, retrieve and write /// the associated processes. /// </summary> protected override void ProcessRecord() { // Get the current processes Process[] processes = Process.GetProcesses(); // Write the processes to the pipeline making them available to the // next cmdlet. The second parameter tells PowerShell to enumerate the // array, and send one process at a time to the pipeline WriteObject(processes, true); } #endregion Overrides } #endregion GetProcCommand
  • 160. What can I do with PowerShell? try stuff out in an interactive shell tie a few things together in utilities build commands up into a script generalize (parameterize, etc.) clean up and productize share!
  • 161.  
  • 162.  
  • 163. Extending function --> scripts and Cmdlets Extending data stores --> providers Extending PowerShell
  • 164.  
  • 165. What is Windows PowerShell? How does PowerShell work? How can I hack PowerShell so that it can be used with my product? Recap
  • 166. Dale Lane [email_address] IBM Hursley Park Windows PowerShell An introduction to...