86
KEEP CALM and LEARN POWERSHELL

Power shell voor developers

Embed Size (px)

Citation preview

Page 1: Power shell voor developers

KEEP CALMand

LEARNPOWERSHELL

Page 2: Power shell voor developers

YouTube: https://www.youtube.com/watch?v=V5Gjx4jM91A

Page 3: Power shell voor developers

Robert TingaBusiness Development Manager QUINTOR

[email protected]

06 - 21862066

Introduction

Page 4: Power shell voor developers

QuintorJAVA

.NET

MOBILE

GRONINGENAMERSFOORTDEN HAAG

112 EMPLOYEESATLASSIANMS TFS

AGILE/SCRUM

ANALYSE

Page 5: Power shell voor developers

Employees

Januari 2006

Januari 2007

Januari 2008

Januari 2009

Januari 2010

Januari 2011

Januari 2012

Januari 2013

Januari 2014

Januari 2015

Januari 2016

0

20

40

60

80

100

120

Groningen Amersfoort Den Haag

Page 6: Power shell voor developers
Page 7: Power shell voor developers

KEEP CALMand

LEARNPOWERSHELL

Page 8: Power shell voor developers

Jeroen Swart.NET [email protected]

• Developer >= 1996• Mainframe/assembler, Microsoft/C++, .NET/C#• .NET >= 2001• Quintor >= 2011• .NET competentie• ALM & .NET ontwikkelstraat

Page 9: Power shell voor developers

REPL

DSCRemote

PowerShell

Verb

Commands

Build &Release Management

Functions

PowerShell

Package Management

Modules

NuGet

Strings

Pipeline

TasksTFS

Scripts

Chocolatey

PowerShell Gallery

Objects

Arrays

Page 10: Power shell voor developers

> _−REPL (Read Evaluate Print Loop)−.NET−Commands−Parameters−Objecten−Command pipeline

Page 11: Power shell voor developers

Show-Code

Page 12: Power shell voor developers

> Commands−[Verb]-[Prefix][Noun]

−Verb: Get, New, Update, … (Get-Verb)

−Prefix: VM, AD, Azure, Sql, …−Noun: Switch, User, Website, Database− Get-Service− Get-VMSwitch− New-ADUser− Start-AzureWebsite− Backup-SqlDatabase

Page 13: Power shell voor developers

> Command pipeline−Get-Process | Sort ProcessName | Select *

−Select-Object select−Sort-Object sort−Where-Object where, ?−ForEach-Object foreach, %

Page 14: Power shell voor developers

> Select-Object−Specify which properties to return

− Select ProcessName,Description− Select *

−Specify how many objects to return− Select –First 5− Select –First 5 –Skip 5− Select –Last 10

− Get-Process | Select ProcessName,Description –First 10

Page 15: Power shell voor developers

> Sort-Object−Specify order of objects

− Sort ProcessName

−Specify direction− Sort ProcessName -Descending

−Get-Process | Sort ProcessName,Description

Page 16: Power shell voor developers

> Where-Object−Filter objects by property

− Where -Property ProcessName -EQ 'powershell'

−Filter objects using script− Where { $_.ProcessName -eq 'powershell' }

− Get-Process |? { $_.ProcessName -like 'po*' }

Page 17: Power shell voor developers

> ForEach-Object−Repeat for each object

− ForEach { Write-Host $_.ProcessName }

− Get-Process |% { Write-Host "$($_.ProcessName)" }

Page 18: Power shell voor developers

> Command pipeline−Measure-Object−Group-Object−Compare-Object−Tee-Object

Page 19: Power shell voor developers

> Format-*−Format-Table (ft)

− -AutoSize (ft –a)−Format-List (fl)−Format-Wide (fw)

− -Column (fw –c 3)

−Get-Command format-*

Page 20: Power shell voor developers

> Out-*−Out-Default−Out-File−Out-Null−Out-String−Out-GridView (ogv)

−Get-Command out-*

Page 21: Power shell voor developers

> ConvertTo-* / ConvertFrom-*−ConvertTo-Json, ConvertFrom-Json−ConvertTo-Xml (, Get-Content)−ConvertTo-Csv, ConvertFrom-Csv−ConvertTo-Html

−Get-Command convertto-*,convertfrom-*

Page 22: Power shell voor developers

> Advanced pipeline−-PassThru−Multiline with `−Multi-command on single line with ;−Select @{ Name = $_.Name; Type = 'Foo' }

− Force expression evaluation using brackets ()

Page 23: Power shell voor developers

Show-Code

Page 24: Power shell voor developers

> Hosts−Console−ISE (Integrated Script Environment)−Visual Studio Extension (2015, 2013, 2012)

−Visual Studio Code Extension−PowerGUI−PowerShell Plus−Custom−[insert your application name here]

Page 25: Power shell voor developers

> Host environment−Get-Variable−$Host−$Profile−$PSVersionTable

Page 26: Power shell voor developers

> $Host−Console

−ISE

Page 27: Power shell voor developers

> $Profile−Current user / All users−Current host / All hosts−$profile

− Current user, current host−$profile.AllUsersAllHosts−$profile.AllUsersCurrentHosts−$profile.CurrentUsersAllHosts−$profile.CurrentUsersCurrentHost

$profile.AllUsersAllHosts C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1

$profile.AllUsersCurrentHostsC:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1

$profile.CurrentUsersAllHostsC:\Users\jswart\Documents\WindowsPowerShell\profile.ps1

$profile.CurrentUsersCurrentHostC:\Users\jswart\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

$profile (console)C:\Users\jswart\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

$profile (ISE)C:\Users\jswart\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

Page 28: Power shell voor developers

> $Profile$global:CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()

function prompt{ $Host.UI.RawUI.WindowTitle = "$($CurrentUser.Name) - $(Get-Location)"

Write-Host 'PS >' -NoNewline return ' '}

Page 29: Power shell voor developers

> $PSVersionTableName Value---- -----PSVersion 5.0.10586.122PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}BuildVersion 10.0.10586.122CLRVersion 4.0.30319.42000WSManStackVersion 3.0PSRemotingProtocolVersion 2.3SerializationVersion 1.1.0.1

Page 30: Power shell voor developers

> Strings−Literals

− 'Name: $Name'− "Name: $Name"

−Format− 'Name: {0}' –f $Name

−Expression− "Name: $user.Name"− "Name: $($user.Name)"

Name: $NameName: Jeroen

Name: Jeroen

Name: Hashtable.NameName: Jeroen

Page 31: Power shell voor developers

> Strings & regular expressions−Match

− 'PowerShell' –match 'sh'− 'PowerShell' –match '^P'− 'PowerShell' –match 'P$‘− 'PowerShell' –cmatch

'p$'

−Replace− 'PowerShell' -replace 'e','E'

TrueTrueFalseFalse

PowErShEll

Page 32: Power shell voor developers

> Arrays & objects−Command output is array or object−When Parameter type is Array, provide either array or single object as value

Page 33: Power shell voor developers

> Arrays−$a = 1,2−$a = @(1)−$a = @()−$a = 1..5−$a += 6−$a.GetType() -> System.Array

− $a.Length− $a.Contains(1)− $a[0]

Page 34: Power shell voor developers

> Objects (HashTable)−$o = @{}−$o = @{ Name = 'me' }−$o = @{

Name = 'me'PowerShell = $true

}−$o = @{ Name = 'me'; PowerShell = $true }

Page 35: Power shell voor developers

> Objects (PSCustomObject)

$o = New-Object PSCustomObject ` | Add-Member -MemberType NoteProperty -Name 'Name' -Value 'me' -PassThru ` | Add-Member -MemberType NoteProperty -Name 'PowerShell' -Value $true -PassThru

Page 36: Power shell voor developers

> Objects−$o.Name−$o.'Name'−$o = @{

Name = 'me'PowerShell = $true

}−$o = @{ Name = 'me'; PowerShell = $true }

Page 37: Power shell voor developers

> Scripts−Collection of commands−Conditional statements (if/else, etc.)−Parameters−Output−Execute using . Or &−Execute using full or relative path (.\). .\DoSomethingSmart.ps1

. '.\DoSomethingSmart.ps1'

Page 38: Power shell voor developers

> Scripts – if/else

if ($condition) {

}

elseif ($otherCondition) {

}

else {

}

if (Test-Path -Path $path) {}

if (Get-Service 'MSSQL*') {}

Basic syntax Using commands returning a boolean

Using other commands

if ($name -eq 'PowerShell' ) {}

Using logical operatorsif ($condition -eq $true) {}

Using explicit conditions

Page 39: Power shell voor developers

> Scripts – if/else− -eq, -ne− -lt, -gt, -le, -ge− -like, -match, -notlike, -notmatch− -contains, -in, -notcontains, -notin− And their case-sensitive version (-ceq, -clike, etc.)− And their (explicit) case-insensitive version (-ieq, -ilike, etc.)

− -not, -or, -and, -xor− And their binary version (-bnot, -bor, etc.)

− -is, -isnot

Page 40: Power shell voor developers

> Scripts – switch/case

switch ($value) {

1 { }

2 { }

default { }

}

switch ($value) { '1' { }

'2' { }

default { }

}

switch ($value) { { $_ -eq 1 } { }

{ $_ -in 2,3 } { }

{ $_ -like '4*' } { }

{ $_ -match '^5' } { }

default { }

}

Basic syntax

Using strings

Using expressions

Page 41: Power shell voor developers

> Scripts – foreach

foreach ($item in $items) {

# use $item

}

$items |% {

# use $_

}

Basic syntax

Alternative

Page 42: Power shell voor developers

> Scripts – for

for ($index = 0; $index -lt 10; $index++) {

# use $items[$index]

}

Basic syntax

Page 43: Power shell voor developers

> Scripts – try/catch try { throw 'Serious error'

throw [InvalidOperationException]'Serious error'

}

catch [InvalidOperationException] {

write-host 'InvalidOperationException'

}

catch {

}

finally {

}

Page 44: Power shell voor developers

> Scripts – parameters− Name− Default− Type− Mandatory− ValueFromPipeline− ParameterSetName− Validation

− ValidateSet− ValidateScript

− switch

param (

)

param (

$Value

)

param (

$Value = 'The default value'

)

param (

[string]$Value

)

param (

[Parameter(Mandatory = $true)]

[string]$Value

)

param (

[Parameter(ValueFromPipeline = $true)]

[string[]]$Value

)

param (

[Parameter(ParameterSetName = ‘ByValue')]

[string]$Value,

[Parameter(ParameterSetName = 'ByCount')]

[int]$Count

)

. .\Script.ps1 -Value 'foo'

. .\Script.ps1 –Count 42

param (

[ValidateSet('High', 'Low')] [string]$Value

)

param (

[ValidateScript({ Test-Path -Path $_ -PathType Leaf

})]

[string]$Path

)

param (

[switch]$Force

)

if ($Force) {

}

if ($Force.IsPresent) {

}

. .\Script.ps1 –Force True

. .\Script.ps1 False . .\Script.ps1 –Force:$false

False

param (

[bool]$Force

)

if ($Force) {

}

. .\Script.ps1 –Force $true

True

. .\Script.ps1 –Force $falseFalse

Page 45: Power shell voor developers

> Scripts – output− return− Write-Output− Write-Host− Write-Verbose

− CmdletBinding− -Verbose

return 'The result'

The result

Write-Output 'The result'

The result

Write-Output 'The result'

Write-Output ‘More result'

The result

More result

Write-Host 'Message‘

Write-Host 'Message' -ForegroundColor Yellow

Write-Host 'Message' -BackgroundColor Magenta ` -ForegroundColor White

Write-Host ('Message {0}' -f 42)

[CmdletBinding()]

param (

)

Write-Verbose 'Verbose message‘

Page 46: Power shell voor developers

> Scripts – output− Write-Verbose -Verbose $VerbosePreference− Write-Debug -Debug $DebugPreference− Write-Warning -WarningAction $WarningPreference− Write-Error -ErrorAction $ErrorActionPreference− Write-Information -InformationAction $InformationPreference

− Action/Preference− SilentlyContinue− Continue− Stop

Page 47: Power shell voor developers

> Scripts – lifecycle

param (

)

# script-body here

. .\Script.ps1 -Value '1','2'

'1','2' | . .\Script.ps1

− $Value = '1','2'

− $Value = '2'

param (

[string[]]$Value

)

# script-body here

param (

[Parameter(ValueFromPipeline = $true)]

[string[]]$Value

)

# script-body here

$Value

Page 48: Power shell voor developers

> Scripts – lifecycleparam (

)

begin {}

process { # script-body here}

end {}

. .\Script.ps1 -Value '1','2'

'1','2' | . .\Script.ps1

− Begin− Process ($Value = '1','2')− End

− Begin− Process ($Value = '1')− Process ($Value = '2')− End

param (

)

begin {}

process { # script-body here}

end {}

param (

[string[]]$Value

)

begin {}

process { # script-body here}

end {}

param (

[Parameter(ValueFromPipeline = $true)]

[string[]]$Value

)

begin {}

process { # script-body here

$Value }

end {}

Page 49: Power shell voor developers

Show-Code

Page 50: Power shell voor developers

> Functionsfunction Verb-PrefixNoun {

}

function Verb-PrefixNoun {

param (

[string]$Value

)

# function-body here

$Value

}

function Verb-PrefixNoun { param (

[string[]]$Value

)

begin { }

process { # script-body here

$Value }

end { }}

Page 51: Power shell voor developers

> Modules− PowerShell Script or C#− C#

− System.Management.Automation namespace− Cmdlet base-class− Cmdlet attribute

− PowerShell Script− Collection of functions− .psm1− .psd1

Page 52: Power shell voor developers

> Modules−Import-Module−.psm1−.psm1 + .psd1

− New-ModuleManifest− Update-ModuleManifest

− Test-ModuleManifest−Script-files

function Get-SomeStuff {}

function Update-SomeStuff {}

function Remove-SomeStuff {}

@{

Author = 'Jeroen Swart'

RootModule = 'MyModule.psm1'

ModuleVersion = '1.0.0.0'

GUID = 'bbd0a9d3-8308-4e5b-9762-1cbc057dd1c4'

Description = '...'

PowerShellVersion = '4.0'

FunctionsToExport = (

'Get-SomeStuff',

'Update-SomeStuff',

'Remove-SomeStuff')

}

Get-ChildItem ` -Path "$PSScriptRoot\Internal" ` -Filter '*.ps1' |% { . $_.FullName }

Get-ChildItem ` -Path "$PSScriptRoot\Functions" ` -Filter '*.ps1' |% { . $_.FullName }

Page 53: Power shell voor developers

> Modules−Import-Module –Path '...'−Import-Module –Name '...'

− System− %windir%\System32\WindowsPowerShell\v1.0\

Modules− $pshome\Modules

− All users− %ProgramFiles%\WindowsPowerShell\Modules− "$($env:ProgramFiles)\WindowsPowerShell\

Modules"− Current user

− %UserProfile%\Documents\WindowsPowerShell\Modules

− $home\Documents\WindowsPowerShell\Modules

Page 54: Power shell voor developers

> Modules−Get-Module−Get-Module –ListAvailable−Remove-Module

−Import-Module –Force

Page 55: Power shell voor developers

• NuGet• Chocolatey• PowerShell Package Management• TFS Build• TFS Release Management• Remote PowerShell• PowerShell DSC• Server Management

> Select PowerShell | More

Page 56: Power shell voor developers

• NuGet• Chocolatey• PowerShell Package Management

> Select PowerShell | More

Page 57: Power shell voor developers

> NuGet−zip, maar .nupkg−lib

− net45− net40− portable-win+net45+wp8+win8+wpa81

−content−tools

− init.ps1− .psm1

−nuspec

Page 58: Power shell voor developers

> NuGet−init.ps1

−installPath−toolPath−package−project

− EnvDTE.Project− ProjectItems− DTE EnvDTE.DTE

Page 59: Power shell voor developers

> NuGet−Add/modify files & content in a project

−Build and/or run the solution−Code generation

− Entity Framework Migrations−Manage windows & documents−Enhance Visual Studio UI

Page 60: Power shell voor developers

Show-Code

Page 61: Power shell voor developers

> Chocolatey−Windows Package Manager

− choco list− choco install

−NuGet-based−nuspec−tools

− chocolateyInstall.ps1− chocolateyUninstall.ps1

Page 62: Power shell voor developers

> Chocolatey−Install-ChocolateyPackage−Install-ChocolateyZipPackage−Install-ChocolateyVsixPackage−Install-ChocolateyEnvironmentVariable−Install-ChocolateyFileAssociation

Page 63: Power shell voor developers

> Chocolatey

Install-ChocolateyPackage ` 'notepadplusplus' ` 'exe' ` '/S' ` 'https://notepad-plus-plus.org/repository/6.x/6.8.8/npp.6.8.8.Installer.exe'

Notepadplusplus (chocolateyInstall.ps1)

$packageName = 'GoogleChrome'

$app = Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -eq 'Google Chrome'}if ($app) { $msiArgs = $('/x' + $app.IdentifyingNumber + ' /q REBOOT=ReallySuppress') Start-ChocolateyProcessAsAdmin $msiArgs 'msiexec'}

GoogleChrome (chocolateyUninstall.ps1)

Page 64: Power shell voor developers

> PowerShell Modules−xcopy

− System, All users, Current user

−Chocolatey package− xcopy

−PowerShell Package Management− PowerShell v5

Page 65: Power shell voor developers

> PowerShell Package Management−Package Manager Manager

Page 66: Power shell voor developers

> PowerShell Package Management−Module−Script−Package

−Find, Install, Update, Publish, Save−Find-Module−Install-Package

Page 67: Power shell voor developers

Show-Code

Page 68: Power shell voor developers

• TFS Build• TFS Release Management

> Select PowerShell | More

Page 69: Power shell voor developers

> TFS Build−XAML Build

−Task-based build− Script (in VC)− Arguments

Page 70: Power shell voor developers

> TFS Release Management−XAML

−Task-based− TFS 2015 Update 2

Page 71: Power shell voor developers

> TFS Release Management−Remote PowerShell

−PowerShell Scripts

−PowerShell Modules

−PowerShell DSC

−PowerShell Package Management

(Chocolatey)

Page 72: Power shell voor developers

> TFS Release Management

Build Drop-location

RM

Target-servers

Trigger release Execute script

Copy files to servers

Page 73: Power shell voor developers

> TFS Release Management

Build Package Source

RM

Target-servers

Chocolatey PackagesPowerShell Modules

Trigger release

Retrieve packages

Install packages

Page 74: Power shell voor developers

• Remote PowerShell• PowerShell DSC• Server Management

> Select PowerShell | More

Page 75: Power shell voor developers

> Remote PowerShell−Enter-PSSession & Exit-PSSession

−New-PSSession & Remove-PSSession−Invoke-Command -Session

Page 76: Power shell voor developers

> Remote PowerShell−Enable remoting

− Enable-PSRemoting−Check configuration

− Test-WSMan−Limit access

− Set-Item `wsman:\localhost\client\trustedhosts

[name] `-Concatenate-Force

Page 77: Power shell voor developers

> Remote PowerShell−'Double Hop'−CredSSP & Credential

−Server− Enable-WSManCredSSP -Role Server

−Client− Enable-WSManCredSSP -Role Client `

–DelegateComputer [machinename]

Page 78: Power shell voor developers

> PowerShell DSC

$server = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")if($Credential) { $server.ConnectionContext.Login = $Credential.UserName $server.ConnectionContext.SecurePassword = $credential.Password}

$database = $server.Databases |? { $_.Name -eq $Name }if (-not $database) { $database = New-Object Microsoft.SqlServer.Management.Smo.Database($server, $Name) $database.Create()}

PowerShell Script

Page 79: Power shell voor developers

> PowerShell DSC

bSqlDatabase Database { Ensure = "Present" Name = $DatabaseName}

PowerShell DSC

Page 80: Power shell voor developers

> PowerShell DSC− Desired State Configuration− Declarative

− Configuration− Resource

− Get− Test− Set

Page 81: Power shell voor developers

> PowerShell DSC− Push vs Pull

Page 82: Power shell voor developers

Show-Code

Page 83: Power shell voor developers

> Server Management−Server

− Processes− Services− Resources (RAM, CPU, …)

−IIS− Websites− App pools

− Logging

Page 84: Power shell voor developers

• notes in ppt• MSDN

• Windows PowerShell• PowerShell DSC• PowerShell SDK

• Blogs• Windows PowerShell Blog• Hey Scripting Guy• ...

• Books• Windows PowerShell in Action• Windows PowerShell Cookbook• Windows PowerShell for Developers• ...

> Get-Help

Page 85: Power shell voor developers

• PowerShell Workflow• Debugging (incl. remote)• Classes• ISE• Automation• Extensions/Add-ons• Unit testing (Pester)• Azure (incl. PowerShell DSC)

• OSS Packages & Modules

> _

Page 86: Power shell voor developers

?VRAGEN