PowerShell for Developers: Introduction, Features, and Development Guide
Learn why developers should use PowerShell, its command line capabilities, version details, script development environment, language elements, object wrappers, type accelerators, weird features, and examples.
PowerShell for Developers: Introduction, Features, and Development Guide
E N D
Presentation Transcript
PowerShell for Developers Ing. Ondřej Ševeček | GOPAS a.s. | MCM: Directory Services | MVP: Enterprise Security | Certified Ethical Hacker | ondrej@sevecek.com | www.sevecek.com | GOPAS: info@gopas,cz| www.gopas.cz | www.facebook.com/P.S.GOPAS
Why the admins use PowerShell • Newer command line marketing • older VBScript still supported but with limited functionality • Script from command line or textual .PS1 files • extensive object oriented pipeline • support for CMD, EXE, D/COM, NET (plus Win32API through PINVOKE)
Why developers might be interested • Provide Admins with familiar interface for custom applications • own cmdlets in NET • Automate own tasks • builds, file distribution, signing, packaging etc. • Develop installation tasks • MSIEXEC custom actions - external • Test / validate / proof of concept • which is non-compiled, quickly written
PowerShell versions • Version 1 • download for Windows XP and 2003 and Vista • built into Windows 2008 • Version 2 • download for Windows XP and 2003, Vista, 2008 • built into Windows 7 and 2008 R2 • NetFx 2.0 CLR • Version 3 • download for Windows 7 and 2008 R2 • built into Windows 8 and 2012 • NetFx 4.0 CLR • Version 4 • download for Windows 7 and 2008 R2, 8 and 2012 • built into Windows 8.1 and 2012 R2 • NetFx 4.5 CLR • Download as Windows Management Framework
Determine version • $psVersionTable • Get-Host • powershell -v 2, powershell -v 3
Script development environment • Notepad • PowerShell ISE • third-party free download • not necessary anymore since Windows 8
Basic language elements • Variables, values and constants • $true, $false, 0x38B, $null • 'string', "string", {code} • @(array), @{hash}, (1..30) • Types (objects vs. structs) • Operators • -eq/-ceq, -ge/-gt, -le/-lt, -like, -clike, -match, -cmatch, -join, -split, -f, -is • -and, -or, -not, !, -xor, -band, -bor, -not, -bxor • *, /, % • Conditions • While, Do While, Foreach, break, continue • Switch • Functions
String and Date methods • [String] • ToLower() • ToUpper() • Split() • Trim() • [DateTime] • AddDays() • Parse()
Object wrappers (adapters) • Get-Member • .psbase, .psadapted, .psextended, .psobject • Get-Process, [XML]
Weird access to non-existing members • .NonExistentProperty - no efect, empty • .NonExistentMethod() - exception • $array[outsideIndex] - exception
Example: Object pipe Get-Process, Stop-Process New-Object System.DirectoryServices.DirectoryEntry New-Object System.DirectoryServices.DirectorySearcher [System.Collections.ArrayList] [System.Collections.Hashtable]
Example: COM objects $word = New-Object -ComObject 'Word.Application' $doc = $word.Documents.Add() $range = $doc.Range() $range.Font.Size= 20 $range.Font.Name= 'Verdana' $range.ParagraphFormat.Alignment= 2 $range.Text = 'Hellow world' $docName = 'c:\public\hello.docx' $doc.SaveAs([ref] $docName) $word.Quit()
Example: Static methods and properties • [System.Text.ASCIIEncoding]::ASCII.GetBytes() • [System.Math]::PI, [Math]::Round() • [Convert]::ToBase64String(), [BitConverter]::ToString()
Type accelerators • [ADSI] • [WMICLASS] • [XML]
Custom objects • New-Object PSCustomObject • Add-Member
Weird array comparisons @(5, 3, 2, 8, 11) -gt 6 @(5, (Get-Date), $null, 2, $null, 11) -ne $null
Weir parameter parsing • Parsing in command mode • everything is string except for variables and things in parenthesis • watch out for array goes just with comma separator , • Parsing in expression mode • First token switches the mode: • letter, &, .<letter>, .<space> • number, variable, quoted string
Weird default values and conversions • [string] $nothing = $null • [int] $noNumber = $null • [StringBuilder] $noStrBuilder = $null • [int] '55' • '38' * 3 • '38' + '95' • 95 + '11' • [string] (Get-Process) • Get-Process | fl * | Out-String
Weird collection member functions • PowerShell 3 and newer • If the member does not exist in the collection itself, it gets called on all members
Weird function return values • Whatever goes to pipe in function is returned in array • If you return single-item array it gets converted into a single object • If you return [ArrayList], it converts to [Object[]]
Example: SHA1 $name = 'zkusebniretezec' $nameBytes = [System.Text.ASCIIEncoding]::ASCII.GetBytes($name) $sha = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider $hashBytes = $sha.ComputeHash($nameBytes) # bytesarray (20 bytes as SHA-1 isalways 160bits) $hashBytes # thesame in Base64 [Convert]::ToBase64String($hashBytes) # thesame in Hex [BitConverter]::ToString($hashBytes)
C# from PowerShell • Here strings • start @" at the end of a line • end as the first character on an empty line "@ Add-Type -TypeDefinition $hereStringDef Add-Type -AssemblyName 'My.Assembly.Name' Add-Type -Path 'c:\projects\myassemblyname.dll' [System.Reflection.Assembly]::LoadFile('…')
Example: Cookie-aware WebClient $typeCookieAwareWebClient = @" namespaceSevecek { public classCookieAwareWebClient : System.Net.WebClient { privateSystem.Net.CookieContainercookieContainer = newSystem.Net.CookieContainer(); protectedoverrideSystem.Net.WebRequestGetWebRequest(System.Uriaddress) { System.Net.WebRequestbaseRequest = base.GetWebRequest(address); if (baseRequestisSystem.Net.HttpWebRequest) { (baseRequest as System.Net.HttpWebRequest).CookieContainer = cookieContainer; } return baseRequest; } } } "@ if (-not ('Sevecek.CookieAwareWebClient' -as [type])) { Add-Type -TypeDefinition $typeCookieAwareWebClient }
Weird struct assignment $structs = @" namespace Sevecek { public structsubStruct { public string name; public int age; } public structparentStruct { public string id; public subStruct person; } } "@ Add-Type -TypeDefinition $structs $onePerson = New-Object parentStruct $onePerson.person.name = 'ondrej' $onePerson.person
Exception handling try { throw } catch [type] {} finally {} $error -ErrorAction $errorActionPreference throw 'some error' throw (Get-Process)[5]
Win32API with PINVOKE • www.pinvoke.net
Custom CMDLETs in C# • using System.Management.Automation • Class for each cmdlet - decorated as cmdlet • Public properties as parameters - decorated again • Override void processing methods • WriteObject() to pipeline • http://msdn.microsoft.com/en-us/library/dd878294(v=vs.85).aspx
NASHLEDANOU nakurzech v počítačové škole GOPAS, a.s. GOPAS: info@gopas,cz| www.gopas.cz | www.facebook.com/P.S.GOPAS