SlideShare ist ein Scribd-Unternehmen logo
1 von 61
The Art of PowerShell
Toolmaking
Kurt Roggen [BE]
Principal Consultant
me@kurtroggen.be
about_KurtRoggen
Agenda
• Modules… Modules… Modules
• Module Creation
• Module Management
Module Creation
3 cmdlets to know/remember!!
PowerShell is self-discoverable using
1. Get-Command
2. Get-Help
3. Get-Member
#1. Get-Command
Displays all commands (cmdlet, function, alias)
• Get-Command
• Get-Command -Verb get
• Get-Command -Noun service
• Get-Command -Module ActiveDirectory
• Get-Command -CmdType cmdlet
• Get-Command -Syntax
Alias: gcm
#2. Get-Help
Displays help information
• Get-Help
• Get-Help get-service
• Get-Help get-service -Examples
• Get-Help get-service -Detailed
• Get-Help get-service -Full
• Get-Help get-service -Online
• Get-Help get-service -Parameter ComputerName
• Get-Help * -Parameter ComputerName
• Get-Help about_wildcards
Alias: help
#3. Get-Member
Displays object model with all MemberTypes
(Property, Method, AliasProperty, ScriptMethod, ...)
• Get-Service | Get-Member
• Get-Member –InputType (Get-Service)
• Get-Member –MemberType Method
• Get-Member –MemberType Property
Alias: gm
Get-Member
Consistency… Consistency… Consistency!
• Consistent behavior across all PowerShell cmdlets
• For Cmdlet naming
• For Parameter usage and naming
• For Object (model) and Property/Method naming
• Makes learning and remembering faster and easier
“Think – Type – Get”
Cmdlet Naming
• Use strict Verb-<Prefix>SingularNoun convention
– Make guessing easy  “Think – Type – Get”
• Use only approved verbs
– PowerShell warns about unapproved verbs at module load time
– Approved verbs: Get-verb
• Workaround
– Define alias, using New-Alias –Name <VerbAlias-Noun> -Value <cmdlet>
Parameter Naming
• Use consistent parameter names across all cmdlets
• Examples:
-ComputerName
-CimSession
-Name
• Parameter name should match object names
• Workaround
– Define alias parameter
Object Model and Property Naming
• Parameter name should match object names
• Workaround
– Define “Alias Property”
• Example:
– ‘Name’ (alias)property
Module Anatomy
PowerShell Module Anatomy
ModuleName
(directory)
ModuleName.psd1
(module manifest)
ModuleName.psm1
(module script)
*.dll
(binaries)
*.ps1
(scripts)
*.Format.ps1xml
*.Types.ps1xml
(format & type extensions)
Resources
(help, languages, Pester,
snippets, DSC, ...)
PowerShell Module Components
Module Script - .PSM1
• Create PS module folder
• Save PS module as
.PSM1 instead of .PS1
– PS module folder name
must match PS module file
name
• Locations
– $env:PSModulePath
Module Manifest – .PSD1
• Metadata about module
– Version, Author,
– Formats, Types
– Export Aliases, Variables,
Functions, …
– Requirements
• PS Host, Version, .NET, CLR
• Required for publishing to
PowerShell Gallery
• Cmdlet: New-ModuleManifest
DEMO
What do you export from your module?
Defined in PSM1
Using Export-ModuleMember
-Alias *
-Variable *DivaNET*, DIVA*
-Function *
Overrides psd1 keywords
Defined in PSD1
Using keywords “*ToExport”:
• FunctionsToExport = '*'
• CmdletsToExport = '*'
• AliasesToExport = '*'
• VariablesToExport = '*'
Decide what information to export from your module
• Function
• Aliases
• Variables
Help
Create your own Help
Provide specific help information for
• Function usage (Description, Synopsis)
• Parameters
• Examples
• Related functions (Link)
Provide general help information for topics or modules
• about_<topic>.help.txt
• about_<module>.help.txt ()
PowerShell Help Options
Comment Based Help
• Internal help
– Included in script/module
– Based on .keywords inside
comment block
• Simple
XML Based Help (MAML)
• External help
– Separate help files
– Supports multi-language
• More complex
– Tools: SAPIEN PowerShell Help
Writer
• Supports updatable help
– Requires HelpInfoURI
keyword in module manifest
Comment Based Help
Function Get-OS
{
<#
.SYNOPSIS
<This is what the function is does>
.DESCRIPTION
<This is what the function does but more detailed.>
.PARAMETER ComputerName
<Describe each parameter purpose and usage>
.EXAMPLE
Get-OS
Will retrieve the OS version of the computer.
.LINK
http://mysite.com/get-os/
.LINK
Get-ServicePack
Get-BIOS
#>
Param (
[string]$ComputerName,
[switch]$Details
)
about_Comment_Based_Help
https://technet.microsoft.com/en-us/library/hh847834.aspx
Use ISE Snippets (Control+J)
Updatable XML based Help
• XML based – MAML
• Requires several components
– .psd1 – keyword HelpInfoURI
– HelpInfo.xml
– .psm1-Help.xml file
– CAB file
• Syntax: ModuleName_ModuleGUID_UI-Culture_HelpContent.cab
• Example: TestModule_d03c1cf3-f738-48a3-b845-5ead46a52671_en-US_HelpContent.cab
about_Updatable_Help - https://technet.microsoft.com/en-us/library/hh847735.aspx
https://msdn.microsoft.com/en-us/library/windows/desktop/hh852735(v=vs.85).aspx
SAPIEN PowerShell HelpWriter 2016
• For writing and editing Windows PowerShell help files.
• Can convert comment-based help to MAML files.
Objects
Create your own objects
• Naming of Property, Method
• Add additional members
– AliasProperty
– ScriptProperty
– ScriptMethod
Create your own Objects
Using Add-Member
• New-Object PSObject
• Add-Member `
-Name <Name> `
-Value <Value> `
-MemberType <Type>
• Allows AliasProperty,
ScriptProperty,
ScriptMethod
Using New-Object with HashTable
• New-Object –TypeName
PSObject –Property
$<HashTable>
• Using Type casting
$Obj=[pscustomobject][ordered]@{
ComputerName = $ComputerName
Value = ‘abc’
}
• Makes code more readable
Create PS Object
Using New-Object and Add-Member
$Obj = New-Object –Type PSObject
$Obj | Add-Member –Name ComputerName –Value $ComputerName –Type NoteProperty
$Obj | Add-Member –Name OS –Value $OS –Type NoteProperty
$Obj | Add-Member –Name ServicePack –Value $ServicePack –Type NoteProperty
$Obj | Add-Member –Name Version –Value $ComputerName –Type NoteProperty
$Obj | Add-Member –Name Name –Value Version –Type AliasProperty
Return PS Object (to pipeline)
$Obj
Create PS Object
Using Hashtable
$Properties = @{
Name = “Kurt”
LastName = “Roggen”
FullName = “Kurt Roggen”
ComputerName = “$env:COMPUTERNAME”
}
$Obj = New-Object –Type PSObject –Property $Properties
Return PS Object (to pipeline)
$Obj
Create your own Object Type
$Obj = New-Object –Type PSObject
$Obj.PSTypeNames.Insert(0,’myModule.Computer’)
Related methods:
• $Object.PSTypeNames.Add(‘myModule.Computer’)
• $Object.PSTypeNames.Remove(‘myModule.Computer’)
Extend your own Objects
Using Add-Member
• Simple
• Explicit
• Straight forward
Using <Module>.types.PS1XML
• Advanced
• Implicit
• Requires TypesToProcess
keyword in module manifest
Extend your own Objects
Using Add-Member
$obj = [pscustomobject]@{Name='Kurt Roggen'; FirstName='Kurt'; LastName='Roggen'}
With AliasProperty
Add-Member -InputObject $obj -MemberType AliasProperty -Name FullName
-Value Name
With ScriptProperty
Add-Member -InputObject $obj -MemberType ScriptProperty -Name MyFullName
-Value { $this.Firstname + ' ' + $this.LastName.ToUpper() }
With ScriptMethod
Add-Member -InputObject $obj -MemberType ScriptMethod -Name GetAddress
-Value $function:GetAddress
$obj.GetAddress()
DEMO
Extend your own Objects
Using types.ps1xml file
• Extends object type
– Defines additional members (properties and methods)
• Using XML file <ModuleName>.types.PS1XML
– Create from default PowerShell type files as template
• Requires “TypesToProcess” keyword in module
manifest
about_Types
https://technet.microsoft.com/en-us/library/hh847881.aspx
Support the Pipeline
Accept Pipeline Input using “ValueFromPipeline”
function Get-OS
{
param(
[Parameter(ValueFromPipeLine)]
[string[]]$ComputerName = $env:COMPUTERNAME
)
PROCESS
{
<foreach $Computer in $ComputerName…>
}
}
Support the Pipeline
Accept Pipeline Input using “ValueFromPipelineByPropertyName”
function Get-OS
{
param(
[Parameter(ValueFromPipeLineByPropertyName)]
[string[]]$ComputerName = $env:COMPUTERNAME
)
PROCESS
{
<foreach $Computer in $ComputerName…>
}
}
Views/Formats
Create your own view/format
• Apply custom view/format onto objects
• format.PS1XML file
– Formatting definitions
– Create from default PowerShell (format) views
• View Types
– Table view (format-table)
– List view (format-list)
• Requires keyword FormatsToProcess in module manifest
about_Format.ps1xml
https://technet.microsoft.com/en-us/library/hh847831.aspx
DEMO
Parameters
Parameter Usage
• Use Advanced Functions with Common Parameters
• Use Parameter Sets
• Use Validation Sets
Use “Common Parameters”
• Parameters provided by PowerShell
• Using [CmdletBinding()]
• -Verbose, -Debug, -ErrorAction, -OutVariable, …
• [CmdletBinding()]
-WhatIf, -Confirm
• [CmdletBinding(SupportsShouldProcess=$true,
ConfirmImpact='High')]
about_CommonParameters
https://technet.microsoft.com/en-us/library/hh847884.aspx
Use “Switch” parameters
• Provide -Passthru switch for Set-*, Add-* alike cmdlets
function Unregister-MySoftwarePackage
{
param(
[Parameter(Mandatory=$true]
[Alias('Name')]
[string]$PackageName,
[switch]$Force,
[switch]$Passthru
)
Rename-Item -Path $FilePath -NewName $NewName -PassThru:$PassThru
}
Use parameter Aliases
• Improves parameters self-discovery
• Allows object matching from pipeline
param(
[Parameter(Mandatory=$true)]
[Alias('Name')]
[string]$PackageName
)
Use Parameter Validation
• [ValidateSet(<ValidationSet>)]
– Provides validation using defined ‘Validation Set’
– Validated at execution by PowerShell
– Provides information to intellisense auto-completion
param(
[ValidateSet('Information','Warning','Error')]
[string]$EventType = 'Information‘ )
• [ValidateScript(<scriptblock>)]
– Provides validation using script block
param(
[ValidateScript({Test-Path –Path $Path})]
[string]$Path )
• [ValidatePattern(<regex>)]
Build Argument Completion
PowerShell Syntax:
<Cmdlet> -Parameter <argument>
Argument Completion
Argument Completion
• Syntax: Verb-<Prefix>Noun –Parameter <argument>
• Available for both PS ISE and PS CLI*
Building Argument Completion
Approaches
#1 Using module ‘TabExpansionPlusPlus’
• Module: TabExpansionPlusPlus
• Cmdlets
– Register-ArgumentCompleter
– New-CompletionResult
PS compat: PS v3 - v5
• Installation: PowerShellGet
Install-Module TabExpansionPlusPlus
#2 Using native PowerShell
• Module: n/a
• Cmdlets
– Register-ArgumentCompleter
– New-Object
System.Management.Automation.CompletionResult
• PS compat: PS v5
Building Argument Completion
Using native PowerShell
Helper function
Register Argument completer
Argument completer function
DEMO
Building Argument Completion
Using [System.Management.Automation.CompletionResult]
• New-CompletionResult command takes three parameters:
1. CompletionText: The text inserted on completion
2. ListItemText: The text displayed in completion dropdown
3. Tooltip : The tooltip for items in ISE completion dropdown.
Building Argument Completion
Using TabExpansionPlusPlus
• Provides Argument Completers for most common
PowerShell modules
• Appx
• Azure
• CimCmdlets
• Dism
• DFS-N, DFS-R
• DHCP Server
• DNS Client, DNS Server
• FailoverClustering
• Group Policy
• LocalAccounts
• NetAdapter, NetSecurity
• NetLBFO, NetQoS
• PrintManagement
• PnPDevice
• PackageManagement
• PowerShell Core
• PowerShellGet
• PowerShellDirect
• SmbShare
• SCVMM
• DataONTAP
Available on GitHub at
http://github.com/lzybkr/TabExpansionPlusPlus
DEMO
Others
Building Snippets
• Include code snippets in module
– Subfolder “Snippets”
– Files syntax: <module>.snippets.ps1xml
• Cmdlets
– New-ISESnippet
– Import-ISESnippet –Module <module> -ListAvailable
– Get-ISESnippet
Building “Proxy Functions”
• Complex – Modify default behaviour of cmdlets
• Use only when needed.
Module Management
Public PowerShell Gallery
• External repository for PowerShell resources
– Modules, scripts, DSC resources
URL: http://www.powershellgallery.com
Module Management
Package Management (OneGet) versus PowerShellGet
Package Management
Allows automation of SDII (Software Discovery, Installation & Inventory)
PowerShellGet
Package management for
PowerShell resources
• Modules
• Scripts
• DSC resources
Module Management
SDII (Software Discovery, Installation & Inventory)
• Find resources
– Find-Module
– Find-Script
– Find-DscResource
• Install resources
– Install-Module
– Install-Script
• Get resources
– Installed-Module
– Installed-Script
Module Management
Publishing PowerShell resources
• Publish resources to PSGallery
– Publish-Module
– Publish-Script
• Requires
– (NuGet) API key
– Module manifest (Version, Author, LicenseURI)
Private PowerShell Gallery
• Internal trusted repository for PowerShell resources
• Currently in preview on GitHub
Summary
• Provide consistent behavior across all PowerShell
cmdlets
• Provide consistency for
– For Cmdlet naming
– For Parameter usage and naming
– For Object (model) and Property/Method naming
• Makes learning and remembering faster and easier
Special thanks to our sponsors
Belgiums’ biggest IT PRO Conference

Weitere ähnliche Inhalte

Was ist angesagt?

Ant_quick_guide
Ant_quick_guideAnt_quick_guide
Ant_quick_guideducquoc_vn
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans Fabrizio Giudici
 
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Modernizing the Ext JS Class System - Don GriffinSenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Modernizing the Ext JS Class System - Don GriffinSencha
 
PyGrunn 2017 - Django Performance Unchained - slides
PyGrunn 2017 - Django Performance Unchained - slidesPyGrunn 2017 - Django Performance Unchained - slides
PyGrunn 2017 - Django Performance Unchained - slidesArtur Barseghyan
 
Decoupled Libraries for PHP
Decoupled Libraries for PHPDecoupled Libraries for PHP
Decoupled Libraries for PHPPaul Jones
 
Getting started with Django 1.8
Getting started with Django 1.8Getting started with Django 1.8
Getting started with Django 1.8rajkumar2011
 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery ObjectsSteve Wells
 
PyPedia
PyPediaPyPedia
PyPediakantale
 
KAAccessControl
KAAccessControlKAAccessControl
KAAccessControlWO Community
 
Crud operations using aws dynamo db with flask ap is and boto3
Crud operations using aws dynamo db with flask ap is and boto3Crud operations using aws dynamo db with flask ap is and boto3
Crud operations using aws dynamo db with flask ap is and boto3Katy Slemon
 
Utopia Kindgoms scaling case: From 4 to 50K users
Utopia Kindgoms scaling case: From 4 to 50K usersUtopia Kindgoms scaling case: From 4 to 50K users
Utopia Kindgoms scaling case: From 4 to 50K usersJaime Buelta
 
20100425 Configuration Management With Puppet Lfnw
20100425 Configuration Management With Puppet Lfnw20100425 Configuration Management With Puppet Lfnw
20100425 Configuration Management With Puppet Lfnwgarrett honeycutt
 
Database madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyDatabase madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyJaime Buelta
 
Modules Building Presentation
Modules Building PresentationModules Building Presentation
Modules Building Presentationhtyson
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engineWO Community
 
User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014Robert Stupp
 
Extending WordPress. Making use of Custom Post Types
Extending WordPress. Making use of Custom Post TypesExtending WordPress. Making use of Custom Post Types
Extending WordPress. Making use of Custom Post TypesUtsav Singh Rathour
 
PyFilesystem
PyFilesystemPyFilesystem
PyFilesystemAndreas Jung
 
20090514 Introducing Puppet To Sasag
20090514 Introducing Puppet To Sasag20090514 Introducing Puppet To Sasag
20090514 Introducing Puppet To Sasaggarrett honeycutt
 

Was ist angesagt? (20)

Ant_quick_guide
Ant_quick_guideAnt_quick_guide
Ant_quick_guide
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
 
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Modernizing the Ext JS Class System - Don GriffinSenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
 
PyGrunn 2017 - Django Performance Unchained - slides
PyGrunn 2017 - Django Performance Unchained - slidesPyGrunn 2017 - Django Performance Unchained - slides
PyGrunn 2017 - Django Performance Unchained - slides
 
Decoupled Libraries for PHP
Decoupled Libraries for PHPDecoupled Libraries for PHP
Decoupled Libraries for PHP
 
Getting started with Django 1.8
Getting started with Django 1.8Getting started with Django 1.8
Getting started with Django 1.8
 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery Objects
 
PyPedia
PyPediaPyPedia
PyPedia
 
java script
java scriptjava script
java script
 
KAAccessControl
KAAccessControlKAAccessControl
KAAccessControl
 
Crud operations using aws dynamo db with flask ap is and boto3
Crud operations using aws dynamo db with flask ap is and boto3Crud operations using aws dynamo db with flask ap is and boto3
Crud operations using aws dynamo db with flask ap is and boto3
 
Utopia Kindgoms scaling case: From 4 to 50K users
Utopia Kindgoms scaling case: From 4 to 50K usersUtopia Kindgoms scaling case: From 4 to 50K users
Utopia Kindgoms scaling case: From 4 to 50K users
 
20100425 Configuration Management With Puppet Lfnw
20100425 Configuration Management With Puppet Lfnw20100425 Configuration Management With Puppet Lfnw
20100425 Configuration Management With Puppet Lfnw
 
Database madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemyDatabase madness with_mongoengine_and_sql_alchemy
Database madness with_mongoengine_and_sql_alchemy
 
Modules Building Presentation
Modules Building PresentationModules Building Presentation
Modules Building Presentation
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
 
User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014
 
Extending WordPress. Making use of Custom Post Types
Extending WordPress. Making use of Custom Post TypesExtending WordPress. Making use of Custom Post Types
Extending WordPress. Making use of Custom Post Types
 
PyFilesystem
PyFilesystemPyFilesystem
PyFilesystem
 
20090514 Introducing Puppet To Sasag
20090514 Introducing Puppet To Sasag20090514 Introducing Puppet To Sasag
20090514 Introducing Puppet To Sasag
 

Ähnlich wie ITPROceed 2016 - The Art of PowerShell Toolmaking

PowerShell 101
PowerShell 101PowerShell 101
PowerShell 101Thomas Lee
 
Unleashing Creative Freedom with MODX (2015-09-03 at GroningenPHP)
Unleashing Creative Freedom with MODX (2015-09-03 at GroningenPHP)Unleashing Creative Freedom with MODX (2015-09-03 at GroningenPHP)
Unleashing Creative Freedom with MODX (2015-09-03 at GroningenPHP)Mark Hamstra
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration TestersNikhil Mittal
 
MWLUG 2015 - AD114 Take Your XPages Development to the Next Level
MWLUG 2015 - AD114 Take Your XPages Development to the Next LevelMWLUG 2015 - AD114 Take Your XPages Development to the Next Level
MWLUG 2015 - AD114 Take Your XPages Development to the Next Levelbalassaitis
 
ExtBase workshop
ExtBase workshop ExtBase workshop
ExtBase workshop schmutt
 
Unleashing Creative Freedom with MODX (2015-07-21 @ PHP FRL)
Unleashing Creative Freedom with MODX (2015-07-21 @ PHP FRL)Unleashing Creative Freedom with MODX (2015-07-21 @ PHP FRL)
Unleashing Creative Freedom with MODX (2015-07-21 @ PHP FRL)Mark Hamstra
 
Unleashing Creative Freedom with MODX (2015-09-08 at PHPAmersfoort)
Unleashing Creative Freedom with MODX (2015-09-08 at PHPAmersfoort)Unleashing Creative Freedom with MODX (2015-09-08 at PHPAmersfoort)
Unleashing Creative Freedom with MODX (2015-09-08 at PHPAmersfoort)Mark Hamstra
 
O365con14 - powershell for exchange administrators
O365con14 - powershell for exchange administratorsO365con14 - powershell for exchange administrators
O365con14 - powershell for exchange administratorsNCCOMMS
 
Modul-Entwicklung fĂźr Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung fĂźr Magento, OXID eShop und Shopware (2013)Modul-Entwicklung fĂźr Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung fĂźr Magento, OXID eShop und Shopware (2013)Roman Zenner
 
Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Drupalcon Paris
 
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and ToolingSencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and ToolingSencha
 
PowerShell - Be A Cool Blue Kid
PowerShell - Be A Cool Blue KidPowerShell - Be A Cool Blue Kid
PowerShell - Be A Cool Blue KidMatthew Johnson
 
Automating Content Import
Automating Content ImportAutomating Content Import
Automating Content ImportDavid Lippman
 
Powershell For Developers
Powershell For DevelopersPowershell For Developers
Powershell For DevelopersIdo Flatow
 
Pysys testframework
Pysys testframeworkPysys testframework
Pysys testframeworkMoray Grieve
 
Powershell Training
Powershell TrainingPowershell Training
Powershell TrainingFahad Noaman
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoFu Cheng
 

Ähnlich wie ITPROceed 2016 - The Art of PowerShell Toolmaking (20)

The Power of PowerShell: Advanced
The Power of PowerShell: Advanced The Power of PowerShell: Advanced
The Power of PowerShell: Advanced
 
PowerShell 101
PowerShell 101PowerShell 101
PowerShell 101
 
Unleashing Creative Freedom with MODX (2015-09-03 at GroningenPHP)
Unleashing Creative Freedom with MODX (2015-09-03 at GroningenPHP)Unleashing Creative Freedom with MODX (2015-09-03 at GroningenPHP)
Unleashing Creative Freedom with MODX (2015-09-03 at GroningenPHP)
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration Testers
 
MWLUG 2015 - AD114 Take Your XPages Development to the Next Level
MWLUG 2015 - AD114 Take Your XPages Development to the Next LevelMWLUG 2015 - AD114 Take Your XPages Development to the Next Level
MWLUG 2015 - AD114 Take Your XPages Development to the Next Level
 
ExtBase workshop
ExtBase workshop ExtBase workshop
ExtBase workshop
 
Unleashing Creative Freedom with MODX (2015-07-21 @ PHP FRL)
Unleashing Creative Freedom with MODX (2015-07-21 @ PHP FRL)Unleashing Creative Freedom with MODX (2015-07-21 @ PHP FRL)
Unleashing Creative Freedom with MODX (2015-07-21 @ PHP FRL)
 
Unleashing Creative Freedom with MODX (2015-09-08 at PHPAmersfoort)
Unleashing Creative Freedom with MODX (2015-09-08 at PHPAmersfoort)Unleashing Creative Freedom with MODX (2015-09-08 at PHPAmersfoort)
Unleashing Creative Freedom with MODX (2015-09-08 at PHPAmersfoort)
 
O365con14 - powershell for exchange administrators
O365con14 - powershell for exchange administratorsO365con14 - powershell for exchange administrators
O365con14 - powershell for exchange administrators
 
Modul-Entwicklung fĂźr Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung fĂźr Magento, OXID eShop und Shopware (2013)Modul-Entwicklung fĂźr Magento, OXID eShop und Shopware (2013)
Modul-Entwicklung fĂźr Magento, OXID eShop und Shopware (2013)
 
Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3
 
CodeIgniter & MVC
CodeIgniter & MVCCodeIgniter & MVC
CodeIgniter & MVC
 
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and ToolingSencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
Sencha Roadshow 2017: Modernizing the Ext JS Class System and Tooling
 
PowerShell - Be A Cool Blue Kid
PowerShell - Be A Cool Blue KidPowerShell - Be A Cool Blue Kid
PowerShell - Be A Cool Blue Kid
 
Automating Content Import
Automating Content ImportAutomating Content Import
Automating Content Import
 
Powershell For Developers
Powershell For DevelopersPowershell For Developers
Powershell For Developers
 
Pysys testframework
Pysys testframeworkPysys testframework
Pysys testframework
 
Powershell Training
Powershell TrainingPowershell Training
Powershell Training
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 

KĂźrzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 

KĂźrzlich hochgeladen (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

ITPROceed 2016 - The Art of PowerShell Toolmaking

  • 1. The Art of PowerShell Toolmaking Kurt Roggen [BE] Principal Consultant me@kurtroggen.be
  • 3. Agenda • Modules… Modules… Modules • Module Creation • Module Management
  • 5. 3 cmdlets to know/remember!! PowerShell is self-discoverable using 1. Get-Command 2. Get-Help 3. Get-Member
  • 6. #1. Get-Command Displays all commands (cmdlet, function, alias) • Get-Command • Get-Command -Verb get • Get-Command -Noun service • Get-Command -Module ActiveDirectory • Get-Command -CmdType cmdlet • Get-Command -Syntax Alias: gcm
  • 7. #2. Get-Help Displays help information • Get-Help • Get-Help get-service • Get-Help get-service -Examples • Get-Help get-service -Detailed • Get-Help get-service -Full • Get-Help get-service -Online • Get-Help get-service -Parameter ComputerName • Get-Help * -Parameter ComputerName • Get-Help about_wildcards Alias: help
  • 8. #3. Get-Member Displays object model with all MemberTypes (Property, Method, AliasProperty, ScriptMethod, ...) • Get-Service | Get-Member • Get-Member –InputType (Get-Service) • Get-Member –MemberType Method • Get-Member –MemberType Property Alias: gm
  • 10. Consistency… Consistency… Consistency! • Consistent behavior across all PowerShell cmdlets • For Cmdlet naming • For Parameter usage and naming • For Object (model) and Property/Method naming • Makes learning and remembering faster and easier “Think – Type – Get”
  • 11. Cmdlet Naming • Use strict Verb-<Prefix>SingularNoun convention – Make guessing easy  “Think – Type – Get” • Use only approved verbs – PowerShell warns about unapproved verbs at module load time – Approved verbs: Get-verb • Workaround – Define alias, using New-Alias –Name <VerbAlias-Noun> -Value <cmdlet>
  • 12. Parameter Naming • Use consistent parameter names across all cmdlets • Examples: -ComputerName -CimSession -Name • Parameter name should match object names • Workaround – Define alias parameter
  • 13. Object Model and Property Naming • Parameter name should match object names • Workaround – Define “Alias Property” • Example: – ‘Name’ (alias)property
  • 15. PowerShell Module Anatomy ModuleName (directory) ModuleName.psd1 (module manifest) ModuleName.psm1 (module script) *.dll (binaries) *.ps1 (scripts) *.Format.ps1xml *.Types.ps1xml (format & type extensions) Resources (help, languages, Pester, snippets, DSC, ...)
  • 16. PowerShell Module Components Module Script - .PSM1 • Create PS module folder • Save PS module as .PSM1 instead of .PS1 – PS module folder name must match PS module file name • Locations – $env:PSModulePath Module Manifest – .PSD1 • Metadata about module – Version, Author, – Formats, Types – Export Aliases, Variables, Functions, … – Requirements • PS Host, Version, .NET, CLR • Required for publishing to PowerShell Gallery • Cmdlet: New-ModuleManifest DEMO
  • 17. What do you export from your module? Defined in PSM1 Using Export-ModuleMember -Alias * -Variable *DivaNET*, DIVA* -Function * Overrides psd1 keywords Defined in PSD1 Using keywords “*ToExport”: • FunctionsToExport = '*' • CmdletsToExport = '*' • AliasesToExport = '*' • VariablesToExport = '*' Decide what information to export from your module • Function • Aliases • Variables
  • 18. Help
  • 19. Create your own Help Provide specific help information for • Function usage (Description, Synopsis) • Parameters • Examples • Related functions (Link) Provide general help information for topics or modules • about_<topic>.help.txt • about_<module>.help.txt ()
  • 20. PowerShell Help Options Comment Based Help • Internal help – Included in script/module – Based on .keywords inside comment block • Simple XML Based Help (MAML) • External help – Separate help files – Supports multi-language • More complex – Tools: SAPIEN PowerShell Help Writer • Supports updatable help – Requires HelpInfoURI keyword in module manifest
  • 21. Comment Based Help Function Get-OS { <# .SYNOPSIS <This is what the function is does> .DESCRIPTION <This is what the function does but more detailed.> .PARAMETER ComputerName <Describe each parameter purpose and usage> .EXAMPLE Get-OS Will retrieve the OS version of the computer. .LINK http://mysite.com/get-os/ .LINK Get-ServicePack Get-BIOS #> Param ( [string]$ComputerName, [switch]$Details ) about_Comment_Based_Help https://technet.microsoft.com/en-us/library/hh847834.aspx Use ISE Snippets (Control+J)
  • 22. Updatable XML based Help • XML based – MAML • Requires several components – .psd1 – keyword HelpInfoURI – HelpInfo.xml – .psm1-Help.xml file – CAB file • Syntax: ModuleName_ModuleGUID_UI-Culture_HelpContent.cab • Example: TestModule_d03c1cf3-f738-48a3-b845-5ead46a52671_en-US_HelpContent.cab about_Updatable_Help - https://technet.microsoft.com/en-us/library/hh847735.aspx https://msdn.microsoft.com/en-us/library/windows/desktop/hh852735(v=vs.85).aspx
  • 23. SAPIEN PowerShell HelpWriter 2016 • For writing and editing Windows PowerShell help files. • Can convert comment-based help to MAML files.
  • 25. Create your own objects • Naming of Property, Method • Add additional members – AliasProperty – ScriptProperty – ScriptMethod
  • 26. Create your own Objects Using Add-Member • New-Object PSObject • Add-Member ` -Name <Name> ` -Value <Value> ` -MemberType <Type> • Allows AliasProperty, ScriptProperty, ScriptMethod Using New-Object with HashTable • New-Object –TypeName PSObject –Property $<HashTable> • Using Type casting $Obj=[pscustomobject][ordered]@{ ComputerName = $ComputerName Value = ‘abc’ } • Makes code more readable
  • 27. Create PS Object Using New-Object and Add-Member $Obj = New-Object –Type PSObject $Obj | Add-Member –Name ComputerName –Value $ComputerName –Type NoteProperty $Obj | Add-Member –Name OS –Value $OS –Type NoteProperty $Obj | Add-Member –Name ServicePack –Value $ServicePack –Type NoteProperty $Obj | Add-Member –Name Version –Value $ComputerName –Type NoteProperty $Obj | Add-Member –Name Name –Value Version –Type AliasProperty Return PS Object (to pipeline) $Obj
  • 28. Create PS Object Using Hashtable $Properties = @{ Name = “Kurt” LastName = “Roggen” FullName = “Kurt Roggen” ComputerName = “$env:COMPUTERNAME” } $Obj = New-Object –Type PSObject –Property $Properties Return PS Object (to pipeline) $Obj
  • 29. Create your own Object Type $Obj = New-Object –Type PSObject $Obj.PSTypeNames.Insert(0,’myModule.Computer’) Related methods: • $Object.PSTypeNames.Add(‘myModule.Computer’) • $Object.PSTypeNames.Remove(‘myModule.Computer’)
  • 30. Extend your own Objects Using Add-Member • Simple • Explicit • Straight forward Using <Module>.types.PS1XML • Advanced • Implicit • Requires TypesToProcess keyword in module manifest
  • 31. Extend your own Objects Using Add-Member $obj = [pscustomobject]@{Name='Kurt Roggen'; FirstName='Kurt'; LastName='Roggen'} With AliasProperty Add-Member -InputObject $obj -MemberType AliasProperty -Name FullName -Value Name With ScriptProperty Add-Member -InputObject $obj -MemberType ScriptProperty -Name MyFullName -Value { $this.Firstname + ' ' + $this.LastName.ToUpper() } With ScriptMethod Add-Member -InputObject $obj -MemberType ScriptMethod -Name GetAddress -Value $function:GetAddress $obj.GetAddress()
  • 32. DEMO Extend your own Objects Using types.ps1xml file • Extends object type – Defines additional members (properties and methods) • Using XML file <ModuleName>.types.PS1XML – Create from default PowerShell type files as template • Requires “TypesToProcess” keyword in module manifest about_Types https://technet.microsoft.com/en-us/library/hh847881.aspx
  • 33. Support the Pipeline Accept Pipeline Input using “ValueFromPipeline” function Get-OS { param( [Parameter(ValueFromPipeLine)] [string[]]$ComputerName = $env:COMPUTERNAME ) PROCESS { <foreach $Computer in $ComputerName…> } }
  • 34. Support the Pipeline Accept Pipeline Input using “ValueFromPipelineByPropertyName” function Get-OS { param( [Parameter(ValueFromPipeLineByPropertyName)] [string[]]$ComputerName = $env:COMPUTERNAME ) PROCESS { <foreach $Computer in $ComputerName…> } }
  • 36. Create your own view/format • Apply custom view/format onto objects • format.PS1XML file – Formatting definitions – Create from default PowerShell (format) views • View Types – Table view (format-table) – List view (format-list) • Requires keyword FormatsToProcess in module manifest about_Format.ps1xml https://technet.microsoft.com/en-us/library/hh847831.aspx DEMO
  • 38. Parameter Usage • Use Advanced Functions with Common Parameters • Use Parameter Sets • Use Validation Sets
  • 39. Use “Common Parameters” • Parameters provided by PowerShell • Using [CmdletBinding()] • -Verbose, -Debug, -ErrorAction, -OutVariable, … • [CmdletBinding()] -WhatIf, -Confirm • [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')] about_CommonParameters https://technet.microsoft.com/en-us/library/hh847884.aspx
  • 40. Use “Switch” parameters • Provide -Passthru switch for Set-*, Add-* alike cmdlets function Unregister-MySoftwarePackage { param( [Parameter(Mandatory=$true] [Alias('Name')] [string]$PackageName, [switch]$Force, [switch]$Passthru ) Rename-Item -Path $FilePath -NewName $NewName -PassThru:$PassThru }
  • 41. Use parameter Aliases • Improves parameters self-discovery • Allows object matching from pipeline param( [Parameter(Mandatory=$true)] [Alias('Name')] [string]$PackageName )
  • 42. Use Parameter Validation • [ValidateSet(<ValidationSet>)] – Provides validation using defined ‘Validation Set’ – Validated at execution by PowerShell – Provides information to intellisense auto-completion param( [ValidateSet('Information','Warning','Error')] [string]$EventType = 'Information‘ ) • [ValidateScript(<scriptblock>)] – Provides validation using script block param( [ValidateScript({Test-Path –Path $Path})] [string]$Path ) • [ValidatePattern(<regex>)]
  • 43. Build Argument Completion PowerShell Syntax: <Cmdlet> -Parameter <argument>
  • 45. Argument Completion • Syntax: Verb-<Prefix>Noun –Parameter <argument> • Available for both PS ISE and PS CLI*
  • 46. Building Argument Completion Approaches #1 Using module ‘TabExpansionPlusPlus’ • Module: TabExpansionPlusPlus • Cmdlets – Register-ArgumentCompleter – New-CompletionResult PS compat: PS v3 - v5 • Installation: PowerShellGet Install-Module TabExpansionPlusPlus #2 Using native PowerShell • Module: n/a • Cmdlets – Register-ArgumentCompleter – New-Object System.Management.Automation.CompletionResult • PS compat: PS v5
  • 47. Building Argument Completion Using native PowerShell Helper function Register Argument completer Argument completer function DEMO
  • 48. Building Argument Completion Using [System.Management.Automation.CompletionResult] • New-CompletionResult command takes three parameters: 1. CompletionText: The text inserted on completion 2. ListItemText: The text displayed in completion dropdown 3. Tooltip : The tooltip for items in ISE completion dropdown.
  • 49. Building Argument Completion Using TabExpansionPlusPlus • Provides Argument Completers for most common PowerShell modules • Appx • Azure • CimCmdlets • Dism • DFS-N, DFS-R • DHCP Server • DNS Client, DNS Server • FailoverClustering • Group Policy • LocalAccounts • NetAdapter, NetSecurity • NetLBFO, NetQoS • PrintManagement • PnPDevice • PackageManagement • PowerShell Core • PowerShellGet • PowerShellDirect • SmbShare • SCVMM • DataONTAP Available on GitHub at http://github.com/lzybkr/TabExpansionPlusPlus DEMO
  • 51. Building Snippets • Include code snippets in module – Subfolder “Snippets” – Files syntax: <module>.snippets.ps1xml • Cmdlets – New-ISESnippet – Import-ISESnippet –Module <module> -ListAvailable – Get-ISESnippet
  • 52. Building “Proxy Functions” • Complex – Modify default behaviour of cmdlets • Use only when needed.
  • 54. Public PowerShell Gallery • External repository for PowerShell resources – Modules, scripts, DSC resources URL: http://www.powershellgallery.com
  • 55. Module Management Package Management (OneGet) versus PowerShellGet Package Management Allows automation of SDII (Software Discovery, Installation & Inventory) PowerShellGet Package management for PowerShell resources • Modules • Scripts • DSC resources
  • 56. Module Management SDII (Software Discovery, Installation & Inventory) • Find resources – Find-Module – Find-Script – Find-DscResource • Install resources – Install-Module – Install-Script • Get resources – Installed-Module – Installed-Script
  • 57. Module Management Publishing PowerShell resources • Publish resources to PSGallery – Publish-Module – Publish-Script • Requires – (NuGet) API key – Module manifest (Version, Author, LicenseURI)
  • 58. Private PowerShell Gallery • Internal trusted repository for PowerShell resources • Currently in preview on GitHub
  • 59. Summary • Provide consistent behavior across all PowerShell cmdlets • Provide consistency for – For Cmdlet naming – For Parameter usage and naming – For Object (model) and Property/Method naming • Makes learning and remembering faster and easier
  • 60. Special thanks to our sponsors
  • 61. Belgiums’ biggest IT PRO Conference

Hinweis der Redaktion

  1. Check out about_Regular_Expressions
  2. https://msdn.microsoft.com/en-us/library/windows/desktop/hh852735(v=vs.85).aspx
  3. https://blogs.msdn.microsoft.com/powershell/2016/02/05/platyps-write-external-help-files-in-markdown/
  4. https://technet.microsoft.com/en-us/library/hh847831.aspx
  5. Globbing - https://msdn.microsoft.com/en-us/library/aa717088(v=vs.85).aspx About_wildcards - https://technet.microsoft.com/en-us/library/hh847812.aspx
  6. https://msdn.microsoft.com/en-us/library/dd878348(v=vs.85).aspx
  7. * Starting from PSv5
  8. https://github.com/PowerShell/PSPrivateGallery