Click here to load reader

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

  • View
    4

  • Download
    0

Embed Size (px)

Text of Windows Boston Scripting 101 · PDF file Powershell Published 2011 Clyde G. Johnson,...

  • Scripting 101–

    Powershell

    Published 2011

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

    Windows Boston

  • 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

  • Automate repetitive Tasks

     Login Scripts

     UserID Creation

     Inventory Scripts

     Mass file changes

     Data Migrations

  • Types of Admin Scripts

     WMI (inventory)

     ADSI (Manipulating Active Directory)

     File manipulation

     Registry Manipulation

     Remote vs. local

     Software configuration and manipulation

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

  • 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

  • Disabled by default

     Set-ExecutionPolicy RemoteSigned

     Get-Help About_Signing

  • Powershell basics

     Cmdlets

     implement specific functions

     Verb-noun

     Pipelines

     Output of one command is input to another

     Modules

  • 5 Key cmdlets

     Get-Help

     Get-Command

     Get-Member

     Get-Psdrive

     Format-List

  • 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

  • The Pipeline, Illustrated

    11

    Get-Mailbox

    Sort

    Size

    -Descend

    Select

    -First

    100

    Move-Mailbox

    Not the exact syntax –

    but you get the idea!

  • 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)

  • Powershell

     Variables

     Functions

     Branching (if-then-else)

     Loops (while, do for and foreach)

     Structured error/exception handling

  • Variables

     Variables

     Start with $

     Will expand within quotes

     Special Variables

     $args (command line arguments to a function)

     $_ (current object in the pipeline

  • 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

  • PowerShell scripting.

     Command line and Scheduled task

     Powershell.exe c:\dev\script.ps1

     Debug

     PowerShell Integrated Scripting Environment (ISE)

     PowerShell Scriptomatic

  • Powershell (v3)

     490 cmdlets / 55 Modules (4)

     Print management

     DHCP

     Powershell (ISE) has also gotten an upgrade

     Now has intellisense

     Bracketing highlight

     Powershell Workflows?

  • Powershell ISE v3 (beta server 8)

  • Demo Scriptomatic

    Power Shell Scriptomatic

  • Password Sample

     Creating a encrypted password

    Read-Host -assecurestring | ConvertFrom-securestring |

    out-file C:\dev\securestring.txt

  • 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

  • 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);

  • 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”

    }

    }

  • 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“

    }

  •  http://technet.microsoft.com/en-

    us/library/ee692944.aspx

     http://blogs.msdn.com/powershell

     http://thepowershellguy.com

     http://technet.microsoft.com/en-

    us/scriptcenter/dd742419.aspx

     http://morelunches.com/recommended/classroom-kit-

    for-trainers/

    http://technet.microsoft.com/en-us/library/ee692944.aspx http://technet.microsoft.com/en-us/library/ee692944.aspx http://technet.microsoft.com/en-us/library/ee692944.aspx http://blogs.msdn.com/powershell http://thepowershellguy.com/ http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx http://morelunches.com/recommended/classroom-kit-for-trainers/ http://morelunches.com/recommended/classroom-kit-for-trainers/ http://morelunches.com/recommended/classroom-kit-for-trainers/ http://morelunches.com/recommended/classroom-kit-for-trainers/ http://morelunches.com/recommended/classroom-kit-for-trainers/ http://morelunches.com/recommended/classroom-kit-for-trainers/ http://morelunches.com/recommended/classroom-kit-for-trainers/ http://morelunches.com/recommended/classroom-kit-for-trainers/ http://morelunches.com/recommended/classroom-kit-for-trainers/

  • 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

  • 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

  • Files

     Get with Get-Item or Get-ChildItem

     Call methods on files:  (Get-item books.txt).isReadOnly = $true

     (gi books.txt).set_isReadOnly($true)

     Cr

Search related