Top Banner
Scripting 101– Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston
32

Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

May 21, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Scripting 101–

Powershell

Published 2011

Clyde G. Johnson, MCSE,MCSA,MCITP, A+

Windows Boston

Page 2: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Powershell v2

Released August 2009

Part of Windows 7 and Server 2008 R2

Versions are available for download

XP, Server 2003, Vista and Server 2008

32 bit AND 64 bit

NOT enabled by default

Page 3: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Automate repetitive Tasks

Login Scripts

UserID Creation

Inventory Scripts

Mass file changes

Data Migrations

Page 4: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Types of Admin Scripts

WMI (inventory)

ADSI (Manipulating Active Directory)

File manipulation

Registry Manipulation

Remote vs. local

Software configuration and manipulation

Page 5: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Script basics

Modular code

Write it once – use it many times

Comments!

The next person to read your code might be you!!

Header

What the name should be.

Your name and the Date.

Attribution – whom you “borrowed” it from.

Page 6: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Sample

#Serial.ps1

# Gets the serial # of strserver

# Author: Clyde G. Johnson 3-5-2012

# http: somewhere on the web…

$strserver=“.”

Get-WmiObject -ComputerName $strserver -Class

Win32_BIOS | Select-Object SerialNumber

Page 7: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Disabled by default

Set-ExecutionPolicy RemoteSigned

Get-Help About_Signing

Page 8: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Powershell basics

Cmdlets

implement specific functions

Verb-noun

Pipelines

Output of one command is input to another

Modules

Page 9: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

5 Key cmdlets

Get-Help

Get-Command

Get-Member

Get-Psdrive

Format-List

Page 10: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Piping

Connects one command to another

Pass output from command to command

Each command refines the output

Export to CSV, XML or HTML

Pipe to a file or a Printer

Page 11: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

The Pipeline, Illustrated

11

Get-Mailbox

Sort

Size

-Descend

Select

-First

100

Move-Mailbox

Not the exact syntax –

but you get the idea!

Page 12: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Extending powershell with Modules

Get-Module –listavailable

Import-Module name

Get-Command –module name (You must import

the module before running this – why demo

failed)

Page 13: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Powershell

Variables

Functions

Branching (if-then-else)

Loops (while, do for and foreach)

Structured error/exception handling

Page 14: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Variables

Variables

Start with $

Will expand within quotes

Special Variables

$args (command line arguments to a function)

$_ (current object in the pipeline

Page 15: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Branch Statements

if (condition) {code block}

elseif (condition) {code block}

else {code block}

switch (expression)

{

(test) {code block}

value {code block}

default {code block}

}

Page 16: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

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

Page 17: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

PowerShell scripting.

Command line and Scheduled task

Powershell.exe c:\dev\script.ps1

Debug

PowerShell Integrated Scripting Environment (ISE)

PowerShell Scriptomatic

Page 18: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Powershell (v3)

490 cmdlets / 55 Modules (4)

Print management

DHCP

Powershell (ISE) has also gotten an upgrade

Now has intellisense

Bracketing highlight

Powershell Workflows?

Page 19: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Powershell ISE v3 (beta server 8)

Page 20: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Demo Scriptomatic

Power Shell Scriptomatic

Page 21: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Password Sample

Creating a encrypted password

Read-Host -assecurestring | ConvertFrom-securestring |

out-file C:\dev\securestring.txt

Page 22: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Bits-Transfer

Import-Module BitsTransfer

$pass = cat "C:\dev\CopyBits\SecureTransfer.txt" | convertto-

securestring

$mycreds = New-object -typename

System.Management.Automation.PSCredential -argumentlist

“domainname/securetransfer",$pass

Start-BitsTransfer -Source \\10.30.0.224\c$\test\*.* -Destination

C:\Temp\ -transfertype Download -Credential $mycreds

Page 23: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Send an email

$mail = New-Object System.Net.Mail.MailMessage

$mail.From = New-Object

System.Net.Mail.MailAddress(“[email protected]”);

$mail.To.Add(“[email protected]”);

$mail.Subject = “bob’s breakfast”

$mail.Body =“ at one o’clock today”

$smtp = New-Object System.Net.Mail.SmtpClient(“10.30.0.22”);

$smtp.Send($mail);

Page 24: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Event Log Sample

#pulls all event id 901’s in the last hour,

$colItems=Get-Eventlog application -after (get-Date).addHours(-1)|

where {$_.EventId -eq 901}

if($colItems -eq $Null) {} else{

foreach ($item in $colItems){

“Do something”

}

}

Page 25: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Backup all your GPO’s sample

#get domain of local machine

$mydomain = get-ADDomain -current LocalComputer

#pull all the GPO’s in the domain.

$AllGPOs = get-gpo -domain $mydomain.DNSRoot –all

# loop thru them

Foreach ($GPO in $ModGPOs) {

# Backup the GPO to the specified path

$GPOBackup = backup-GPO $GPO.DisplayName -path "C:\GPOBackup“

}

Page 27: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Provided Variables (part 1)

Name Description

$_ 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

Page 28: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Provided Variables (part 2)

Name Description

$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

Page 29: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

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}

Page 30: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

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

Page 31: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

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

Page 32: Windows Boston Scripting 101 Powershell · Powershell Published 2011 Clyde G. Johnson, MCSE,MCSA,MCITP, A+ Windows Boston . Powershell v2 ... Get-Service | Where-Object {$_.Status

Comparison Operators

Operation Operator

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