Šablona TechEd 2014

Download Report

Transcript Šablona TechEd 2014

PowerShell for developers
Ing. Ondřej Ševeček
MCSM:Directory | MVP:Enterprise Security |
Certified Ethical Hacker | MCSE:SharePoint
[email protected] | www.sevecek.com
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
Example: Object pipe
Get-Process, Stop-Process
Export-Csv, Import-Csv
Import-CliXml, Export-CliXml
CERTUTIL | ConvertFrom-Csv
New-Object System.DirectoryServices.DirectoryEntry
New-Object System.DirectoryServices.DirectorySearcher
[System.Collections.ArrayList]
[System.Collections.Hashtable]
DSQUERY | Get-WmiObject
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: 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 = 'zkusebni retezec'
$nameBytes = [System.Text.ASCIIEncoding]::ASCII.GetBytes($name)
$sha = New-Object
System.Security.Cryptography.SHA1CryptoServiceProvider
$hashBytes = $sha.ComputeHash($nameBytes)
# bytes array (20 bytes as SHA-1 is always 160bits)
$hashBytes
# the same in Base64
[Convert]::ToBase64String($hashBytes)
# the same 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 = @"
namespace Sevecek {
public class CookieAwareWebClient : System.Net.WebClient
{
private System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
protected override System.Net.WebRequest GetWebRequest(System.Uri address)
{
System.Net.WebRequest baseRequest = base.GetWebRequest(address);
if (baseRequest is System.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 struct subStruct {
public string name;
public int age;
}
public struct parentStruct {
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/enus/library/dd878294(v=vs.85).aspx
Kurzy Počítačové školy Gopas na
www.gopas.cz
GOC171 - Active Directory Troubleshooting
GOC172 - Kerberos Troubleshooting
GOC173 - Enterprise PKI
GOC174 - SharePoint 2013 Troubleshooting
GOC175 - Advanced Security
GOC169 - Auditing ISO/IEC 2700x
Získejte tričko TechEd 2014
za vyplněný hodnotící dotazník.
Počítačová škola Gopas – Vaše IT škola života