POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010.

Slides:



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

Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
Microsoft PowerShell Tom Roeder CS fa. Motivation.NET as a platform shell web server database access Native access to resources eaiser to manage.
James Boother Blog: INTRODUCTION TO POWERSHELL.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Linux+ Guide to Linux Certification, Second Edition
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.
Guide To UNIX Using Linux Third Edition
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
Basic.  PS is a command line interpreter/scripting environment  Designed for.Net  Similar to C#  Easy to instantiate.Net classes  Standardized syntax.
Shell Programming 1. Understanding Unix shell programming language: A. It has features of high-level languages. B. Convenient to do the programming. C.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
 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.
CTEC 1863 – Operating Systems Shell Scripting. CTEC F2 Overview How shell works Command line parameters –Shift command Variables –Including.
Ch 111 Chapter 11 Advanced Batch Files. Ch 112 Overview This chapter focuses on batch file commands that allow you to:  write sophisticated batch files.
Shell Scripting Awk (part1) Awk Programming Language standard unix language that is geared for text processing and creating formatted reports but it.
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
Introduction to Shell Script Programming
1 Operating Systems Lecture 3 Shell Scripts. 2 Shell Programming 1.Shell scripts must be marked as executable: chmod a+x myScript 2. Use # to start a.
1 Operating Systems Lecture 3 Shell Scripts. 2 Brief review of unix1.txt n Glob Construct (metacharacters) and other special characters F ?, *, [] F Ex.
Chapter Nine Advanced Shell Scripting1 System Programming Advanced Shell Scripting.
Windows PowerShell Deep Dive 1 Morgan Simonsen Ementor.
Week 7 Working with the BASH Shell. Objectives  Redirect the input and output of a command  Identify and manipulate common shell environment variables.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
PMS /134/182 HEX 0886B6 PMS /39/80 HEX 5E2750 PMS /168/180 HEX 00A8B4 PMS /190/40 HEX 66CC33 By Adrian Gardener Date 9 July 2012.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
Shell Scripting Todd Kelley CST8207 – Todd Kelley1.
PowerShell Class 2 Substituting for Doug Spindler
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Section 6: Using Windows PowerShell to Manage Group Policy Introducing Windows PowerShell Windows PowerShell Library for Group Policy Windows PowerShell-Based.
Linux+ Guide to Linux Certification, Third Edition
Linux Operations and Administration
CMPSC 60: Week 6 Discussion Originally Created By: Jason Wither Updated and Modified By: Ryan Dixon University of California Santa Barbara.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM. 5.1 © Copyright IBM Corporation 2008 Unit 11: Shell.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
Shell Programming. Creating Shell Scripts: Some Basic Principles A script name is arbitrary. Choose names that make it easy to quickly identify file function.
CN1266 Network Scripting V1.2 Kemtis Kunanuraksapong MSIS with Distinction MCTS, MCDST, MCP, A+
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
PowerShell For SharePoint Developers Neil Iversen Inetium
(A Very Short) Introduction to Shell Scripts CSCI N321 – System and Network Administration Copyright © 2000, 2003 by Scott Orr and the Trustees of Indiana.
LIN Unix Lecture 5 Unix Shell Scripts. LIN Command Coordination ; && || command1 ; command2 Interpretation: Do command 1. Then do command.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
1 © 2000 John Urrutia. All rights reserved. Session 5 The Bourne Shell.
Chapter Six Introduction to Shell Script Programming.
Windows PowerShell Introduction 1 Morgan Simonsen Ementor.
Shell Programming Features “Full” programming language “Full” programming language Conditional statements Conditional statements Arithmetic, String, File,
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.
 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.
Linux+ Guide to Linux Certification, Second Edition
Introduction to Bash Shell. What is Shell? The shell is a command interpreter. It is the layer between the operating system kernel and the user.
By Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
Linux Administration Working with the BASH Shell.
Ravikanth C.
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
ULI101 Week 10. Lesson Overview ● Shell Start-up and Configuration Files ● Shell History ● Alias Statement ● Shell Variables ● Introduction to Shell Scripting.
Introduction to PowerShell
Scripts & Functions Scripts and functions are contained in .m-files
Getting Started with the Data ONTAP PowerShell Toolkit
Agenda Control Flow Statements Purpose test statement
Introduction to PowerShell
Cmdlets “Command-lets”
Linux Shell Script Programming
PowerShell Flow of Control Copyright © 2016 – Curt Hill.
Introduction to Bash Programming, part 3
Bash Scripting CS 580U - Fall 2018.
Presentation transcript:

POWERSHELL Dr. Sarah Gothard CEG 233 Spring 2010

Reference Book Suggestion  Windows PowerShell in Action by Bruce Payette (co-designer of the PowerShell language) is available online at ht.edu:2048/ ht.edu:2048/  That same site has about 10 other PowerShell books  Posted examples from Windows PowerShell in Action:   To run a script for the first time, you must open PowerShell in administrator mode (right click on the shortcut and choose “run as Administrator) and type “ set-executionpolicy remotesigned ”.  Unsigned scripts that were downloaded must be individually unblocked in file properties from Windows Explorer.

PowerShell Introduction  object based—everything in PowerShell is an object  built on MS.NET framework  can access any.NET object  output is always a.NET object  many common Linux commands work in PowerShell  full regex support  unless explicitly stated, nothing is case sensitive  PowerShell is technically strongly typed but performs automatic type conversions as needed  scripts are not associated directly with the shell for security

Handy starting commands  Help: man or Get-Help  man *  man about_*  man –detailed  man -full  Command list: gcm or Get-Command  Variable list : gv or Get-Variable  Drive information : gdr or Get-PSDrive  Run a cmd command: cmd /c target_command

Interface Operations  To freeze the screen, highlight any text.  To copy text, highlight it and press enter.  To paste text, right click in the PowerShell window.  Use home and end to go to the beginning and the end of a line, respectively.  Use up and down arrows to navigate command history.  Use pg up to see the first command entered in a session and pg dn to see the last.

Scripting and Command Line  Any PowerShell cmdlet, control statement, operation, etc., can be used both in a script and from the command line.  If a typed command is clearly not finished, PowerShell will begin a new console line after the first. Once the code is complete, hit enter twice to trigger completion.  To type something from the command line that requires an extra line, put a backquote at the end of the first line. Hit enter twice when you are done.

Scalar Variables  $num = 1  $str = "Hi"  $flt = [Math]::Pi  $proc = (get-process)[0]  $date = Get-Date

Provided Variables (part 1) NameDescription $_ The current pipeline object; used in script blocks, filters, the process clause of functions, where-object, foreach-object and switch $^ contains the first token of the last line input into the shell $$ contains the last token of last line input into the shell $? Contains the success/fail status of the last statement $Args Used in creating functions that require parameters $Error If an error occurred, the object is saved in the $error PowerShell variable $foreach Refers to the enumerator in a foreach loop. $HOME The user's home directory; set to %HOMEDRIVE%\%HOMEPATH% $Host Information about the currently executing host $Input Input piped to a function or code block

Provided Variables (part 2) NameDescription $LastExitCode The exit code of the last native application to run $Match A hash table consisting of items found by the –match operator. $MyInvocation Information about the currently script or command-line $true Boolean TRUE $false Boolean FALSE $null A null object $OFS Output Field Separator, used when converting an array to a string. By default, this is set to the space character. $profile Path to a script file that will execute each time PS is opened. $ShellID The identifier for the shell. This value is used by the shell to determine the ExecutionPolicy and what profiles are run at startup. $StackTrace contains detailed stack trace information about the last error

Escape Sequences Escape SequenceDescription `a Alert `` Back quotation `b Backspace `r Carriage return `$ Dollar sign `n Line feed `0 Null `” Quotation mark `’ Single quotation mark `t Tab ` Continue to next line

Math and Time  System.Math  All typical math operations  Use with get-member -static  System.DateTime  Use with get-member -static  Get-Random  Timing a command:  Measure-Command {target command}

Collections  Any variable can be treated like a collection of one.  collections are zero based  Collections are automatically flattened when they are sent down a pipe  To keep collections from being flattened, use a comma before the collection. The unary comma operator instructs PowerShell to wrap the object in a new array that contains that single object. When that array is flattened, we get our original array.

Collection Examples  $nums = 1, 2,  $strs = “Hi”, “Mom”  $flts = [Math]::Pi, [Math]::E  $procs = Get-Process  $files *.sys) forces a collection

Empty Sets  Valid output can consist of an empty set  $null is used to represent an empty set  The foreach statement iterates over a scalar once, even if that scalar happens to be $null.

Aliases  Most PowerShell commands have a shorter alias.  Operations:  List the current aliases: get-alias  Find aliases for a given command: get-alias -def command  Find command for a given alias: get-alias alias  Create an alias: set-alias name target  To load a set of aliases each time, put them in your profile file, whose path is stored in the variable $PROFILE: 1. Create your profile file manually: ni -path $profile -itemtype file -force 2. Open your file: notepad $profile

Files  Get with Get-Item or Get-ChildItem  Call methods on files:  (Get-item books.txt).isReadOnly = $true  (gi books.txt).set_isReadOnly($true)  Create file: ni or New-Item  Remove file: rm or Remove-Item  Check if a file exists: Test-Path  Check if directory:  Get-Item * | where {$_.PSISContainer}

Search  File by name  Get-Item -path path -filter pattern  Get-Childitem -recurse -path path -filter pattern  File contents  Select-String –path path –pattern pattern  Get-Childitem -recurse * | select-string -pattern pattern  Service by name:  Get-Service pattern  Get-Service | Where-Object {$_.Status -eq "Stopped"}  Process by name  Get-Process -Name pattern  Get-Process | Sort-Object cpu | select-object -last 5  Variable by name: Get-Variable -Name pattern

Compare File Contents  diff -referenceobject $(get-content reference file ) -differenceobject $(get- content compare file )  diff -referenceobject $(get-content reference file ) -differenceobject $(get- content compare file ) –includeequal

Midline cmdlets  Midline cmdlets are cmdlets that normally operate on operands that are piped to them.  Examples:  where-object: get-service | Where-Object {$_.Status –eq “Stopped”}  more  foreach  Sort-Object  Select-String  Get-Member

Comparison Operators OperationOperator Equal to -eq Less than -lt Greater than -gt Greater than or equal to -ge Less than or equal to -le Not equal to -ne Not -not, ! And -and Or -or

Text Comparison Operators OperationOperator Like -like Not like -notlike Match -match Not Match -notmatch Replace -replace Equal -eq Not equal -ne Case-sensitive equal -ceq Case-sensitive not equal -cne

Branch Statements if ( condition ) { code block } elseif ( condition ) { code block } else { code block } switch ( expression ) { ( test ) { code block } value { code block } default { code block } }

Loops  do { code block } while ( condition )  while ( condition ) { code block }  do { code block } until ( condition )  for ( init ; condition ; increment ) { code block }  foreach ($ var in $ array ) { code block }  break  continue

Functions  Creation function name { param($param1, $param2) operations }  Invocation function_name arg1 arg2

Function returns  A return statement essentially ends the method. Any function output that wasn’t captured is returned.  To keep from returning more than you intend, throw away unwanted output:  [void]$string.append ($i)  mkdir folder 2> $null  Output from an echo is considered a return value. If you want it to output to the screen instead, use Write-Host.

Parsing Modes  Strings do not need quotes unless they have spaces  & in front forces a string to be executed  A dot in front executes a script  Expression: ()  Subexpression (possibility of multiple semicolon- separated statements): $()  Array

Create Windows Shortcut 1. $wsh = New-Object -ComObject WScript.Shell 2. $link = $wsh.CreateShortcut(“ absolute path to shortcut\shortcut name.lnk”) 3. $link.TargetPath = “ absolute path of file ” 4. $link.Save()

Advanced Topics (see reference book)  Output text colors  Errors and exceptions  Built-in debugging  GUI scripts (several examples in reference book)  Windows system administration: WMI  Security  Provided Windows PowerShell ISE