James Kolpack, InRAD LLC popcyclical.com Adapted from a Keith Hill PresentationKeith Hill Presentation Come up and pick up a PowerShell Quick Reference.

Slides:



Advertisements
Similar presentations
CIS 240 Introduction to UNIX Instructor: Sue Sampson.
Advertisements

Rick Toner MCSD, MCPD, MCITP Blog:
Microsoft PowerShell Tom Roeder CS fa. Motivation.NET as a platform shell web server database access Native access to resources eaiser to manage.
Find Command Characteristics –Locate files descending from multiple starting points –Employs regular expressions Examples On entire system: >find / -name.
James Boother Blog: INTRODUCTION TO POWERSHELL.
CS311 – Today's class Perl – Practical Extraction Report Language. Assignment 2 discussion Lecture 071CS Operating Systems I.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Great people, great experience, great passion Administering SharePoint with Windows PowerShell Go Beyond the Management Shell with SharePoint and Windows.
Basic.  Powershell scripts are flat text files that end with “.ps1” (e.g. myscript.ps1)  Similar to other scripting languages, whatever you can do on.
Bash, part 2 Prof. Chris GauthierDickey COMP Unix Tools.
INTRODUCTION TO POWERSHELL Neil Iversen. Points of Interest  Introduction  Getting Around  Basic Syntax  Making yourself at ~  Not-So-Basic Syntax.
Guide To UNIX Using Linux Third Edition
Basic.  PS is a command line interpreter/scripting environment  Designed for.Net  Similar to C#  Easy to instantiate.Net classes  Standardized syntax.
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.
PowerShell: Drink the Kool-Aid!. Who we are…..Who we are…..
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)PHP Recap.
MS WINDOWS POWER SHELL CSE 535 Operating Systems.
AIT 616 Fall 2002 PHP. AIT 616 Fall 2002 PHP  Special scripting language used to dynamically generate web documents  Open source – Free!!!  Performs.
8 Shell Programming Mauro Jaskelioff. Introduction Environment variables –How to use and assign them –Your PATH variable Introduction to shell programming.
Windows PowerShell Deep Dive 1 Morgan Simonsen Ementor.
PowerShell Basics. o PowerShell is a great way to manipulate server and/or workstation components o It’s geared toward system administrators by creating.
Section 6: Using Windows PowerShell to Manage Group Policy Introducing Windows PowerShell Windows PowerShell Library for Group Policy Windows PowerShell-Based.
December, 21, 2010 Bartek Bielawski Sr IT Site Services Specialist Warsaw, Poland.
UNIX Shell Script (1) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology
Shell Programming. Introducing UNIX Shells  Shell is also a programming language and provides various features like variables, branching, looping and.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
Good Morning and Thank You!.  Have some Fun!  Learn at least one thing new!  Make myself available to you So please …  Ask questions and enjoy!
Shell Programming. Creating Shell Scripts: Some Basic Principles A script name is arbitrary. Choose names that make it easy to quickly identify file function.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
PowerShell For SharePoint Developers Neil Iversen Inetium
Introduction to PHP.
Shell Programming Learning Objectives: 1. To understand the some basic utilities of UNIX File 2. To compare UNIX shell and popular shell 3. To learn the.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
1 © 2000 John Urrutia. All rights reserved. Session 5 The Bourne Shell.
Windows PowerShell Introduction 1 Morgan Simonsen Ementor.
Topic 2: Working with scalars CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 2, pages 19-38, Programming Perl 3rd edition chapter.
 An alias is an alternative name assigned to a Cmdlet.  Aliases allow users to quickly interact with the shell.  The Cmdlet get-alias is.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
Agenda Positional Parameters / Continued... Command Substitution Bourne Shell / Bash Shell / Korn Shell Mathematical Expressions Bourne Shell / Bash Shell.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
 It is Microsoft's new task-based command- line shell and scripting language designed especially for system administration.  It helps Information Technology.
Windows PowerShell. What is Windows PowerShell? A command-line interface (CLI) A new way of developing Windows and other products to be more manageable.
PowerShell for Developers GOPAS: | | Ing. Ondřej Ševeček | GOPAS a.s. | MCM: Directory Services |
Sed. Class Issues vSphere Issues – root only until lab 3.
POWERSHELL ABOVE AND BEYOND: GUIS, WORKFLOWS, AND MORE Dean Corcoran Partner Service Account Manager (Cloud) – MCT – MCITP:EA Microsoft Australia SESSION.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Introduction to SQL Server Automation with Powershell by Chris Sommer.
Ravikanth C.
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
Bash Introduction (adapted from chapters 1 and 2 of bash Cookbook by Albing, Vossing, & Newham) CPTE 440 John Beckett.
Ruby: An Introduction Created by Yukihiro Matsumoto in 1993 (named after his birthstone) Pure OO language (even the number 1 is an instance of a class)
PHP Introduction.
Introduction to PowerShell
What is Bash Shell Scripting?
PHP.
PowerShell Best Practices for SQL DBA’s
PowerShell Flow of Control Copyright © 2016 – Curt Hill.
PHP an introduction.
Introduction to Bash Programming, part 3
Effective Windows PowerShell
Presentation transcript:

James Kolpack, InRAD LLC popcyclical.com Adapted from a Keith Hill PresentationKeith Hill Presentation Come up and pick up a PowerShell Quick Reference handout

CodeStock is proudly partnered with: Send instant feedback on this session via Twitter: Send a direct message with the room number d codestock 413c This session is great! For more information on sending feedback using Twitter while at CodeStock, please see the “CodeStock README” in your CodeStock guide. RecruitWise and Staff with Excellence - 1

2

What is Windows PowerShell Dynamic scripting language Next generation command-line shell for Windows 3 James Kolpack

What can it do? Automate complex, repetitive tasks.NET Interactive Prompt Build command line utilities Host-able script engine Windows Server management Exchange SQL Server IIS James Kolpack

PowerShell Innovations Cmdlets Providers.NET type system Object flow pipeline Intrinsic support for regular expressions, WMI and XML Extensible 5 James Kolpack

Getting Started… Download and Install Set PowerShell to allow script execution. PS> Set-ExecutionPolicy Unrestricted Check out the community extensions for dozens of new commands you might find useful 6 James Kolpack

Resources TitleWhat?Where? Microsoft Scripting Center An actively updated resource from Microsoft. Includes introductory material, articles, webcasts, script repository, and more. technet.microsoft.com/ scriptcenter/ powershell.aspx Windows PowerShell In Action Author Bruce Payette, one of the principal creators of PowerShell, gives this comprehensive tome on everything about the language and how to apply it. Become an expert! manning.com/ payette Intro to Windows PowerShell A reference library of PowerShell examples ranging everywhere between “Getting Started” to advanced topics. co.uk/powershell Keith HillPowerShell MVP and Community Extensions coordinator – wrote the demo script keithhill.spaces.live.com Power- Scripting Podcast Podcast on Windows PowerShell with Jonathan Walz and Hal Rottenberg powerscripting.net 7 James Kolpack

Integrated Scripting Environment James Kolpack popcyclical.com 8

9 James Kolpack DEMO SCRIPT

Shell Stuff Jump start with familiar commands cd dir type copy del 10 PS>.\shellStuff.ps1 James Kolpack

Cmdlets Composable cmdlets “Simple” cmdlets strung together via pipeline and/or script to perform “complex” tasks. Standardized naming scheme for cmdlets - Get-Date, Remove-Item Extensible by 3 rd parties (PowerShell Community Extensions) 11 PS>.\cmdlets.ps1 James Kolpack

The Pipeline Cmdlets output.NET objects (structured information) instead of unstructured text. “Compose” cmdlets together using the pipe “|” character ObjectFlow engine manages objects in the pipeline: “unrolls” collections, outputting each individual element Coerces objects for parameter binding Renders to a textual view for interactive users and legacy apps (stdout) Extended Type System Wrapper types around objects are created to stash book-keeping info PSObject, PSCustomObject, GroupInfo, MatchInfo Legacy apps dump text ( System.String objects) into the pipeline 12 PS>.\pipeline.ps1 James Kolpack

Pipeline Cmdlets Manipulators of generic objects! Blades of the PowerShell Swiss Army Knife Where-Object Filters incoming object stream. get-process | where { $_.HandleCount –gt 500 } Sort-Object Sorts the stream of objects based on one or more properties or an expression. get-childitem | sort LastWriteTime -desc Select-Object Projects properties and expands collections into custom object. get-process | select ProcessName –Exp Modules Group-Object Transforms stream of objects into a stream of GroupInfo objects that share a common property. get-childitem | group Extension 13 James Kolpack

Pipeline Cmdlets Continued Foreach-Object Manipulate individual objects in stream. $feed.rss.channel.item | foreach { $_.Title } Measure-Object Calculates stats such as sum, min, max, ave, lines, characters, words 14 James Kolpack

PowerShell Pipeline: Moving Objects gps | where { $_.PM –gt 40MB } | sort ProcessName 15 System.Diagnostics.Process where Process.Paged MemorySize > 40*1024*1024 No Yes System.Diagnostics.Process Sort on Process.ProcessName Process.GetProcesses()System.Diagnostics.Process out-default Handles NPM … System.String James Kolpack

Type System: Formatting Output Format-Table (ft) Displays output in tabular format Limited number of properties can be displayed in tabular form PowerShell sizes columns evenly use -autoSize for better sizing Format-List (fl) Displays properties in a verbose list format A view may be defined to limit output in list mode - use fl * to force display of all properties Format-Wide (fw) Displays a single property in multiple columns Use -autoSize parameter for better column sizing 16 PS>.\typeSystem.ps1 James Kolpack

Providers Prompt doesn’t always reside in the file system PowerShell ships with providers for: File system, registry, environment, variables, functions, aliases and the certificate store Manipulate various stores as-if a file system Extensible by 3 rd parties (PowerShell Community Extensions) 17 PS>.\providers.ps1 James Kolpack

Scripting Language: Variables Variables are always prefixed with $ except: gps -OutVariable Procs –ErrorVariable Err Set-Variable FirstName 'John' Can be loosely or strongly typed: $a = 5 $a = "hi" [int]$b = 5 $b = "hi" # Errors since $b is type int $c = [int]"7" # Coerce string to int Automatic variables $null, $true, $false, $error, $?, $LastExitCode, $OFS, $MyInvocation 18 James Kolpack

Scripting Language - Variables Global variables: $home, $host, $PSHome, $pid, $profile, $pwd Scoped variables: Qualified variable names: $global:foo; $script:bar; $local:baz; $private:ryan Normal scope resolution on reads when not using qualified name Copy on write semantics for child scopes unless using qualified name Private scoping prevents child scopes from seeing variable 19 James Kolpack

Scripting Language: Data Types All.NET types with special support for: Array: $arr = 1,2,3,4 Hashtable: $ht key2="bar"} Regex: $re = [regex]"\d{3}-\d{4}" Xml: $xml = [xml]" text “ Numerics support: $i = 10; $d = 3.14; $d2 = 3e2; $h = 0x20 Support for K, M and G numeric suffixes e.g.: 1KB = 2 10, 1MB = 2 20, 1GB = James Kolpack

Scripting Language: Strings $str = "Hello World" The escape character is ` (backtick) `` `' `" `$ `0 `a `b `f `n `r `t `v Variable evaluation in strings Double quotes interpolate and single quotes don’t: "Pi is $d" => Pi is 3.14 'Pi is $d' => Pi is $d Here strings – literal multi-line $str >> Here strings can have embedded new lines >> and they provide the closest thing to a block comment in v1.0. >> >> 21 James Kolpack

Scripting Language: Operators 22 Type of OperationOperators Arithmetic: Numeric + - * / () % Arithmetic: String + to concatenate, * to repeat "-" * 72, -f formatting Assignment = += -= *= /= %= Negation ! -not Comparison: General -eq -lt -gt -le -ge -ne -and -or Comparison: String -ceq -clt -cgt -cle -cge -cne -like –notlike -match -notmatch -clike -cnotlike -cmatch -cnotmatch String Manipulation -replace Array -contains -ccontains Bitwise -band -bor -bnot Type test/conversion -is -isnot -as Remember: Many operators start with hyphens “c” indicates case sensitive

Scripting Language: Control Flow Conditionals: if ($a –gt 0) { "positive" } elseif ($a –eq 0) { "zero" } else { "negative" } switch ($op) { "add" { $op1 + $op2 } "sub" { $op2 - $op1 } default { "unrecognized operator: $op" } } 23 James Kolpack

Scripting Language: Control Flow continued Loops: while ($i –lt 10) { ($i++) } for ($i = 0; $i –lt 10; $i++) { $i } foreach ($arg in $args) { $arg } 24 James Kolpack

Scripting Language: Functions Simple function defined at command prompt: PS> function Greeting($name) { "Hello $name" } Flexible function parameters Loose or strong typing Named parameters Optional parameters Extra parameters available via $args function addNumbers([int]$x, [int]$y = 0) { $total = $x + $y foreach ($arg in $args) { $total += [int]$arg } $total } 25 James Kolpack

Scripting Language – Error Handling Errors come in terminating and non-terminating flavors Terminating errors are usually generated by script (null ref exception) Non-terminating errors are usually generated by cmdlets (access denied) Trap terminating errors using trap statement trap [exception] { (break|continue) } Trap non-terminating errors using -ErrorAction parameter get-process | select –expand Modules –ea SilentlyContinue ErrorAction parameters: Stop, Inquire, Continue, SilentlyContinue 26 James Kolpack

Scripting Language: Misc Array Manipulation $arr = 1,2,3,4 $arr += 5,6,7,8 $arr[2..4] => $arr[ ] => Command Substitution echo "The time is $(get-date)" Comment character # comments to end of line Dot source script file to import into current scope PS C:\>..\vs80vars.ps1 27 James Kolpack PS>.\scripting.ps1

Working with.NET Objects Create new objects $webClient = new-object System.Net.WebClient Get and set properties (get-date).Year (get-item foo.txt).IsReadOnly = $true Call methods "Hello World".split(" ") Access static members [Math]::Pow(2,30) # PowerShell prepends 'System.' [DateTime]::UtcNow # if type name not found 28 PS>.\dotnet.ps1;.\regex.ps1;.\xml.ps1 James Kolpack

WMI and PowerShell Get-WMIObject Get-Help -name Get-WMIObject get-wmiobject -namespace "root\cimv2" –list Access filesystem information $disks = gwmi Win32_LogicalDisk –computername localhost $disks[0].freespace $disks[0].freespace/1gb $disks[0].filesystem Get a list of the Hotfixes that have been installed $hotfixes = gwmi Win32_QuickFixEngineering –computername localhost $hotfixes | format-table Hotfixid OperatingSystem gwmi win32_OperatingSystem -computername localhost 29 James Kolpack PS>.\wmi.ps1 (Windows Management Instrumentation)

Storing Script Blocks as Data Script can be stored as data and later executed, like a lambda expression PS > $script = {get-process} PS> $script get-process PS> &$script Handles NPM(K) PM(K) WS(K) VS(M) CPU(s) Id ProcessName alg CCAPP CCEVTMGR 30 PS>.\scriptBlock.ps1 James Kolpack

PowerShell 2.0 – new stuff Remote management and invokes Integrated Scripted Environment Eventing Background jobs Modules (new way to extend PowerShell) Misc enhancements, perf improvements and bug fixes 31 James Kolpack

Resources TitleWhat?Where? Microsoft Scripting Center An actively updated resource from Microsoft. Includes introductory material, articles, webcasts, script repository, and more. technet.microsoft.com/ scriptcenter/ powershell.aspx Windows PowerShell In Action Author Bruce Payette, one of the principal creators of PowerShell, gives this comprehensive tome on everything about the language and how to apply it. Become an expert! manning.com/ payette Intro to Windows PowerShell A reference library of PowerShell examples ranging everywhere between “Getting Started” to advanced topics. co.uk/powershell Keith HillPowerShell MVP and Community Extensions coordinator – wrote the demo script keithhill.spaces.live.com Power- Scripting Podcast Podcast on Windows PowerShell with Jonathan Walz and Hal Rottenberg powerscripting.net 32 James Kolpack Come up and pick up a PowerShell Quick Reference handout

Cmdlets compared to Unix Utilities Characteristics of Unix utilties: Specialized and work with unstructured information $ find. -type f -name "e*" -exec rm {} ; Characteristics of PS cmdlets: Generic, simple and work with structured information PS> dir. -recurse | where {!$_.PSIsContainer -and ($_.Name -like "e*")} | remove-item 33 James Kolpack