+ All Categories
Home > Technology > PowerShell Fundamentals

PowerShell Fundamentals

Date post: 22-Feb-2017
Category:
Upload: mozdzen
View: 147 times
Download: 0 times
Share this document with a friend
27
PowerShell Fundamentals BY PAWEL MOZDZEN 1
Transcript
Page 1: PowerShell Fundamentals

1

PowerShell FundamentalsBY PAWEL MOZDZEN

Page 2: PowerShell Fundamentals

PowerShell Fundamentals 2

PowerShell ISE

DEMOFinalProduct.ps1

FinalProductRun.ps1

Page 3: PowerShell Fundamentals

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

Page 4: PowerShell Fundamentals

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

Page 5: PowerShell Fundamentals

PowerShell Fundamentals 5

PowerShell ISE

DEMOHelp.ps1

Page 6: PowerShell Fundamentals

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[]>] …..

Page 7: PowerShell Fundamentals

PowerShell Fundamentals 7

Pipeline

Page 8: PowerShell Fundamentals

PowerShell Fundamentals 8

Pipeline - the Old Way

Command I

StdOut StdIn StdErr

Command II

StdOut StdIn StdErr

Text

Page 9: PowerShell Fundamentals

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

Page 10: PowerShell Fundamentals

PowerShell Fundamentals 10

Pipeline

DEMOPipeByValue.ps1

PipeByPropertyName.ps1

Page 11: PowerShell Fundamentals

PowerShell Fundamentals 11

ScopeGlobal Scope - Runspace Global Scope - Runspace

Function Scope

Script Scope

Function Scope

Script Scope

Script ScopeFunction Scope

Compartmentalization of Scope

Page 12: PowerShell Fundamentals

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

Page 13: PowerShell Fundamentals

PowerShell Fundamentals 13

Scope

DEMOScopeRunScript.ps1

ScopeTempScript.ps1

Page 14: PowerShell Fundamentals

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

Page 15: PowerShell Fundamentals

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

Page 16: PowerShell Fundamentals

PowerShell Fundamentals 16

Custom Objects – Creation Techniques

DEMOCustomObjects.ps1

Page 17: PowerShell Fundamentals

PowerShell Fundamentals 17

Custom Objects - Real Life Example

DEMOExport-Audiences.ps1

Page 18: PowerShell Fundamentals

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.

Page 19: PowerShell Fundamentals

PowerShell Fundamentals 19

Advanced Parameters - Real Life Example

DEMOExport-Audiences.ps1

Page 20: PowerShell Fundamentals

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

Page 21: PowerShell Fundamentals

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.

Page 22: PowerShell Fundamentals

PowerShell Fundamentals 22

Parameter Validation - Example

Page 23: PowerShell Fundamentals

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

Page 24: PowerShell Fundamentals

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

Page 25: PowerShell Fundamentals

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

Page 26: PowerShell Fundamentals

PowerShell Fundamentals 26

Steps for Building a Proper Function

DEMOFunctionBuildingSteps.ps1

Page 27: PowerShell Fundamentals

27

PowerShell FundamentalsQUESTIONS


Recommended