1 / 28

PowerShell for Developers

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.

elden
Télécharger la présentation

PowerShell for Developers

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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)

  3. 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

  4. 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

  5. Determine version • $psVersionTable • Get-Host • powershell -v 2, powershell -v 3

  6. Script development environment • Notepad • PowerShell ISE • third-party free download • not necessary anymore since Windows 8

  7. 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

  8. String and Date methods • [String] • ToLower() • ToUpper() • Split() • Trim() • [DateTime] • AddDays() • Parse()

  9. Object wrappers (adapters) • Get-Member • .psbase, .psadapted, .psextended, .psobject • Get-Process, [XML]

  10. Weird access to non-existing members • .NonExistentProperty - no efect, empty • .NonExistentMethod() - exception • $array[outsideIndex] - exception

  11. Example: Object pipe Get-Process, Stop-Process New-Object System.DirectoryServices.DirectoryEntry New-Object System.DirectoryServices.DirectorySearcher [System.Collections.ArrayList] [System.Collections.Hashtable]

  12. 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()

  13. Example: Static methods and properties • [System.Text.ASCIIEncoding]::ASCII.GetBytes() • [System.Math]::PI, [Math]::Round() • [Convert]::ToBase64String(), [BitConverter]::ToString()

  14. Type accelerators • [ADSI] • [WMICLASS] • [XML]

  15. Custom objects • New-Object PSCustomObject • Add-Member

  16. Weird array comparisons @(5, 3, 2, 8, 11) -gt 6 @(5, (Get-Date), $null, 2, $null, 11) -ne $null

  17. 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

  18. 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

  19. Weird collection member functions • PowerShell 3 and newer • If the member does not exist in the collection itself, it gets called on all members

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

  21. 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)

  22. 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('…')

  23. 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 }

  24. 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

  25. Exception handling try { throw } catch [type] {} finally {} $error -ErrorAction $errorActionPreference throw 'some error' throw (Get-Process)[5]

  26. Win32API with PINVOKE • www.pinvoke.net

  27. 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

  28. NASHLEDANOU nakurzech v počítačové škole GOPAS, a.s. GOPAS: info@gopas,cz| www.gopas.cz | www.facebook.com/P.S.GOPAS

More Related