SlideShare a Scribd company logo
1 of 86
KEEP CALM
and
LEARN
POWERSHELL
YouTube: https://www.youtube.com/watch?v=V5Gjx4jM91A
Robert Tinga
Business Development Manager QUINTOR
rtinga@quintor.nl
06 - 21862066
Introduction
Quintor
JAVA
.NET
MOBILE
GRONINGEN
AMERSFOORT
DEN HAAG
112 EMPLOYEES
ATLASSIAN
MS TFS
AGILE/SCRUM
ANALYSE
Employees
0
20
40
60
80
100
120
Groningen Amersfoort Den Haag
KEEP CALM
and
LEARN
POWERSHELL
Jeroen Swart
.NET Architect
jswart@quintor.nl
• Developer >= 1996
• Mainframe/assembler, Microsoft/C++, .NET/C#
• .NET >= 2001
• Quintor >= 2011
• .NET competentie
• ALM & .NET ontwikkelstraat
REPL
DSCRemote
PowerShell
Verb
Commands
Build &
Release Management
Functions
PowerShell
Package
Management
Modules
NuGet
StringsPipeline
TasksTFS
Scripts
Chocolatey
PowerShell
Gallery
Objects Arrays
> _
− REPL (Read Evaluate Print Loop)
− .NET
− Commands
− Parameters
− Objecten
− Command pipeline
Show-Code
> 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
> Command pipeline
− Get-Process | Sort ProcessName | Select *
− Select-Object select
− Sort-Object sort
− Where-Object where, ?
− ForEach-Object foreach, %
> 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
> Sort-Object
− Specify order of objects
− Sort ProcessName
− Specify direction
− Sort ProcessName -Descending
− Get-Process | Sort ProcessName,Description
> Where-Object
− Filter objects by property
− Where -Property ProcessName -EQ 'powershell'
− Filter objects using script
− Where { $_.ProcessName -eq 'powershell' }
− Get-Process |? { $_.ProcessName -like 'po*' }
> ForEach-Object
− Repeat for each object
− ForEach { Write-Host $_.ProcessName }
− Get-Process |% { Write-Host "$($_.ProcessName)" }
> Command pipeline
− Measure-Object
− Group-Object
− Compare-Object
− Tee-Object
> Format-*
− Format-Table (ft)
− -AutoSize (ft –a)
− Format-List (fl)
− Format-Wide (fw)
− -Column (fw –c 3)
− Get-Command format-*
> Out-*
− Out-Default
− Out-File
− Out-Null
− Out-String
− Out-GridView (ogv)
− Get-Command out-*
> ConvertTo-* / ConvertFrom-*
− ConvertTo-Json, ConvertFrom-Json
− ConvertTo-Xml (, Get-Content)
− ConvertTo-Csv, ConvertFrom-Csv
− ConvertTo-Html
− Get-Command convertto-*,convertfrom-*
> Advanced pipeline
− -PassThru
− Multiline with `
− Multi-command on single line with ;
− Select @{ Name = $_.Name; Type = 'Foo' }
− Force expression evaluation using brackets ()
Show-Code
> 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]
> Host environment
− Get-Variable
− $Host
− $Profile
− $PSVersionTable
> $Host
− Console
− ISE
> $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:WindowsSystem32WindowsPowerShellv1.0profile.ps1
$profile.AllUsersCurrentHosts
C:WindowsSystem32WindowsPowerShellv1.0Microsoft.PowerShell_profile.ps1
$profile.CurrentUsersAllHosts
C:UsersjswartDocumentsWindowsPowerShellprofile.ps1
$profile.CurrentUsersCurrentHost
C:UsersjswartDocumentsWindowsPowerShellMicrosoft.PowerShell_profile.ps1
$profile (console)
C:UsersjswartDocumentsWindowsPowerShellMicrosoft.PowerShell_profile.ps1
$profile (ISE)
C:UsersjswartDocumentsWindowsPowerShellMicrosoft.PowerShellISE_profile.ps1
> $Profile
$global:CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
function prompt
{
$Host.UI.RawUI.WindowTitle = "$($CurrentUser.Name) - $(Get-Location)"
Write-Host 'PS >' -NoNewline
return ' '
}
> $PSVersionTable
Name Value
---- -----
PSVersion 5.0.10586.122
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.10586.122
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
> Strings
− Literals
− 'Name: $Name'
− "Name: $Name"
− Format
− 'Name: {0}' –f $Name
− Expression
− "Name: $user.Name"
− "Name: $($user.Name)"
Name: $Name
Name: Jeroen
Name: Jeroen
Name: Hashtable.Name
Name: Jeroen
> Strings & regular expressions
− Match
− 'PowerShell' –match 'sh'
− 'PowerShell' –match '^P'
− 'PowerShell' –match 'P$‘
− 'PowerShell' –cmatch 'p$'
− Replace
− 'PowerShell' -replace 'e','E'
True
True
False
False
PowErShEll
> Arrays & objects
− Command output is array or object
− When Parameter type is Array, provide
either array or single object as value
> Arrays
− $a = 1,2
− $a = @(1)
− $a = @()
− $a = 1..5
− $a += 6
− $a.GetType() -> System.Array
− $a.Length
− $a.Contains(1)
− $a[0]
> Objects (HashTable)
− $o = @{}
− $o = @{ Name = 'me' }
− $o = @{
Name = 'me'
PowerShell = $true
}
− $o = @{ Name = 'me'; PowerShell = $true }
> Objects (PSCustomObject)
$o = New-Object PSCustomObject `
| Add-Member -MemberType NoteProperty -Name 'Name' -Value 'me' -PassThru `
| Add-Member -MemberType NoteProperty -Name 'PowerShell' -Value $true -PassThru
> Objects
− $o.Name
− $o.'Name'
− $o = @{
Name = 'me'
PowerShell = $true
}
− $o = @{ Name = 'me'; PowerShell = $true }
> Scripts
− Collection of commands
− Conditional statements (if/else, etc.)
− Parameters
− Output
− Execute using . Or &
− Execute using full or relative path (.)
. .DoSomethingSmart.ps1
. '.DoSomethingSmart.ps1'
> 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 operators
if ($condition -eq $true) {
}
Using explicit conditions
> 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
> 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
> Scripts – foreach
foreach ($item in $items) {
# use $item
}
$items |% {
# use $_
}
Basic syntax
Alternative
> Scripts – for
for ($index = 0; $index -lt 10; $index++) {
# use $items[$index]
}
Basic syntax
> Scripts – try/catch
try {
throw 'Serious error'
throw [InvalidOperationException]'Serious error'
}
catch [InvalidOperationException] {
write-host 'InvalidOperationException'
}
catch {
}
finally {
}
> 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 $false False
> 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‘
> 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
> 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
> Scripts – lifecycle
param (
)
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 {
}
Show-Code
> Functions
function 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 {
}
}
> Modules
− PowerShell Script or C#
− C#
− System.Management.Automation namespace
− Cmdlet base-class
− Cmdlet attribute
− PowerShell Script
− Collection of functions
− .psm1
− .psd1
> 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 "$PSScriptRootInternal" `
-Filter '*.ps1' |% {
. $_.FullName
}
Get-ChildItem `
-Path "$PSScriptRootFunctions" `
-Filter '*.ps1' |% {
. $_.FullName
}
> Modules
− Import-Module –Path '...'
− Import-Module –Name '...'
− System
− %windir%System32WindowsPowerShellv1.0Modules
− $pshomeModules
− All users
− %ProgramFiles%WindowsPowerShellModules
− "$($env:ProgramFiles)WindowsPowerShellModules"
− Current user
− %UserProfile%DocumentsWindowsPowerShellModules
− $homeDocumentsWindowsPowerShellModules
> Modules
− Get-Module
− Get-Module –ListAvailable
− Remove-Module
− Import-Module –Force
• NuGet
• Chocolatey
• PowerShell Package Management
• TFS Build
• TFS Release Management
• Remote PowerShell
• PowerShell DSC
• Server Management
> Select PowerShell | More
• NuGet
• Chocolatey
• PowerShell Package Management
> Select PowerShell | More
> NuGet
− zip, maar .nupkg
− lib
− net45
− net40
− portable-win+net45+wp8+win8+wpa81
− content
− tools
− init.ps1
− .psm1
− nuspec
> NuGet
− init.ps1
− installPath
− toolPath
− package
− project
− EnvDTE.Project
− ProjectItems
− DTE EnvDTE.DTE
> 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
Show-Code
> Chocolatey
− Windows Package Manager
− choco list
− choco install
− NuGet-based
− nuspec
− tools
− chocolateyInstall.ps1
− chocolateyUninstall.ps1
> Chocolatey
− Install-ChocolateyPackage
− Install-ChocolateyZipPackage
− Install-ChocolateyVsixPackage
− Install-ChocolateyEnvironmentVariable
− Install-ChocolateyFileAssociation
> 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)
> PowerShell Modules
− xcopy
− System, All users, Current user
− Chocolatey package
− xcopy
− PowerShell Package Management
− PowerShell v5
> PowerShell Package Management
− Package Manager Manager
> PowerShell Package Management
− Module
− Script
− Package
− Find, Install, Update, Publish, Save
− Find-Module
− Install-Package
Show-Code
• TFS Build
• TFS Release Management
> Select PowerShell | More
> TFS Build
− XAML Build
− Task-based build
− Script (in VC)
− Arguments
> TFS Release Management
− XAML
− Task-based
− TFS 2015 Update 2
> TFS Release Management
− Remote PowerShell
− PowerShell Scripts
− PowerShell Modules
− PowerShell DSC
− PowerShell Package Management (Chocolatey)
> TFS Release Management
Build
Drop-
location
RM
Target-
servers
Trigger release Execute script
Copy files to servers
> TFS Release Management
Build
Package
Source
RM
Target-
servers
Chocolatey Packages
PowerShell Modules
Trigger release
Retrieve packages
Install packages
• Remote PowerShell
• PowerShell DSC
• Server Management
> Select PowerShell | More
> Remote PowerShell
− Enter-PSSession & Exit-PSSession
− New-PSSession & Remove-PSSession
− Invoke-Command -Session
> Remote PowerShell
− Enable remoting
− Enable-PSRemoting
− Check configuration
− Test-WSMan
− Limit access
− Set-Item `
wsman:localhostclienttrustedhosts [name] `
-Concatenate
-Force
> Remote PowerShell
− 'Double Hop'
− CredSSP & Credential
− Server
− Enable-WSManCredSSP -Role Server
− Client
− Enable-WSManCredSSP -Role Client `
–DelegateComputer [machinename]
> 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
> PowerShell DSC
bSqlDatabase Database {
Ensure = "Present"
Name = $DatabaseName
}
PowerShell DSC
> PowerShell DSC
− Desired State Configuration
− Declarative
− Configuration
− Resource
− Get
− Test
− Set
> PowerShell DSC
− Push vs Pull
Show-Code
> Server Management
− Server
− Processes
− Services
− Resources (RAM, CPU, …)
− IIS
− Websites
− App pools
− Logging
• 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
• PowerShell Workflow
• Debugging (incl. remote)
• Classes
• ISE
• Automation
• Extensions/Add-ons
• Unit testing (Pester)
• Azure (incl. PowerShell DSC)
• OSS Packages & Modules
> _
?
VRAGEN

More Related Content

What's hot

Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)
Kris Wallsmith
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
Inada Naoki
 

What's hot (20)

Perforce Object and Record Model
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit Testing
 
Workshop unittesting
Workshop unittestingWorkshop unittesting
Workshop unittesting
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Perl6 in-production
Perl6 in-productionPerl6 in-production
Perl6 in-production
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
Forget about loops
Forget about loopsForget about loops
Forget about loops
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)
 
Back to basics - PHP_Codesniffer
Back to basics - PHP_CodesnifferBack to basics - PHP_Codesniffer
Back to basics - PHP_Codesniffer
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Introducción rápida a SQL
Introducción rápida a SQLIntroducción rápida a SQL
Introducción rápida a SQL
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best Practices
 
New in php 7
New in php 7New in php 7
New in php 7
 
PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
 

Similar to Power shell voor developers

international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
smueller_sandsmedia
 
Test in action week 4
Test in action   week 4Test in action   week 4
Test in action week 4
Yi-Huan Chan
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
mfrost503
 
PowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdfPowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdf
outcast96
 
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
Creating "Secure" PHP Applications, Part 1, Explicit Code & QACreating "Secure" PHP Applications, Part 1, Explicit Code & QA
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
archwisp
 

Similar to Power shell voor developers (20)

Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010Introduction to windows power shell in sharepoint 2010
Introduction to windows power shell in sharepoint 2010
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
PHPSpec BDD Framework
PHPSpec BDD FrameworkPHPSpec BDD Framework
PHPSpec BDD Framework
 
Test in action week 4
Test in action   week 4Test in action   week 4
Test in action week 4
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring Quality
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
An Introduction to Windows PowerShell
An Introduction to Windows PowerShellAn Introduction to Windows PowerShell
An Introduction to Windows PowerShell
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
PowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdfPowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdf
 
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
Creating "Secure" PHP Applications, Part 1, Explicit Code & QACreating "Secure" PHP Applications, Part 1, Explicit Code & QA
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
 
PHP Unit Testing
PHP Unit TestingPHP Unit Testing
PHP Unit Testing
 
Rest with-spray
Rest with-sprayRest with-spray
Rest with-spray
 

More from Dennis Vroegop

More from Dennis Vroegop (10)

The art of AI Art
The art of AI ArtThe art of AI Art
The art of AI Art
 
A leap around AI
A leap around AIA leap around AI
A leap around AI
 
dotNed Azure Durable Functions Slide
dotNed Azure Durable Functions SlidedotNed Azure Durable Functions Slide
dotNed Azure Durable Functions Slide
 
How to create stunning MR apps
How to create stunning MR appsHow to create stunning MR apps
How to create stunning MR apps
 
Mef dennis vroegop 20152905
Mef dennis vroegop 20152905Mef dennis vroegop 20152905
Mef dennis vroegop 20152905
 
Windows 8.1 apps: from idea to the store!
Windows 8.1 apps: from idea to the store!Windows 8.1 apps: from idea to the store!
Windows 8.1 apps: from idea to the store!
 
Scrum, it's all about the people
Scrum, it's all about the peopleScrum, it's all about the people
Scrum, it's all about the people
 
Sde2012 top ten ux tips win8
Sde2012 top ten ux tips win8Sde2012 top ten ux tips win8
Sde2012 top ten ux tips win8
 
Win8 metro infosupport
Win8 metro infosupportWin8 metro infosupport
Win8 metro infosupport
 
Rx dotNed
Rx dotNedRx dotNed
Rx dotNed
 

Recently uploaded

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Recently uploaded (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 

Power shell voor developers

  • 3. Robert Tinga Business Development Manager QUINTOR rtinga@quintor.nl 06 - 21862066 Introduction
  • 6.
  • 8. Jeroen Swart .NET Architect jswart@quintor.nl • Developer >= 1996 • Mainframe/assembler, Microsoft/C++, .NET/C# • .NET >= 2001 • Quintor >= 2011 • .NET competentie • ALM & .NET ontwikkelstraat
  • 10. > _ − REPL (Read Evaluate Print Loop) − .NET − Commands − Parameters − Objecten − Command pipeline
  • 12. > 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
  • 13. > Command pipeline − Get-Process | Sort ProcessName | Select * − Select-Object select − Sort-Object sort − Where-Object where, ? − ForEach-Object foreach, %
  • 14. > 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
  • 15. > Sort-Object − Specify order of objects − Sort ProcessName − Specify direction − Sort ProcessName -Descending − Get-Process | Sort ProcessName,Description
  • 16. > Where-Object − Filter objects by property − Where -Property ProcessName -EQ 'powershell' − Filter objects using script − Where { $_.ProcessName -eq 'powershell' } − Get-Process |? { $_.ProcessName -like 'po*' }
  • 17. > ForEach-Object − Repeat for each object − ForEach { Write-Host $_.ProcessName } − Get-Process |% { Write-Host "$($_.ProcessName)" }
  • 18. > Command pipeline − Measure-Object − Group-Object − Compare-Object − Tee-Object
  • 19. > Format-* − Format-Table (ft) − -AutoSize (ft –a) − Format-List (fl) − Format-Wide (fw) − -Column (fw –c 3) − Get-Command format-*
  • 20. > Out-* − Out-Default − Out-File − Out-Null − Out-String − Out-GridView (ogv) − Get-Command out-*
  • 21. > ConvertTo-* / ConvertFrom-* − ConvertTo-Json, ConvertFrom-Json − ConvertTo-Xml (, Get-Content) − ConvertTo-Csv, ConvertFrom-Csv − ConvertTo-Html − Get-Command convertto-*,convertfrom-*
  • 22. > Advanced pipeline − -PassThru − Multiline with ` − Multi-command on single line with ; − Select @{ Name = $_.Name; Type = 'Foo' } − Force expression evaluation using brackets ()
  • 24. > 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]
  • 25. > Host environment − Get-Variable − $Host − $Profile − $PSVersionTable
  • 27. > $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:WindowsSystem32WindowsPowerShellv1.0profile.ps1 $profile.AllUsersCurrentHosts C:WindowsSystem32WindowsPowerShellv1.0Microsoft.PowerShell_profile.ps1 $profile.CurrentUsersAllHosts C:UsersjswartDocumentsWindowsPowerShellprofile.ps1 $profile.CurrentUsersCurrentHost C:UsersjswartDocumentsWindowsPowerShellMicrosoft.PowerShell_profile.ps1 $profile (console) C:UsersjswartDocumentsWindowsPowerShellMicrosoft.PowerShell_profile.ps1 $profile (ISE) C:UsersjswartDocumentsWindowsPowerShellMicrosoft.PowerShellISE_profile.ps1
  • 28. > $Profile $global:CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent() function prompt { $Host.UI.RawUI.WindowTitle = "$($CurrentUser.Name) - $(Get-Location)" Write-Host 'PS >' -NoNewline return ' ' }
  • 29. > $PSVersionTable Name Value ---- ----- PSVersion 5.0.10586.122 PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} BuildVersion 10.0.10586.122 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1
  • 30. > Strings − Literals − 'Name: $Name' − "Name: $Name" − Format − 'Name: {0}' –f $Name − Expression − "Name: $user.Name" − "Name: $($user.Name)" Name: $Name Name: Jeroen Name: Jeroen Name: Hashtable.Name Name: Jeroen
  • 31. > Strings & regular expressions − Match − 'PowerShell' –match 'sh' − 'PowerShell' –match '^P' − 'PowerShell' –match 'P$‘ − 'PowerShell' –cmatch 'p$' − Replace − 'PowerShell' -replace 'e','E' True True False False PowErShEll
  • 32. > Arrays & objects − Command output is array or object − When Parameter type is Array, provide either array or single object as value
  • 33. > Arrays − $a = 1,2 − $a = @(1) − $a = @() − $a = 1..5 − $a += 6 − $a.GetType() -> System.Array − $a.Length − $a.Contains(1) − $a[0]
  • 34. > Objects (HashTable) − $o = @{} − $o = @{ Name = 'me' } − $o = @{ Name = 'me' PowerShell = $true } − $o = @{ Name = 'me'; PowerShell = $true }
  • 35. > Objects (PSCustomObject) $o = New-Object PSCustomObject ` | Add-Member -MemberType NoteProperty -Name 'Name' -Value 'me' -PassThru ` | Add-Member -MemberType NoteProperty -Name 'PowerShell' -Value $true -PassThru
  • 36. > Objects − $o.Name − $o.'Name' − $o = @{ Name = 'me' PowerShell = $true } − $o = @{ Name = 'me'; PowerShell = $true }
  • 37. > Scripts − Collection of commands − Conditional statements (if/else, etc.) − Parameters − Output − Execute using . Or & − Execute using full or relative path (.) . .DoSomethingSmart.ps1 . '.DoSomethingSmart.ps1'
  • 38. > 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 operators if ($condition -eq $true) { } Using explicit conditions
  • 39. > 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
  • 40. > 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
  • 41. > Scripts – foreach foreach ($item in $items) { # use $item } $items |% { # use $_ } Basic syntax Alternative
  • 42. > Scripts – for for ($index = 0; $index -lt 10; $index++) { # use $items[$index] } Basic syntax
  • 43. > Scripts – try/catch try { throw 'Serious error' throw [InvalidOperationException]'Serious error' } catch [InvalidOperationException] { write-host 'InvalidOperationException' } catch { } finally { }
  • 44. > 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 $false False
  • 45. > 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‘
  • 46. > 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
  • 47. > 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
  • 48. > Scripts – lifecycle param ( ) 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 { }
  • 50. > Functions function 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 { } }
  • 51. > Modules − PowerShell Script or C# − C# − System.Management.Automation namespace − Cmdlet base-class − Cmdlet attribute − PowerShell Script − Collection of functions − .psm1 − .psd1
  • 52. > 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 "$PSScriptRootInternal" ` -Filter '*.ps1' |% { . $_.FullName } Get-ChildItem ` -Path "$PSScriptRootFunctions" ` -Filter '*.ps1' |% { . $_.FullName }
  • 53. > Modules − Import-Module –Path '...' − Import-Module –Name '...' − System − %windir%System32WindowsPowerShellv1.0Modules − $pshomeModules − All users − %ProgramFiles%WindowsPowerShellModules − "$($env:ProgramFiles)WindowsPowerShellModules" − Current user − %UserProfile%DocumentsWindowsPowerShellModules − $homeDocumentsWindowsPowerShellModules
  • 54. > Modules − Get-Module − Get-Module –ListAvailable − Remove-Module − Import-Module –Force
  • 55. • NuGet • Chocolatey • PowerShell Package Management • TFS Build • TFS Release Management • Remote PowerShell • PowerShell DSC • Server Management > Select PowerShell | More
  • 56. • NuGet • Chocolatey • PowerShell Package Management > Select PowerShell | More
  • 57. > NuGet − zip, maar .nupkg − lib − net45 − net40 − portable-win+net45+wp8+win8+wpa81 − content − tools − init.ps1 − .psm1 − nuspec
  • 58. > NuGet − init.ps1 − installPath − toolPath − package − project − EnvDTE.Project − ProjectItems − DTE EnvDTE.DTE
  • 59. > 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
  • 61. > Chocolatey − Windows Package Manager − choco list − choco install − NuGet-based − nuspec − tools − chocolateyInstall.ps1 − chocolateyUninstall.ps1
  • 62. > Chocolatey − Install-ChocolateyPackage − Install-ChocolateyZipPackage − Install-ChocolateyVsixPackage − Install-ChocolateyEnvironmentVariable − Install-ChocolateyFileAssociation
  • 63. > 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)
  • 64. > PowerShell Modules − xcopy − System, All users, Current user − Chocolatey package − xcopy − PowerShell Package Management − PowerShell v5
  • 65. > PowerShell Package Management − Package Manager Manager
  • 66. > PowerShell Package Management − Module − Script − Package − Find, Install, Update, Publish, Save − Find-Module − Install-Package
  • 68. • TFS Build • TFS Release Management > Select PowerShell | More
  • 69. > TFS Build − XAML Build − Task-based build − Script (in VC) − Arguments
  • 70. > TFS Release Management − XAML − Task-based − TFS 2015 Update 2
  • 71. > TFS Release Management − Remote PowerShell − PowerShell Scripts − PowerShell Modules − PowerShell DSC − PowerShell Package Management (Chocolatey)
  • 72. > TFS Release Management Build Drop- location RM Target- servers Trigger release Execute script Copy files to servers
  • 73. > TFS Release Management Build Package Source RM Target- servers Chocolatey Packages PowerShell Modules Trigger release Retrieve packages Install packages
  • 74. • Remote PowerShell • PowerShell DSC • Server Management > Select PowerShell | More
  • 75. > Remote PowerShell − Enter-PSSession & Exit-PSSession − New-PSSession & Remove-PSSession − Invoke-Command -Session
  • 76. > Remote PowerShell − Enable remoting − Enable-PSRemoting − Check configuration − Test-WSMan − Limit access − Set-Item ` wsman:localhostclienttrustedhosts [name] ` -Concatenate -Force
  • 77. > Remote PowerShell − 'Double Hop' − CredSSP & Credential − Server − Enable-WSManCredSSP -Role Server − Client − Enable-WSManCredSSP -Role Client ` –DelegateComputer [machinename]
  • 78. > 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
  • 79. > PowerShell DSC bSqlDatabase Database { Ensure = "Present" Name = $DatabaseName } PowerShell DSC
  • 80. > PowerShell DSC − Desired State Configuration − Declarative − Configuration − Resource − Get − Test − Set
  • 81. > PowerShell DSC − Push vs Pull
  • 83. > Server Management − Server − Processes − Services − Resources (RAM, CPU, …) − IIS − Websites − App pools − Logging
  • 84. • 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
  • 85. • PowerShell Workflow • Debugging (incl. remote) • Classes • ISE • Automation • Extensions/Add-ons • Unit testing (Pester) • Azure (incl. PowerShell DSC) • OSS Packages & Modules > _

Editor's Notes

  1. YouTube: https://www.youtube.com/watch?v=V5Gjx4jM91A
  2. Januari 2016: 72 groningen 38 amersfoort 2 Den Haag
  3. Get-Process $p = Get-Process $p $p.GetType() $p[0] $p[0].GetType() Get-Process –Name powershell Get-Process –Name power* Get-Process power* Get-Process –n power* Get-Command Get-Command Get-Command Get-Help Get-Command Get-Help Get-Command -Full Get-Help Get-Command -Online (get-command Get-Verb).Definition Get-Alias Get-Alias cls,dir,kill
  4. PassThru: e.g. RestartService PowerShell recognizes incomplete commands; to force multiline use ` PowerShell does not use (or require) statements to end with ‘;’ , but you may use it, especially practical when invoking multiple commands in a single line Select hashtable: think LINQ projections
  5. Get-Process Get-Process | Select ProcessName, Description Get-Process | Select ProcessName, Description -First 5 Get-Process | Select ProcessName, Description | Select -First 5 Get-Process | Select ProcessName, Description -First 5 | fl Get-Process | Select ProcessName, Description -First 5 |Sort ProcessName -Descending | fl Get-Service | Select -First 20 Get-Service | Select -First 20 | ft -a Get-Service | fw -c 3 Get-Service | Out-GridView Get-Service | Out-GridView -PassThru Get-Service | Out-GridView -PassThru -Title 'Select a service to restart' Get-Service | ConvertTo-Json Get-Service | ConvertTo-Html | Out-File d:\get-service.html Get-Service | ConvertTo-Html | Out-File d:\get-service.html;Start-Process d:\get-service.html Get-Service | Select -First 1 (Get-Service | Select -First 1).Name Get-Service | Select Name -First 5 (Get-Service | Select Name -First 5).Name
  6. PowerShell Tools for Visual Studio https://visualstudiogallery.msdn.microsoft.com/c9eb3ba8-0c59-4944-9a62-6eee37294597 Writing a Windows PowerShell Host Application https://msdn.microsoft.com/en-us/library/ee706563(v=vs.85).aspx
  7. DEMO #1 Write-Hello.ps1 param ( [Parameter(Mandatory = $true)] [string]$Name ) Write-Host 'Writing hello...' Write-Output "Hello $Name" > .\Write-Hello.ps1 -Name 'Jeroen' > $h = .\Write-Hello.ps1 -Name 'Jeroen' > $h DEMO #2 Write-Hello.ps1 param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string[]]$Name ) Write-Host 'Writing hello...' $Name |% { Write-Output "Hello $_" } > .\Write-Hello.ps1 -Name 'Jeroen','you' > 'Jeroen','you' | .\Write-Hello.ps1 DEMO #3 Write-Hello.ps1 param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string[]]$Name ) begin { Write-Host 'Writing hello...' } process { $Name |% { Write-Output "Hello $_" } } > 'Jeroen','you' | .\Write-Hello.ps1 > .\Write-Hello.ps1 -Name 'Jeroen','you' DEMO #4 Write-Hello.ps1 param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string[]]$Name ) begin { Write-Host 'Writing hello...' } process { $Name |% { "Hello $_" } |% { Write-Verbose $_ Write-Output $_ } } > .\Write-Hello.ps1 -Name 'Jeroen','you' > .\Write-Hello.ps1 -Name 'Jeroen','you' –Verbose > $r = .\Write-Hello.ps1 -Name 'Jeroen','you' -Verbose > $r
  8. Understanding a Windows PowerShell Module: https://msdn.microsoft.com/en-us/library/dd878324(v=vs.85).aspx How to Write a PowerShell Script Module: https://msdn.microsoft.com/en-us/library/dd878340(v=vs.85).aspx How to Write a PowerShell Binary Module: https://msdn.microsoft.com/en-us/library/dd878342(v=vs.85).aspx Writing a PowerShell module in C#, Part 1: The basics http://www.powershellmagazine.com/2014/03/18/writing-a-powershell-module-in-c-part-1-the-basics/ Basics of Writing a PowerShell Module with C#, Part 2: Debugging http://www.powershellmagazine.com/2014/04/08/basics-of-writing-a-powershell-module-with-c-part-2-debugging/
  9. EnvDTE.Project: https://msdn.microsoft.com/en-us/library/envdte.project.aspx EnvDTE.DTE: https://msdn.microsoft.com/en-us/library/envdte.dte.aspx
  10. Show Write-Hello solution init.ps1 Write-Hello.psm1 nuspec Package.ps1 Publish.ps1 Run Package.ps1 show package Create new project add/show package source add nuget package open Package Manager Console Get-Module Write-Hello –Name ‘Jeroen’
  11. https://chocolatey.org/
  12. http://www.powershellgallery.com/
  13. http://www.powershellgallery.com/
  14. http://www.powershellgallery.com/
  15. Create PowerShell module (at 'D:\Projects\PowerShell\WriteHello\‘) Register local folder as source (at ‘D:\Packages’) Get-PackageSource Register-PackageSource -Name ‘Demo’ -Location ‘D:\Packages’ -ProviderName PowerShellGet -Trusted Publish module to local source Publish-Module -Path 'D:\Projects\PowerShell\WriteHello\' -Repository Demo Install module from local source Find-Module WriteHello Find-Module WriteHello | Install-Module -Scope CurrentUser Import-Module WriteHello
  16. Debug.ps1 Get-Variable dir env: ApplyVersion.ps1 Parameters in task Parameters in script
  17. http://powershell.com/cs/media/p/7257.aspx Windows Server Core, Windows Server Nano & Windows Containers
  18. Enable-PSRemoting, of winrm quickconfig Trustedhosts zowel IP’s, als FQDN’s met wildcards
  19. To verify: Get-WSManCredSSP
  20. Met ‘vanilla’ PowerShell programmeer je ieder detail van iedere stap in het deployment-proces, inclusief iedere kleine uitzondering en afwijking. Terwijl veel van deze stappen generiek en herbruikbaar zijn. Je kunt hiervoor een library maken van herbruikbare functies; maar PowerShell DSC biedt dit al, in de vorm van herbruikbare resources. Naast Microsoft, wordt ook veel door de community aangeboden, en je kunt zelf eenvoudig resources toevoegen. Dit voorbeeld is voor het aanmaken van een SQL Server database.
  21. In plaats van iedere stap uit te programmeren, beschrijf je met PowerShell DSC het gewenste eindresultaat. Een volledig eindresultaat wordt beschreven in een ‘configuration’, welke is verdeelt in resources. Een resource kan een folder zijn met inhoud, een windows-feature die moet worden geactiveerd (zoals IIS), of een MSI of web-package die moet worden geinstalleerd. Dit voorbeeld toont een resource voor het aanwezig zijn van een SQL Server database.
  22. DSC Configuration for deploying Website Batch-service
  23. CPU Load Get-WmiObject win32_processor | select LoadPercentage Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average Performance Counters Get-Counter '\Memory\Available MBytes‘ Get-Counter -ListSet *memory* | Select-Object -ExpandProperty Counter Get-Counter -ComputerName localhost '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples | Select-Object -Property instancename, cookedvalue| Sort-Object -Property cookedvalue -Descending| Select-Object -First 20| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100).toString('P')}} –AutoSize function Get-MemoryUsage ($ComputerName=$ENV:ComputerName) { if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) { $ComputerSystem = Get-WmiObject -ComputerName $ComputerName -Class Win32_operatingsystem -Property CSName, TotalVisibleMemorySize, FreePhysicalMemory $MachineName = $ComputerSystem.CSName $FreePhysicalMemory = ($ComputerSystem.FreePhysicalMemory) / (1mb) $TotalVisibleMemorySize = ($ComputerSystem.TotalVisibleMemorySize) / (1mb) $TotalVisibleMemorySizeR = “{0:N2}” -f $TotalVisibleMemorySize $TotalFreeMemPerc = ($FreePhysicalMemory/$TotalVisibleMemorySize)*100 $TotalFreeMemPercR = “{0:N2}” -f $TotalFreeMemPerc # print the machine details: “Name: $MachineName” “RAM: $TotalVisibleMemorySizeR GB” “Free Physical Memory: $TotalFreeMemPercR %” } } Logging cd d:\www\events\app_data dir | select -last 1 | get-content |? { $_ -match 'error' }
  24. Windows PowerShell https://msdn.microsoft.com/en-us/powershell/mt173057.aspx https://technet.microsoft.com/library/bb978526.aspx PowerShell DSC https://msdn.microsoft.com/en-us/powershell/dsc/overview PowerShell SDK https://msdn.microsoft.com/library/dd835506.aspx Windows PowerShell Blog https://blogs.msdn.microsoft.com/powershell/ Hey Scripting Guy https://blogs.technet.microsoft.com/heyscriptingguy/ PowerShell ISE Add-Ons http://social.technet.microsoft.com/wiki/contents/articles/2969.windows-powershell-ise-add-on-tools.aspx
  25. OSS Packages: chocolatey.org OSS Modules: powershellgallery.com Azure PowerShell DSC https://azure.microsoft.com/en-us/blog/vm-agent-and-extensions-part-1/ https://blogs.msdn.microsoft.com/powershell/2014/08/07/introducing-the-azure-powershell-dsc-desired-state-configuration-extension/ https://azure.microsoft.com/en-us/blog/new-additions-to-the-azure-vm-powershell-dsc-extension/