PowerShell: Script Development Environment, Basic Language Elements, String and Date Methods

PowerShell: Script Development Environment, Basic Language Elements, String and Date Methods
Slide Note
Embed
Share

PowerShell is a powerful tool for developers and administrators, offering extensive object-oriented pipeline support and enabling automation of tasks. Learn about its various versions, script development environments, language elements, and useful string and date methods. Dive into the world of PowerShell to enhance your productivity and streamline your workflow.

  • PowerShell
  • Script Development
  • Language Elements
  • Automation
  • Object-oriented

Uploaded on Mar 09, 2025 | 2 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

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 = '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)

  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 = @" 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 }

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

  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 na kurzech v po ta ov kole GOPAS, a.s. GOPAS: info@gopas,cz| www.gopas.cz| www.facebook.com/P.S.GOPAS

More Related Content