Você está na página 1de 160

2011 Microsoft Corporation. All rights reserved.

Microsoft Confidential

Conditions and Terms of Use


Microsoft Confidential
This training package is proprietary and confidential, and is intended only for uses described in the training materials. Content and software
is provided to you under a Non-Disclosure Agreement and cannot be distributed. Copying or disclosing all or any portion of the content
and/or software included in such packages is strictly prohibited.
The contents of this package are for informational and training purposes only and are provided "as is" without warranty of any kind,
whether express or implied, including but not limited to the implied warranties of merchantability, fitness for a particular purpose, and noninfringement.
Training package content, including URLs and other Internet Web site references, is subject to change without notice. Because Microsoft
must respond to changing market conditions, the content should not be interpreted to be a commitment on the part of Microsoft, and
Microsoft cannot guarantee the accuracy of any information presented after the date of publication. Unless otherwise noted, the companies,
organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no
association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should
be inferred.

Copyright and Trademarks


2011 Microsoft Corporation. All rights reserved.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this
document. Except as expressly provided in written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this
document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic,
mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
For more information, see Use of Microsoft Copyrighted Content at
http://www.microsoft.com/about/legal/permissions/
Microsoft, Internet Explorer, and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United
States and/or other countries. Other Microsoft products mentioned herein may be either registered trademarks or trademarks of Microsoft
Corporation in the United States and/or other countries. All other trademarks are property of their respective owners.

PowerShell for the IT Administrator


Part 1

Microsoft Confidential

Meet your trainer

Patricio Belardo
Senior Premier Field Engineer
IIS / Dev
pbelardo@microsoft.com

Microsoft Confidential

alias

Introductions
About You:
Name
Company Affiliation
Title/Function/Area of Responsibility
Product experience
Expectations for this Course

Microsoft Confidential

Logistics

Class Hours

Phones

Rest Rooms

Computers

Microsoft Confidential

Workshop Information
Course Material:
Student Lab Manual
Demonstration Scripts
Hands-On Lab Solutions

Delivery Method:
Slides Demonstration Hands-On
C:\pshell\part1\lesson<n>

C:\pshell\part1\lesson<n>\labs

Lab Environment:
SYDDC01

W7Client

Microsoft Confidential

Virtual Lab Environment


https://www.premier-education-services.com/
Login with Microsoft Account
Enter POWERSHELL as Lab ID

Microsoft Confidential

alias

Agenda
Lesson 1 | Introduction
Lesson 2 | Commands
Lesson 3 | Pipeline
Lesson 4 | Providers
Lesson 5 | Variables and Type Fundamentals
Lesson 6 | Scripting
Lesson 7 | Active Directory Administration (ADSI)
Lesson 8 | Active Directory Administration Part 2 (cmdlets)
Lesson 9 | Windows Management Instrumentation
Lesson 10 | Registry, Event Log and ACL Management
Lesson 11 | Remoting
8

Microsoft Confidential

Lesson 1 | Introduction

Microsoft Confidential

Lesson 1 | Introduction
What is PowerShell?

Why?

What?
Interactive Shell

Object-oriented

New Scripting
Language

Consistent Method
of Administration

Revolutionary

10

Microsoft Confidential

Lesson 1 | Introduction
Console & Integrated Scripting Environment (ISE)

11

Lightweight
Quick
Not as user friendly

Used for script development


User friendly
Very extensible

Microsoft Confidential

Lesson 1 | Introduction
Prerequisites and Installation

Middleware

WinRM .Net Framework 3.5

.Net Framework 2

Operating System

XP

2003

Vista

2008

Win7

2008 R2

PowerShell v2 Installed By
Default

12

Microsoft Confidential

Lesson 1 | Introduction
Basic PowerShell Commands | Cmdlets
Cmdlet pronounced Command-let
Smallest unit of functionality
Always of the form Verb-Noun
Parameter names are always passed with - as switch

13

Get-Service name Bits

Get-Help

Set-Location -path c:\windows

Set-Location c:\windows

Microsoft Confidential

Lesson 1 | Introduction
PowerShell Help
Built-In Help
Cmdlet Help:
Get-Help Get-Command Full
Get-Help Get-Command Detailed
Get-Help Get-Command Examples

Concept Help e.g. about topics:


Get-Help about_
Get-Help about_wildcards
Get-Help about_Variables

14

Microsoft Confidential

Lesson 1 | Introduction
PowerShell Command History
Start-Transcript
Create record of PowerShell session in a text file
start-transcript PowerShell_transcript.txt
stop-transcript

Get-History
Returns last 32 commands
Use $MaximumHistoryCount automatic variable to return last 64
Use Invoke-History to re-run a command
get-history
Invoke-history id id#
$MaximumHistoryCount
get-history count $MaximumHistoryCount
15

Microsoft Confidential

Demonstration

Lesson 1 | Introduction
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson1\lesson1-demo.txt

16

Microsoft Confidential

Lab 1 | Introduction (30 minutes)


Scenario

This lab will provide you handson experience with PowerShell


commands.

Goals
Create transcripts of PowerShell
commands
Practice using the top 3 cmdlets
Execute multiple commands in a single
line.

17

Microsoft Confidential

Lesson 2 | Commands

18

Microsoft Confidential

Lesson 2 | Commands
Important Cmdlets

Get-Command

Get-Member

Discovers Cmdlets

Gets all properties and methods


of an object.

Get-Command -Verb set


Get-Service | Get-Member
Get-Command Noun service

Or
$a = Get-Service
$a | Get-Member

Get-Command -Type cmdlet

19

Microsoft Confidential

Lesson 2 | Commands
Objects
An object is a collection of parts and
how to use them

How to use
Methods

Parts
Properties

Pedal

Front Wheel

Brake

Back Wheel

Steer Left

Pedals

Steer Right
Saddle

Wheelie
Frame

20

Microsoft Confidential

Lesson 2 | Commands
Object (Service)

Properties

Methods

Service Name

Start()

Status

Stop()
Pause()

Service
21

Microsoft Confidential

Lesson 2 | Commands
Aliases
A shortened name for a command
Eg dir => get-childitem

Allows you to provide a new term for an existing cmdlet


Get-Help *alias*

Get-Alias

- Shows existing aliases

New-Alias gh Get-Help

- Creates new alias

Lesson 2 | Commands
Object Models
.Net Framework
COM
WMI (Lesson 9)

23

Microsoft Confidential

Lesson 2 | Commands
.Net Framework

PowerShell

VB
.Net

C#

.Net Framework
Object

Object

Object

Object

Operating System
Win32 API

24

Microsoft Confidential

Object

Lesson 2 | Commands
Namespaces & Types
.Net Class Library: Hierarchy of
namespaces

Namespace

Namespace: Collection of Types i.e.


Classes
(template of properties and methods to
create an object)

System.String

Type

Namespace

System.DirectoryServices.DirectoryEntry

Type: The class used to create an


object instance can be said to be the
type of that object.

Type

Example of Type in PowerShell:


[math] or [system.math]
25

Microsoft Confidential

Lesson 2 | Commands
Utilising .Net Framework | Instantiate Object

$webClient = new-object System.Net.WebClient

$webClient | Get-Member

$webClient = new-object System.Net.WebClient


$output = $webClient.DownloadString("http://www.tvguide.co.uk")
if ($output -like "*Top Gear*")
{
"Wahoo Top Gear is on
}

26

Microsoft Confidential

Lesson 2 | Commands
Classes & Objects
Class = Object Template

Object = Instance of a class

5 points
Size
Colour
Orientation

27

Microsoft Confidential

Lesson 2 | Commands
Utilising .Net Framework | Classes and Static Members

A static member can be used without first creating an


instance of the class
Display static members of the math class:
[math] | get-member -static

Example use of a static member of the math class:


(gwmi win32_logicaldisk | ?{$_.drivetype -le 4}) `
| %{[math]::round($_.freespace/1gb,2)}

28

Microsoft Confidential

Lesson 2 | Commands
Utilising .Net Framework | Windows Forms
Not all .net assemblies are
available to PowerShell by
default!

May need to load assemblies


Nasty syntax

[void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms)
$form = new-object Windows.Forms.Form
$form.Text = PowerShell Does Indeed Rock"
$button = new-object Windows.Forms.Button
$button.text=Go On Push Me!"
$button.add_click({$form.close()})
$form.controls.add($button)
$form.Add_Shown({$form.Activate()})
$form.ShowDialog()

Add-Type cmdlet can also be


used to add a type to a PS session
29

Microsoft Confidential

Lesson 2 | Commands
Component Object Model (COM)

HKEY_CLASSES_ROOT

Lists all installed


COM components

30

Microsoft Confidential

Lesson 2 | Commands
Component Object Model (COM) | Instantiate Object

Get-Help New-Object -det

-ComObject parameter to
differentiate from .Net Object

$wn = new-object -com wscript.network


$wn.userdomain

$ws = new-object -com wscript.shell


$ws.popup(Hello World)

$s = new-object -com SAPI.SpVoice


$s.rate = -10
$s.speak(Too much pop makes you drunk)

31

Microsoft Confidential

Demonstration

Lesson 2 | Commands
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson2\lesson2-demo.txt

32

Microsoft Confidential

Lab 2 | Commands (30 minutes)


Scenario

This lab will provide you handson experience with PowerShell


commands.

Goals
Work with Cmdlets
Work with New Object

33

Microsoft Confidential

Lesson 3 | Pipeline

34

Microsoft Confidential

Lesson 3 | Pipeline
Introduction

| pipes (or sends) output from left to a command on


the right
Passes an object not text
Can be used for filtering, formatting, outputting and
many other things
Can use multiple pipes on one line

Get-Service

where-object {$_.Status -eq "Stopped"}

Objects
35

Current Object On Pipeline


(the pipeline variable)
Microsoft Confidential

Objects

Format-List

Lesson 3 | Pipeline
Operators
Arithmetic
Assignment
Comparison
Logical
Redirection
Split/Join
Type
Unary
Special

36

Microsoft Confidential

Lesson 3 | Pipeline
Comparison Operators
Compare values (such as text or numbers)
Test conditions (with where-object)
Case-insensitive by default (precede with c to make casesensitive)
13 Comparison operators:
-eq

-ne

-gt

-ge

-lt

-le

-like

-notlike

-match

-notmatch

-contains

-notcontains

-replace

Examples:
PowerShell eq powershell

37

Microsoft Confidential

4 gt 4

Lesson 3 | Pipeline
Logical Operators
Join multiple operations
Check for compound conditions
True/False
5 logical and 4 bitwise operators:
-and

-or

-not

-xor

-band

-bor

-bxor

-bnot

Examples:
(4 ge 8) and (5 lt 10)

38

Microsoft Confidential

! (4 eq 4)

Lesson 3 | Pipeline
Filtering, Sorting, and Grouping data | Display
PS only sends the most pertinent data to the console
Select-Object, Format-List and Format-Table cmdlets allow
control over the properties displayed:
Get-ChildItem | Select-Object property Name, Length, LastWriteTime
gci | Select Name, @{Name=Size(MB);Expression={[Math]::Round($_.Length/1MB, 2)}}

Get-Process | Format-List -Property ID, Name


Get-Process | FL *

Get-Service | FT Property Name, Status AutoSize -Wrap

39

Microsoft Confidential

Lesson 3 | Pipeline
Filtering, Sorting, and Grouping data | Filtering
Where-Object can be used to filter results:
Get-Process | Where-Object { $_.WS -gt 50MB }
Get-Process | Where { $_.Name -eq notepad }
Get-Process | ? { $_.Threads.Count -gt 25 }

40

Microsoft Confidential

Lesson 3 | Pipeline
Filtering, Sorting, and Grouping data | Sort and Group
Sort-Object can be used to sort objects by a specified
property:
Get-Process | Sort-Object -Property WS

Position in pipeline is important!


Get-Process | Sort WS | Select -First 10
Get-Process | Select -First 10 | Sort WS

Group-Object can be used to group values based on


specified properties:
get-eventlog -logname system -newest 1000 | group -property entrytype

41

Microsoft Confidential

Lesson 3 | Pipeline
Input and Output | Text File
Text file input to pipeline
Text file output from pipeline
Key cmdlets:
Get-Content
Set-Content
Add-Content
Get-Process | Set-Content c:\test\processes.txt
winlogon, dnscache | Add-Content c:\test\services.txt
Get-Content c:\test\services.txt | Get-Service

42

Microsoft Confidential

Lesson 3 | Pipeline
Input and Output | CSV Files
CSV file input to pipeline
CSV file output from pipeline
Key cmdlets:
Import-CSV
Export-CSV

Import-CSV c:\test\famous.csv | Sort Surname | Select GivenName


Get-Process | Export-CSV c:\test\processinfo.csv

43

Microsoft Confidential

Demonstration

Lesson 3 | Pipeline
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson3\lesson3-demo.txt

44

Microsoft Confidential

Lab 3 | Pipeline (30 minutes)


Scenario

This lab will provide you handson experience with the


PowerShell pipeline.

Goals
Work with PowerShell Operators
Work with PowerShell Pipeline
Filter and sort with the Pipeline

45

Microsoft Confidential

Lesson 4 | Providers

46

Microsoft Confidential

Lesson 4 | Providers
Overview
Default Providers:
Alias, Environment, FileSystem, Function, Registry, Variable, Certificate, WSMan

Consistent Data Store Interaction


Same Cmdlets: New-Item, Remove-Item, Get-Item, Set-Item
Single (items, e.g. Alias) & Multiple (containers & items, e.g. FileSystem)
Level Providers
Consider As Drives e.g. C:, Cert:, Function:, etc.

47

Microsoft Confidential

Lesson 4 | Providers
Cmdlets
Get-Help about_providers

Get help

Get-PSProvider

List installed providers

Get-PSDrive

List PowerShell Drive

Set-Location HKLM:

Connect to provider

Create New PSDrive:


new-psdrive name HKCR psprovider registry root HKEY_CLASSES_ROOT

48

Microsoft Confidential

Demonstration

Lesson 4 | Providers
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson4\lesson4-demo.txt

49

Microsoft Confidential

Lab 4 | Providers (30 minutes)


Scenario

This lab will provide you handson experience with PowerShell


providers.

Goals
Work with Environment Provider
Work with Certificate Provider
Work with Registry Provider

50

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals

51

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Variables
A way of storing dynamic data
All variables begin with $
Holds object or collection of objects (array or hash table)
$MyNum = 32

$Netlogon = get-service name netlogon

52

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Variables
Use Here-String to assign multi-line string values to a
variable:
$MultiLine = @
"Curiouser and curiouser!"
cried Alice (she was so much
surprised, that for the
"@

PowerShell Constants
Variable whose value cannot be changed once defined
Write protected variable
Set-Variable name Pi value 3.142 option constant
53

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Variables | Types
Type defines the kind of values stored in a variable
(e.g. integer, double, array, Boolean, string, etc.)
Use GetType() method to check type
By default variables are weakly typed
(allowed to hold different type of objects at different times)
Can be strong typed
[int]$MyNum = 32
$MyNum.GetType()

IsPublic IsSerial Name


-------- -------- ---True
True
Int32
54

BaseType
-------System.ValueType

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Automatic Variables
Predefined variables
Get-Help about_Automatic_Variables

Examples (use help for full list):


$Args

Stores values of parameters passed to a function

$Error

Stores information about the error object when an error has


occurred during any script execution

$PsHome Home directory where PowerShell is installed

55

$Home

Home directory of the user

$True

Check for Boolean Value of True

$False

Check for Boolean Value of False


Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Strings & Spaces
String
Expandable double quotes
$a = Hello World!
$b = $a
$b

Hello World!

Literals single quote


$a = Hello World!
$b = $a
$b

56

$a

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Arrays
Data structure that holds a collection of objects
Each object is in its own compartment

Object 1

57

Object 2

Object 3

Microsoft Confidential

Object 4

Object 5

Lesson 5 | Variables and Type Fundamentals


Arrays
Create empty array:
$arr1 = @()

Automatically created arrays:


$arr2 = a,b,c

$arrProcesses = Get-Process

Count elements in array:


$arr2.count

Tip: Useful with iteration statements. Ex:


for ($a=0;$a -le $arr2.count-1;$a++)
{$arr2[$a]}

Add element to array, and assign a value:


$arr2 += d

58

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Arrays | Access Elements
Access array compartments using []
$arrProcesses = Get-Process

Object 1

Object 2

Object 3

Object 4

Object 5

Zero-based
(Index 0)

$arrProcesses[0].name

$arrProcesses[4].name

Index Numbers
$arrProcesses[0]

Value of the 1st element

$arrProcesses[-1]

Value of the last element in array

Lesson 5 | Variables and Type Fundamentals


Arrays
One-dimensional array:
$arrProcesses = Get-Process
$arrProcesses[0]
Index 0

Index 1

Index 2

Index 3

Index 4

Multi-dimensional array:
$rows = 2
$cols = 2
$arrDim = New-Object 'object[,]' $rows,$cols
$arrDim[0,0]
Index 0,0
Index 1,0
60

Index 0,1
Index 1,1
Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Hash Tables
Kind of array
Key-Value pair
Dictionary array form
Can access value using a corresponding label

61

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Hash Table
Create empty hash table:
$hash1 = @{}

Create and populate hash table:


$hash2 = @{"Type1"="Desktop";"Type2"="Server"}

Add element to hash table:


$hash2[Type3] = Laptop

62

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Hash Table | Access Elements
Consider following hash table
$hash2 = @{"Type1"="Desktop";"Type2"="Server"}

Use dot notation to find the value of Type 1:


$hash2.type1

63

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Working with Console Input-Output

Writing to Console
Write-Host $a foregroundcolor green

Use either variable name or


Write-Host

or
$a

Reading From Console


Use Read-Host to assign to
variable

64

$name = Read-Host Enter your name


Write-Host "Hello $name

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Working with Console Input-Output
Additional output options:
Out-File

Sends output to a file

Out-Printer

Sends output to a printer

Out-Host

Default output window

Out-GridView

Out-GridView Display output in a Grid view

65

Write-Host

Writes customized output to a host

Write-Output

Sends specified objects to next command in pipeline

Tee-Object

Saves command output in a file or variable, and displays it in


the console

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Working with Files
Check if file exists:
$Fileinfo = Test-Path C:\Windows\System32\drivers\ntfs.sys
if ($Fileinfo -eq "True") {Write-Host "File Exists"}

Copying files:
Copy-Item C:\setup.log d:\

Moving files:
Move-Item C:\setup.log d:\

Use Rename-Item and Delete-Item to rename or delete


files
Also works on directories

66

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


Error Automatic Variables

Error recording variable:

Global setting: $Error


$Error stores last 256 errors
Per cmdlet: -ErrorVariable

Error handling variables:

Global setting: $ErrorActionPreference


Per cmdlet:-ErrorAction

Execution status:

Last command run: $?

Applies to last command


Boolean (true = success, false = failure)

Exit Code: $LastExitCode

Applies to external command or script


0 = success, anything else = failure

67

Microsoft Confidential

Lesson 5 | Variables and Type Fundamentals


ErrorActionPreference Variable
SilentlyContinue
Continue
(default)
Stop

Inquire

68

Do not display messages on host


Continue processing following elements

Display message on host


Continue processing following elements

Display message on host


Stop all processing

Display message on host


Prompt user if processing should continue

Microsoft Confidential

Demonstration

Lesson 5 | Variables and Type


Fundamentals
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson5\lesson5-demo.txt
69

Microsoft Confidential

Lab 5 | Variables and Type Fundamentals


(30 minutes)
Scenario

This lab will provide you handson experience with PowerShell


variables and type fundamentals.

Goals
To use different types of variables for
various operations
To create, modify and understand use of an
array
To create, modify and understand use of a
hash table

70

Microsoft Confidential

Lesson 6 | Scripting

71

Microsoft Confidential

Lesson 6 | Scripting
Security | Execution Policy | Settings

Restricted

Scripts cannot be run


PowerShell interactive-mode only
Default Setting

All Signed

Runs a script only if signed


Signature must be trusted on local machine
(i.e. cert on local machine must sign script)

Remote
Signed
Unrestricted
72

Runs all local scripts


Scripts downloaded from IE, Outlook Express &
Messenger must be signed by trusted source
(i.e. cert on local machine must sign script)
Recommended Minimum

All scripts from all sources can be run without


signing

Microsoft Confidential

Lesson 6 | Scripting
Security | Execution Policy | Scope

Process

Affects current session only


Stored in $PSExecutionPolicyPreference
Lost upon exit of session (i.e. host process)

CurrentUser

Affects current user only


Stored in HKCU registry subkey

LocalMachine

Affects all users on computer


Stored in HKLM registry subkey

set-executionpolicy -scope CurrentUser -executionPolicy Unrestricted

73

Microsoft Confidential

Lesson 6 | Scripting
Security | Execution Policy | Cmdlets
Get-Help about_execution_policies
Get-ExecutionPolicy

Get-ExecutionPolicy -list

Scope
----MachinePolicy
UserPolicy
Process
CurrentUser
LocalMachine

Current policy
All policies in precedence order

ExecutionPolicy
--------------Undefined
Undefined
Undefined
RemoteSigned
AllSigned

Set-ExecutionPolicy remotesigned

74

Get help

Group Policy
Effective Execution Policy

Set Policy

Microsoft Confidential

Requires Elevated
PowerShell Session

Lesson 6 | Scripting
Security | Execution Policy | Remote Signed
API

.ps1

To run an unsigned script:

1. Save the script file on your computer.


2. Click Start, click My Computer, and

Zone Identifier

locate the saved script file.


3. Right-click the script file, and then click
Properties.
4. Click Unblock.
NTFS

75

Microsoft Confidential

Lesson 6 | Scripting
Security | Execution Policy | All Signed | Script Signing
Requires self-signed
or CA cert on
machine

Get-Help about_signing

Set-AuthenticodeSignature .\test.ps1 $cert

$Cert

Test.ps1
Get-Service
76

Test.ps1
Get-Service
# SIG # Begin signature block
# MIIEMwYJKoZIhvcNAQcCoIIEJDC
# gjcCAQSgWzBZMDQGCisGAQQBgj
Microsoft Confidential

Lesson 6 | Scripting
Running Scripts
Script file extension is .ps1
Cannot execute with double click
Use .\ when script is in current directory:
.\script.ps1

Or use full path and file name:


c:\scripts\script.ps1

Or use ampersand and quotes if path/file name contain


spaces:
& c:\my scripts\script.ps1

Or use just filename if script is in environment path:


Script.ps1
77

$env:path=$envpath+;c:\scripts
Microsoft Confidential

Lesson 6 | Scripting
Running Scripts
Command line to execute script:
powershell.exe noexit file c:\myscript.ps1

Ensure remote execution policy allows local script


execution:
Set-Executionpolicy remotesigned

(Or use ExecutionPolicy Bypass)

78

Microsoft Confidential

Lesson 6 | Scripting
PowerShell Comments
Requires comment:
#requires version 2

Single line comment:


#

Delimited comment:
<#
Author:
Date:
#>
79

Microsoft Confidential

Lesson 6 | Scripting
Statement Termination
Newline character:
Carriage return character (U+000D)
Line feed character (U+000A)
Carriage return character (U+000D) followed by line feed character
(U+000A)

Semi-colon
;

80

Microsoft Confidential

Lesson 6 | Scripting
Iteration Statements (Loops)

Do While

$a=1
do
{write-host Loop:$a}
while ($a++ -le 5)

While
$a=1
While ($a lt 10)
{$a; $a++}

Do Until
$a=1
Do {$a; $a++}
Until ($a gt 10)

For
For ($a=1; $a lt 10; $a++)
{$a}

For Each
Foreach ($i in Get-Childitem c:\windows)
{$i.name}
81

Microsoft Confidential

Lesson 6 | Scripting
Flow Control Statements
Break
Use to exit loop
$counter=0; while ($true)
{if ($counter++ -ge 3) {break} $counter}

Continue
Use to continue a loop (i.e. print $i when divisible by 2)
foreach ($i in 1..10) {If ($i % 2) {Continue} $i}

Return
Return control back to caller of script/function
Optionally return output to console

Exit
Exit current script or shell session
82

Microsoft Confidential

Lesson 6 | Scripting
Other Statements

If Statement

Switch Statement

$a = "white"
if ($a -eq "red")
{"The colour is red"}
Elseif ($a -eq "white")
{"The colour is white"}
else
{"Another colour"}

Labeled
Statements

83

$a = "red"
switch ($a)
{
"red" {"The colour is red"}
"white"{"The colour is white"}
default{"Another colour"}
}

:outer while ($true)


{:inner while ($true)
{Get-Date -displayhint time
break outer}
Get-Date displayhint date}
Microsoft Confidential

Lesson 6 | Scripting
Functions
Reusable piece of code
Parameters (separated by spaces) can be passed in
Functions must be defined before they are called
function sum ([int]$a,[int]$b)
{
return $a + $b
}
sum 4 5

84

Microsoft Confidential

Lesson 6 | Scripting
Scripts | Command Line Arguments
Positional Parameters
$Args
Passed to script with spaces
.\myscript.ps1 server1 benp

Accessed in script by $args array


$servername = $args[0]
$username = $args[1]

Named Parameters
Passed to script with parameter name
.\myscript.ps1 -server srv1 user benp

User parameter name directly in script


Param($server, $user)
Write-Host $server
Write-Host $user

85

Microsoft Confidential

Lesson 6 | Scripting
Profiles
Start
PowerShell
Execute Profile
Scripts
Profile 1

Profile 2
Profile 3
PS:/>

86

Microsoft Confidential

Lesson 6 | Scripting
Profile Locations
PowerShell Console
Scope

Name

Current User, Current Host

$Profile or
$Profile.CurrentUserCurrentHost

Current User, All Hosts

$Profile.CurrentUserAllHosts

All Users, Current Host

$Profile.AllUsersCurrentHost

All Users, All Hosts

$Profile.AllUsersAllHosts

Integrated Scripting Environment

87

Scope

Name

Current User, Current Host

$Home\Documents\WindowsPowerShell\Microsoft.PowerS
hellISE_profile.ps1

All Users, Current Host

$PsHome\Microsoft.PowerShellISE_profile.ps1

Microsoft Confidential

Lesson 6 | Scripting
Dot Sourcing & Script Libraries
Use dot sourcing to make items from script library available
in current scope
Without dot sourcing:
Code in scripts are restricted to script scope
Thus, Code will only be available in the script itself, and not from
the console or other scopes

How to dot source a script:


<Dot space> .\script.ps1
. .\script.ps1

<Dot space> c:\scripts\script.ps1


. C:\scripts\script.ps1

Place dot sourced scripts in Profile


Code will be available to all child scopes in PowerShell host
88

Microsoft Confidential

Demonstration

Lesson 6 | Scripting
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson6\lesson6-demo.txt
89

Microsoft Confidential

Lab 6 | Scripting (30 minutes)


Scenario

This lab will provide you handson experience with PowerShell


Scripting.

Goals
Create PowerShell scripts
Create Functions in scripts
Create PowerShell Profiles

90

Microsoft Confidential

Lesson 7 | Active Directory Administration (ADSI)

91

Microsoft Confidential

Lesson 7 | AD (ADSI)
DirectoryEntry Class
[System.DirectoryServices.DirectoryEntry] or simply [ADSI]
.put()
.get()

.create()
.delete()

Directory Entry .setinfo()


(.Net Type)
.putex()

.set()
.setex()

$user | Get-Member

92

$user.psbase | Get-Member

Microsoft Confidential

Lesson 7 | AD (ADSI)
Binding To AD
ADSI Type Accelerator:
$domain = [ADSI]LDAP://DC=contoso,DC=com

Or (from domain member):


$domain = [ADSI]

Alternate credentials:
$domain = New-Object ADSI(LDAP://DC=contoso,DC=com,
CONTOSO\Administrator,Password123)

Note: It is not good practice to embed passwords in scripts.


93

Microsoft Confidential

Lesson 7 | AD (ADSI)
Binding To DC/GC
Bind to DC (DNS name, NetBIOS name or IP address):
[ADSI]LDAP://DC01/DC=contoso,DC=com

Bind to nearest GC:


[ADSI]GC://DC=contoso,DC=com

Bind to specific GC:


[ADSI]GC://GC01/DC=contoso,DC=com

94

Microsoft Confidential

Lesson 7 | AD (ADSI)
Directory Searcher
Bind to AD:
$domain = [ADSI]LDAP://DC=contoso,DC=com

Create searcher object instance:


$dirSearch = [ADSISEARCHER]$domain

Use FindAll() method to search:


$dirSearch.FindAll()

Set search filter:

All objects in
domain

All user
objects

$dirSearch.Filter = (objectCategory=user)

Windows
Server
computer
objects

(&(objectCategory=computer)(operatingSystem=Windows Server*))
95

Microsoft Confidential

Lesson 7 | AD (ADSI)
Organizational Unit Management

96

Create
OU

$objRoot = [ADSI]LDAP://DC=contoso,DC=com
$objOU = $objRoot.Create(organizationalunit,OU=Finance)
$objOU.SetInfo()

Modify
OU

$objFinOU=[ADSI]LDAP://OU=Finance,DC=contoso,DC=com
$objFinOU.Put("Description", "Test OU")
$objFinOU.SetInfo()

Delete
OU

$objRoot = [ADSI]LDAP://DC=contoso,DC=com
$objOU = $objRoot.Delete(organizationalunit,OU=Finance)

Microsoft Confidential

Lesson 7 | AD (ADSI)
User Management
Create
User

$objOU = [ADSI]LDAP://OU=Finance,DC=contoso,DC=com
$objUser = $objOU.Create(user,CN=FinanceUser01)
$objUser.SetInfo()

Enable
User

$objUser=[ADSI]LDAP://CN=FinanceUser01,OU=Finance,DC=contoso,DC=com
$objUser.SetPassword(P@ssword1)
$objUser.AccountDisabled = $false
$objUser.Setinfo()

Modify
User

$objUser=[ADSI]LDAP://CN=FinanceUser01,OU=Finance,DC=contoso,DC=com
$objUser.Put(samaccountname,FinanceUser01)
$objUser.SetInfo()

Delete
User

$objOU = [ADSI]LDAP://OU=Finance,DC=contoso,DC=com
$objOU.Delete('User', 'CN=FinanceUser01')

97

Microsoft Confidential

Demonstration

Lesson 7 | AD (ADSI)
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson7\lesson7-demo.txt
98

Microsoft Confidential

Lab 7 | AD (ADSI) (30 minutes)


Scenario

This lab will provide you handson experience administering


Active Directory using
PowerShell and ADSI.
Goals

Create Multiple AD Users

99

Microsoft Confidential

Lesson 8 | Active Directory Administration


(cmdlets)

100

Microsoft Confidential

Lesson 8 | AD (cmdlets)
AD Module | Overview
AD PowerShell Module named ActiveDirectory
Self-contained package
Consolidates a group of cmdlets
Cmdlets used to manage one or multiple AD forests and
domains

101

Microsoft Confidential

Lesson 8 | AD (cmdlets)
AD Module | Purpose
Account
User
Computer

Group
OU
Password Policy
Default domain password policy
Fine-grained password policy

Forest & Domain


DC & FSMO
Optional Features
102

Microsoft Confidential

Lesson 8 | AD (cmdlets)
Cmdlets

103

Microsoft Confidential

Lesson 8 | AD (cmdlets)
AD Module Prerequisites
At least one 2008 R2 DC in the targeted domain
OR
A 2003 or 2008 DC running the Active Directory
Management Gateway Service
Client: Windows 7 or Windows Server 2008 R2
Windows 7: Remote Server Administration Tools + AD Module
Feature
Windows 2008 R2: AD Module via Add Features Wizard

Import and use the AD module in a PowerShell session via


the Import-Module cmdlet
104

Microsoft Confidential

Lesson 8 | AD (cmdlets)
Active Directory Web Services

ADWS
Windows 7
RSAT
AD Module

Windows 2008 R2

105

Microsoft Confidential

Lesson 8 | AD (cmdlets)
AD Management Gateway Service

Updates
.Net 3.5 SP1

AD DS
Windows 7
RSAT
AD Module

Windows 2008
Windows 2003 SP2
Windows 2003 R2 SP2

106

Microsoft Confidential

Lesson 8 | AD (cmdlets)
Connecting To AD
Binding to AD DN is required to work with AD objects
Cmdlets connect to local domain using current user
credentials by default
All 76 cmdlets have credential & server parameters
To target other domains & specific servers

Global Catalog connection possible using Port #


Get-ADUser filter * -server contoso.com:3268

TIP:

107

Do not hardcode DC names in scripts!


(Use Domain FQDN to discover DC)

Microsoft Confidential

Lesson 8 | AD (cmdlets)
Connection Reuse (New-PSDrive)
Create PSDrive for frequently managed other domains
Saves time, avoids tedious re-entering of credentials
Increases risk

AD cmdlets inherit credentials & search base from new


PSDrive
Set search base to desired path of new PSDrive
$cred = Get-Credential
New-PSDrive -PSProvider ActiveDirectory -Name Contoso -Root ""
Server contoso.com credential $cred
Set-location Contoso:
PS Contoso:\> Set-Location 'Contoso:\cn=users,dc=contoso,dc=com'
PS Contoso:\cn=users,dc=contoso,dc=com>
108

Microsoft Confidential

Lesson 8 | AD (cmdlets)
AD Provider
AD Provider is available once AD Module is imported:
Get-PSProvider

Name
-------ActiveDirectory

Capabilities
---------------Include...

Drives
-------{AD}

Use common Provider cmdlets to manage AD drive:


Set-location ad:

109

dir | ft pschildname
cd "DC=contoso,DC=com
dir | ft pschildname
md OU=Test
cd OU=Test
Microsoft Confidential

Lesson 8 | AD (cmdlets)
User Account Management | AD Cmdlets
Create User

Enumerate
User
Modify User

New-ADUser name benp -SamAccountName benp"


-GivenName ben" -Surname Pearce"
-DisplayName Ben Pearce"

Get-ADUser -Filter * -Properties *


Get-ADUser -Filter * `
-Properties *,msDS-ReplAttributeMetaData

Set-ADUser -Identity benp" Title Engineer"

Target Single AD Object Only!

Delete User

110

Remove-ADUser benp

Microsoft Confidential

Lesson 8 | AD (cmdlets)
Computer Account Management | AD Cmdlets

Computer
Information

Find Stale
Computer
Accounts

111

Get-ADComputer -Filter * `
-property name,OperatingSystem,`
OperatingSystemServicePack,OperatingSystemVersion `
| Out-GridView

$OneYearAgo = (Get-Date).AddYears(-1)
Get-ADComputer -Filter {LastLogonTimeStamp lt`
$OneYearAgo} | Disable-ADAccount

Microsoft Confidential

Lesson 8 | AD (cmdlets)
Group Management | AD Cmdlets
Enumerate
Group
Create
Group

Populate
Group

112

Nested group
membership
Get-ADGroupMember IT -Recursive

New-ADGroup name Sales `


-Path OU=Groups,DC=Contoso,DC=com `
-GroupScope Global `
-GroupCategory Security

To return group
object

$newGroup = New-ADGroup -name "IT" `


-Path "OU=Groups,DC=Contoso,DC=com" `
-GroupScope "Global" passthru
$ITUsers = Get-ADUser -filter {Department -eq "IT"}
Add-ADGroupMember -Identity $newGroup -Members $ITUsers
OR
$ITUsers | Add-ADPrincipalGroupMembership -MemberOf "IT"
Microsoft Confidential

Lesson 8 | AD (cmdlets)
Group Management (continued) | AD Cmdlets

Remove
From Group
TIP:

$ITUsers | Remove-ADPrincipalGroupMembership `
-MemberOf "IT
OR
Remove-ADGroupMember -Identity "IT" -members $ITUsers

There will be a prompt to confirm.


Consider setting $ConfirmPreference
automatic variable in scripts.

$OrignalConfirmPreference = $ConfirmPreference
$ConfirmPreference = "none"
Remove-ADGroupMember -Identity "IT" -members $itusers
$ConfirmPreference = $OrignalConfirmPreference

113

Microsoft Confidential

Lesson 8 | AD (cmdlets)
Multi-Valued Attributes | AD Cmdlets
Example:
OtherTelephone

Multi-valued attribute can contain a single or multiple


values
Each value must be unique
Use Hash Table (Key/Value pair) i.e. @{}

User
Telephone
Numbers
114

New-ADUser `
-Path "ou=sales,ou=departments,dc=contoso,dc=com" `
-name "Sales1" -SamAccountName "Sales1" `
-UsePrincipalName "Sales1@contoso.com" `
-department "sales" `
-OtherAttributes `
@{otherTelephone="555-555-5555","123-456-7890"}
Microsoft Confidential

Demonstration

Lesson 8 | AD (cmdlets)
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson8\lesson8-demo.txt
115

Microsoft Confidential

Lab 8 | AD (cmdlets) (30 minutes)


Scenario

This lab will provide you handson experience with the AD


Module.

Goals
Create Users
Modify AD Objects
Search AD

116

Microsoft Confidential

Lesson 9 | Windows Management


Instrumentation

117

Microsoft Confidential

Lesson 9 | WMI
WMI in Microsoft Windows

PowerShell

Class

Class
Class

Class

Class

Virtualization
Namespace

CIMV2
Namespace
118

Class

Microsoft Confidential

Lesson 9 | WMI
WMI & Remote Machines | Requirements
PowerShell Admin

119

Remote Machine

PowerShell
Get-WMIObject

WMI Service

DCOM

DCOM

RPC

RPC

TCP/IP

TCP/IP

Microsoft Confidential

No PS required!

Other:
DNS
Permission

Lesson 9 | WMI
Useful Cmdlets
Get-WmiObject

Display WMI namespace & class info


Instantiate WMI class
Example: Use Win32_Service class to display service info

Remove-WmiObject

Delete instance of WMI class

Set-WmiInstance

Creates or updates instance of existing WMI class


Example: Set WMI logging level

Get-WSManInstance

Displays management information for resource instance


Example: Display WinRM listener configuration

Invoke-WmiMethod

Call WMI methods


Allows calling method on instance of class or on the class itself i.e. static
methods
Example: Use Win32_Process create method to launch notepad

120

Microsoft Confidential

Lesson 9 | WMI
Get-WmiObject | Cmdlet
Aliases
gwmi

Key Parameters
-namespace, -class, -list, -computername
List Namespaces
Gwmi -Namespace "root" -Class "__NAMESPACE" | Select Name
List Classes (root\cimv2 namespace)

Gwmi -Namespace "root\cimv2" -List | Select Name

121

Microsoft Confidential

Lesson 9 | WMI
Instantiate WMI Object
$bios = Gwmi namespace root\cimv2 class Win32_Bios
$bios | gm

Properties
BIOSVersion
InstallDate

$bios.BIOSVersion
122

Microsoft Confidential

Lesson 9 | WMI
WMI & Remote Machines | Get-WmiObject Cmdlet
Key Parameters
-computername, -credential
-ComputerName
Gwmi win32_bios computername w7client,syddc01,sydsql01
OR
Gwmi win32_bios computername (Get-Content .\servers.txt)

-Credential
$creds=Get-Credential
Gwmi win32_bios computername w7client,syddc01 credential $creds

123

Microsoft Confidential

Demonstration

Lesson 9 | WMI
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson9\lesson9-demo.txt
124

Microsoft Confidential

Lab 9 | WMI (1 hour)


Scenario

This lab will provide you handson experience with WMI.

Goals
WMI Classes & Queries
Basic filtering
WMI Method Execution

125

Microsoft Confidential

Lesson 10 | Registry, Event Log and ACL


Management

126

Microsoft Confidential

Lesson 10 | Registry, Event Log and ACL Management


Registry Classes

Microsoft.Win32.RegistryHive
Retrieve root registry keys

Microsoft.Win32.Registry
Static class members
[Microsoft.Win32.Registry] | gm -static
LocalMachine property:
[Microsoft.Win32.Registry]::localmachine
CurrentUser Property
[Microsoft.Win32.Registry]::currentuser

Instance class members:


$regHKLM = [Microsoft.Win32.Registry]::localmachine
$regHKLM | gm
$regHKLM.GetSubKeyNames()
$regkey=$regHKLM.OpenSubKey("SOFTWARE\Microsoft\Windows\Cur
rentVersion\Run")
127

Microsoft Confidential

Lesson 10 | Registry, Event Log and ACL Management


Registry Classes | Return Root Keys

[enum]::GetValues(Microsoft.Win32.RegistryHive)

ClassesRoot
CurrentUser
LocalMachine
Users
PerformanceData
CurrentConfig
DynData

128

Microsoft Confidential

Lesson 10 | Registry, Event Log and ACL Management


Registry Classes | Identify Static Members
[Microsoft.Win32.Registry] | Get-Member static

Properties

Methods

ClassesRoot

GetValue

CurrentUser

SetValue

LocalMachine

129

Microsoft Confidential

Lesson 10 | Registry, Event Log and ACL Management


Registry Classes | Identify Instance Members
[Microsoft.Win32.Registry]::localmachine | Get-Member

Properties

Methods

Name

GetSubKeyNames

SubKeyCount

GetValueNames

ValueCount

GetValue
OpenSubKey

130

Microsoft Confidential

Lesson 10 | Registry, Event Log and ACL Management


Registry Classes | Static and Instance Members

$regHKLM = [Microsoft.Win32.Registry]::localmachine
$regHKLM.GetSubKeyNames()

BCD00000000
COMPONENTS
HARDWARE
SAM
SECURITY
SOFTWARE
SYSTEM

131

Microsoft Confidential

Lesson 10 | Registry, Event Log and ACL Management


Event Logs | Two Cmdlets

Get-WinEvent
New and legacy event log formats
-ComputerName
Limited to reading from event logs

Get-EventLog
Legacy event log formats (2003, XP)
-ComputerName
*EventLog cmdlets for new event logs, etc
New-EventLog -LogName MyEventLog -Source MySource Computername SYDDC01

Write-EventLog -LogName MyEventLog -Source MySource -EntryType Warning `


-Category 2 -EventId 3 -Message "New Event from MySource" `
Computername SYDDC01
132

Microsoft Confidential

Lesson 10 | Registry, Event Log and ACL Management


Files, Folders & Shares | System IO Namespace

System.IO.FileAttributes
Retrieve file & folder attributes

System.IO.FileSystemInfo
Create instance of type to set attributes using instance members

133

Microsoft Confidential

Lesson 10 | Registry, Event Log and ACL Management


Files, Folders & Shares | Set File Attributes
$myfile = Get-Item c:\PShell\lesson7\debug.txt
$myfile.GetType()

System.IO.FileSystemInfo
$myfile | Format-List name,attributes

Name
: debug.txt
Attributes : Archive
$myfile.attributes = archive,readonly,hidden
$myfile | Format-List name,attributes

Name
: debug.txt
Attributes : ReadOnly, Hidden, Archive
134

Microsoft Confidential

Lesson 10 | Registry, Event Log and ACL Management


Files, Folders & Shares | Reading File & Folder Permissions
(Get-ACL c:\PShell\lesson7\debug.txt).access | fl *

FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference :
BUILTIN\Administrators
IsInherited
: True
InheritanceFlags : None
PropagationFlags : None
FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : NT
AUTHORITY\SYSTEM
IsInherited
: True
InheritanceFlags : None
PropagationFlags : None

135

Microsoft Confidential

Lesson 10 | Registry, Event Log and ACL Management


Files, Folders & Shares | Reading Share Permissions
(Get-ACL \\localhost\c$).access | Format-List *

FileSystemRights : 268435456
AccessControlType : Allow
IdentityReference : NT AUTHORITY\SYSTEM
IsInherited
: False
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : InheritOnly
FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited
: False
InheritanceFlags : None
PropagationFlags : None

136

Microsoft Confidential

Demonstration

Lesson 10 | Registry, Event Log and


ACL Management
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson10\lesson10-demo.txt

137

Microsoft Confidential

Lab 10 | Registry, Event Log and ACL Management


(30 minutes)
Scenario

This lab will provide you handson experience with basic


windows management.

Goals
Reading remote registry information
Searching event logs
File and Folder ACL management

138

Microsoft Confidential

Lesson 11 | Remoting

139

Microsoft Confidential

Lesson 11 | Remoting
Remoting Technologies
PowerShell Remoting
Raw WS-Man
(WinRM)
-ComputerName
WMI Cmdlets

RPC,
DCOM,
LDAP
140

WMI
Microsoft Confidential

PowerShell
Remoting

WSMAN

Lesson 11 | Remoting
WMI
Easiest way to remote in PowerShell v1.0

Get-WmiObject -Class <class> -ComputerName <computer>

$s = Get-WmiObject win32_bios -ComputerName dc


$s | format-List *

141

Microsoft Confidential

Lesson 11 | Remoting
-ComputerName
-ComputerName

Uses Application specific remoting technology


(RPC, DCOM, LDAP)
Get-Help * -Parameter ComputerName

$p = Get-Process -ComputerName billpc, benpc


$p |ft machinename,name
142

Microsoft Confidential

Lesson 11 | Remoting
WS-Management | WinRM (Microsoft)
WS-MAN

Management initiative driven by DMTF


Platform independent, interoperable & industry standard
management solution
CIM based standards for Server and Desktop management
WS-Management (WSMAN)

143

Microsoft Confidential

Lesson 11 | Remoting
Requirements & Configuration
Local & remote machine:
PowerShell 2.0
.NET Framework 2.0 or later
WinRM 2.0

Get-Help:
about_Remote_FAQ
about_Remote_TroubleShooting

Enable via PowerShell:


Enable-PSRemoting [-force]
Runs the Set-WSManQuickConfig cmdlet
Enables all registered Windows PowerShell session configurations to
receive instructions from a remote computer
Force suppresses all user prompts

144

Microsoft Confidential

Lesson 11 | Remoting
Configuration
Enable via GPO:
Computer Configuration\Administrative Templates\Windows
Components\Windows Remote Management (WINRM)\WinRM
Service
Edit Allow automatic configuration of listeners
Click Enable, Enter * against both the the Ipv4 and Ipv6 filter

Computer Configuration\Windows Settings\Security


Settings\System Services\Windows Remote Management
Click Automatic

Computer Configuration\Administrative
Templates\Network\Network Connections\Windows
Firewall\Domain Profile
Edit Define inbound port exceptions
Click Enabled
Click Show
Define the port exception as 5985:TCP:*:Enabled:AllowWinRM
145

Microsoft Confidential

Lesson 11 | Remoting
Verify Configuration
Winrm get winrm/config/client

Check WinRM Service:


get-service -computername syddc01,sydsql01,w7client | ?{$_.name eq "winrm"} | select name,machinename,status | sort machinename |
ft -autosize
146

Microsoft Confidential

Lesson 11 | Remoting
Remoting Architecture

PSSession

Get-Process
SOAP
SSL
TCP Port
5985
XML

147

Microsoft Confidential

Lesson 11 | Remoting
Three Methods To Use Remoting
I. Execute a Single Command or Script
II. Create a Persistent Session
III. Create an Interactive Session

148

Microsoft Confidential

Lesson 11 | Remoting
I. Execute a Single Command or Script
Invoke-Command
One or many machines
Run a command scriptblock
Run a local script remotely -FilePath

Invoke-Command computername s1 scriptblock {get-process}


Invoke-Command computername s1, s2, s3 scriptblock {get-process}
Invoke-Command -ComputerName s1, s2 -FilePath c:\temp\test.ps1

149

Microsoft Confidential

Lesson 11 | Remoting
II. Create a Persistent Session
New-PSSession
$s = New-PSSession -ComputerName Billpc
Invoke-Command -Session $s scriptblock {gps}

Get-PSSession
New-PSSession ComputerName Bill
$s = Get-PSSession Id 1
Invoke-Command session $s scriptblock {Get-Culture}

150

Microsoft Confidential

Lesson 11 | Remoting
III. Create an Interactive Session
Enter-PSSession (etsn)
PS C:\> Enter-PSSession -ComputerName Billpc
[Billpc]: PS C:\Windows\system32>
$env:computername
Billpc

Exit-PSSession (exit)

151

Microsoft Confidential

Lesson 11 | Remoting
ThrottleLimit

Parameter of many cmdlets including Invoke-Command


-ThrottleLimit
Default to 32 concurrent connections if parameter omitted
To find cmdlets that support ThrottleLimit:
Get-Help * -parameter Throttlelimit

Use Invoke-Command to wrap cmdlets that do not natively


support throttling

152

Microsoft Confidential

Lesson 11 | Remoting
Background Jobs
Run local

Or remotely

Job1
Job1
Job2
Job2

Job3

153

Microsoft Confidential

Lesson 11 | Remoting
Starting Background Jobs
Jobs can be run locally or remotely using:
Start-Job:
Start-Job -ScriptBlock {dir path c:\windows rec}
Start-Job -Filepath c:\scripts\sample.ps1
ICM -computername s1 -scriptblock {get-eventlog system} -asjob

Get-Job:
Id
-1

154

Name State
---- ----Job1 Running

HasMoreData
----------True

Location
-------localhost

Microsoft Confidential

Command
------dir c:\

Lesson 11 | Remoting
Starting Background Jobs
Receive-Job gets job results (or partial results if the job is
incomplete)
PS C:\> Start-Job -ScriptBlock {gps vpc*}
Id
-11

Name State
HasMoreData
---- --------------Job11 Running True

Location Command
-------- ------localhost gps vpc*

PS G:\> Receive-Job -id 11 | fl cpu


CPU : 849.6282463

Receive-Job keep prevents deleting of the job results


155

Microsoft Confidential

Lesson 11 | Remoting
Job Completion
Wait-Job
Suppresses the PowerShell prompt until the job is complete

Stop-Job
Get-Job name n*| Stop-Job
Stop-Job *

Remove-Job
The Job must be stopped before it can be removed

156

Microsoft Confidential

Lesson 11 | Remoting
Constrained Session Configuration
Default session config allows builtin\administrators full
control
Restrict local activity from remote session with a new
session config:
Register-PSSessionConfiguration

Assign Execute (Invoke) permission to use custom session


config to AD group:
Set-PSSessionConfiguration ShowSecurityDescriptorUI

Usage:
Specify name of new session config in -ConfigurationName
parameter of remoting cmdlets
Use -Credential parameter of remoting cmdlets
157

Microsoft Confidential

Demonstration

Lesson 11 | Remoting
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson11\lesson11-demo.txt
158

Microsoft Confidential

Lab 11 | Remoting (30 minutes)


Scenario

This lab will provide you handson experience with PowerShell


remoting.

Goals
Execute remote commands
Execute commands via sessions
Use an interactive remote console

159

Microsoft Confidential

Você também pode gostar