powershell fundamentals
TRANSCRIPT
1
PowerShell FundamentalsBY PAWEL MOZDZEN
PowerShell Fundamentals 2
PowerShell ISE
DEMOFinalProduct.ps1
FinalProductRun.ps1
PowerShell Fundamentals 3
What we will cover Custom Objects
Advanced Parameters
Steps for Building a Proper Function
Help System
Pipeline
Scope
But not.. PowerShell Syntax Specific SharePoint Cmdlets
PowerShell Fundamentals 4
Help System Update-Help Get-Help
Get-Help Parameters- Full- Examples- Detailed- Online- ShowWindow
Get-Member
Examples
1. Get-Help Get-SPSite –Full
2. Get-Help Get-SP*
3. Get-Help Get-SPSite –Parameter Limit
Examples
1. Get-SPSite | Get-Member
2. Get-SPSite | Select Url, Owner | Get-Member
PowerShell Fundamentals 5
PowerShell ISE
DEMOHelp.ps1
PowerShell Fundamentals 6
Understanding Help SyntaxGet-Help New-SPSiteSyntax
New-SPSite [-AdministrationSiteType <None | TenantAdministration>] [-AssignmentCollection <SPAssignmentCollection>] [-CompatibilityLevel <Int32>] [-Confirm <SwitchParameter>] [-ContentDatabase <SPContentDatabasePipeBind>] [-Description <String>] [-HostHeaderWebApplication <SPWebApplicationPipeBind>] [-Language <UInt32>] [-Name <String>] [-OverrideCompatibilityRestriction <SwitchParameter>] [-OwnerEmail <String>] [-QuotaTemplate <SPQuotaTemplatePipeBind>] [-SecondaryEmail <String>] [-SecondaryOwnerAlias <SPUserPipeBind>] [-SiteSubscription <SPSiteSubscriptionPipeBind>] [-Template <SPWebTemplatePipeBind>] [-WhatIf <SwitchParameter>]
[-Url] <String>[-Url] <String> -OwnerAlias <SPUserPipeBind>-OwnerAlias <SPUserPipeBind>
[<CommonParameters>][<CommonParameters>]
Get-Help New-SPUser …[-PermissionLevel <String[]>] …..
PowerShell Fundamentals 7
Pipeline
PowerShell Fundamentals 8
Pipeline - the Old Way
Command I
StdOut StdIn StdErr
Command II
StdOut StdIn StdErr
Text
PowerShell Fundamentals 9
Working with Pipeline – PowerShell Way
Command I
Output Errors Warnings
Command II
-Param
OBJECTVerbose Debug
-Param-Param 1
-Param-Param-Param
…n
? Pipeline Parameter Binding By Value By Property Name
PowerShell Fundamentals 10
Pipeline
DEMOPipeByValue.ps1
PipeByPropertyName.ps1
PowerShell Fundamentals 11
ScopeGlobal Scope - Runspace Global Scope - Runspace
Function Scope
Script Scope
Function Scope
Script Scope
Script ScopeFunction Scope
Compartmentalization of Scope
PowerShell Fundamentals 12
General Rules Scoped elements exist only in scope they were created. Accessing non-existent element will result in reaching out to the parent scope. Scoped elements can be created with the same name as in the parent scope. When a scope is finished processing it is destroyed and removed from memory.
Dot Sourcing
Private variables
Strict Mode Set-StrictMode -Off Set-StrictMode -Version [1,2,3,latest]
Scope
PowerShell Fundamentals 13
Scope
DEMOScopeRunScript.ps1
ScopeTempScript.ps1
PowerShell Fundamentals 14
Benefits for turning script into a function Once loaded into memory it is available for later use: Dot-Sourcing, Import-Module Function has its own scope Multiple functions per script file. Provides better separation of concerns for complex tasks.
Function Example function Get-SiteColumnStats{ $spWeb = Get-spweb "http://sps-demo:5555/sites/acct" $spFields = $spWeb.Fields $spFields | Group-Object TypeAsString | Sort-Object Count -Descending}Get-SiteColumnStats
Functions
PowerShell Fundamentals 15
Everything in PowerShell is an OBJECT
Functions and scripts can return only one kind of thing.
Use Custom Objects to consolidate information before returning it.
To return a collection of data assign it to a property of the custom object.
Techniques for creating custom objects: Using Hashtable Using Select-Object Using Add-Member Using Type Declaration
Custom Objects
PowerShell Fundamentals 16
Custom Objects – Creation Techniques
DEMOCustomObjects.ps1
PowerShell Fundamentals 17
Custom Objects - Real Life Example
DEMOExport-Audiences.ps1
PowerShell Fundamentals 18
Functions – Advanced Parameters
Get-Help about_Functions_Advanced_Paramenters
All PowerShell functions follow a verb dash noun naming standard.
Adds certain features to a function:• Enables [Parameter()] decorator,• Adds standard set of extra function
parameters such us –verbose, -debug
Makes parameter required. Any default values will be ignored. Enables to accept values from pipeline. Accepts values of the same type. Only one such decorator for the same type.
Enables to accept values from pipeline. Accepts values from passed in object’s
properties same name. First it will try to find a match By Value then
by Property Name
BEGIN and END blocks execute only once. PROCESS block executes for each piped in
object
Important to handle function calls where values are passed in via parameter.
Redundant if piped in.
PowerShell Fundamentals 19
Advanced Parameters - Real Life Example
DEMOExport-Audiences.ps1
PowerShell Fundamentals 20
Defined as set of parameter decorators. Each validator defined as a separate decorator.
[ValidateCount(1,50)]
[ValidateLength(1,50)]
[ValidateScript({...})]
[ValidateSet[("One","Two","Three")]
[ValidatePattern("\w+\\\w+")]
[ValidateRange(1,5)]
Parameter Validation
PowerShell Fundamentals 21
Validate against null or empty values:
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
For mandatory parameters to allow null values:
[AllowNull()]
[AllowEmptyString()]
[AllowEmptyCollection()]
Parameter Validation – Cont’d.
PowerShell Fundamentals 22
Parameter Validation - Example
PowerShell Fundamentals 23
Verbose Output: Write-VerboseA way to check variables’ state in longer scriptsA way to comment script behavior documenting itA way to notify about longer running processesAnd the most important..
Debug Output: Write-DebugTo let you know which line is currently processingTo pause the execution and let user check things
Verbose and Debug Output
a way to avoid using Write-Host
PowerShell Fundamentals 24
Converting script to a module
Accessing Module Use: Import-Module moduleFileName.psm1 Place module in PowerShell searchable locations: $env:PSModulePath
Special considerations for saving modules in PowerShell locations: Always save your module within a folder of the same name. Use letters and numbers only.
Exporting Module Members Export-ModuleMember -Function <functionName>
Export-ModuleMember -Variable <variableName> Example: Export-ModuleMember -Function *-*
Functions in Script Modules
PowerShell Fundamentals 25
Start with defining a task. Build base command(s). Turn it into a function. Parameterize it. Test it calling in different ways. Add error handling if necessary. Add Verbose and Debug output. Turn it into a module.
Steps for Building a Proper Function
PowerShell Fundamentals 26
Steps for Building a Proper Function
DEMOFunctionBuildingSteps.ps1
27
PowerShell FundamentalsQUESTIONS