Download as pdf or txt
Download as pdf or txt
You are on page 1of 159

© 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 non-
infringement.
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

TRAINER_NAME
Premier Field Engineer
Microsoft Services
TRAINER_ALIAS@microsoft.com

3 Microsoft Confidential
alias
Introductions

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

4 Microsoft Confidential
Logistics

Class Hours Phones

Rest Rooms Computers

5 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: Hyper-V Host Hyper-V Guests


SYDDC01 W7Client Administrator Administrator
Password P@ssword

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

7 Microsoft Confidential
Lesson 1 | Introduction

8 Microsoft Confidential
Lesson 1 | Introduction
What is PowerShell?

What? Why?

Interactive Shell
Object-oriented
New Scripting
Language
Consistent Method
Revolutionary of Administration

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

 Lightweight
 Quick
 Not as user friendly

 Used for script development


 User friendly
 Very extensible

10 Microsoft Confidential
Lesson 1 | Introduction
Prerequisites and Installation

Middleware

.Net Framework 2 WinRM .Net Framework 3.5

Operating System

XP 2003 Vista 2008 Win7 2008 R2

PowerShell v2 Installed By
Default

11 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

Get-Service –name Bits Get-Help

Set-Location -path c:\windows Set-Location c:\windows

12 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

13 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

14 Microsoft Confidential
Demonstration

Lesson 1 | Introduction
Instructor-led demonstration

PowerShell ISE
C:\pshell\part1\lesson1\lesson1-demo.txt

15 Microsoft Confidential
Lab 1 | Introduction (30 minutes)
Scenario
This lab will provide you hands-
on experience with PowerShell
commands.

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

16 Microsoft Confidential
Lesson 2 | Commands

17 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
Get-Command -Type cmdlet $a = Get-Service
$a | Get-Member

18 Microsoft Confidential
Lesson 2 | Commands
Objects
“An object is a collection of parts and
how to use them”
Parts How to use
Properties Methods
Pedal
Front Wheel
Brake
Back Wheel
Steer Left
Pedals
Steer Right
Saddle
Wheelie
Frame

19 Microsoft Confidential
Lesson 2 | Commands
Object (Service)

Properties Methods

Service Name Start()

Status Stop()

Pause()

Service

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

22 Microsoft Confidential
Lesson 2 | Commands
.Net Framework

VB
PowerShell C#
.Net
.Net Framework

Object Object Object Object Object

Operating System
Win32 API

23 Microsoft Confidential
Lesson 2 | Commands
Namespaces & Types

.Net Class Library: Hierarchy of


Namespace namespaces

System.String Namespace: Collection of Types i.e.


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

Type: The class used to create an


System.DirectoryServices.DirectoryEntry object instance can be said to be the
type of that object.
Type
Example of Type in PowerShell:
[math] or [system.math]

24 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“
}

25 Microsoft Confidential
Lesson 2 | Commands
Classes & Objects

Class = Object Template Object = Instance of a class

5 points
Size
Colour
Orientation

26 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)}

27 Microsoft Confidential
Lesson 2 | Commands
Utilising .Net Framework | Windows Forms

Not all .net assemblies are May need to load assemblies


available to PowerShell by
default! 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

28 Microsoft Confidential
Lesson 2 | Commands
Component Object Model (COM)

HKEY_CLASSES_ROOT

Lists all installed


COM components

29 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”)

30 Microsoft Confidential
Demonstration

Lesson 2 | Commands
Instructor-led demonstration

PowerShell ISE
C:\pshell\part1\lesson2\lesson2-demo.txt

31 Microsoft Confidential
Lab 2 | Commands (30 minutes)
Scenario
This lab will provide you hands-
on experience with PowerShell
commands.

Goals

Work with Cmdlets


Work with New Object

32 Microsoft Confidential
Lesson 3 | Pipeline

33 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"} | Format-List

Objects Current Object On Pipeline Objects


(the pipeline variable)

34 Microsoft Confidential
Lesson 3 | Pipeline
Operators

Arithmetic
Assignment
Comparison
Logical
Redirection
Split/Join
Type
Unary
Special

35 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 case-
sensitive)
13 Comparison operators:
-eq -ne -gt -ge -lt
-le -like -notlike -match -notmatch
-contains -notcontains -replace

Examples:
“PowerShell” –eq “powershell” 4 –gt 4

36 Microsoft Confidential
Lesson 3 | Pipeline
Logical Operators

Join multiple operations


Check for compound conditions
True/False
5 logical and 4 bitwise operators:

-and -or -xor -band -bor


-not ! -bxor -bnot

Examples:

(4 –ge 8) –and (5 –lt 10) ! (4 –eq 4)

37 Microsoft Confidential
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

38 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 }

39 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

40 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

41 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

42 Microsoft Confidential
Demonstration

Lesson 3 | Pipeline
Instructor-led demonstration

PowerShell ISE
C:\pshell\part1\lesson3\lesson3-demo.txt

43 Microsoft Confidential
Lab 3 | Pipeline (30 minutes)
Scenario
This lab will provide you hands-
on experience with the
PowerShell pipeline.

Goals

Work with PowerShell Operators


Work with PowerShell Pipeline
Filter and sort with the Pipeline

44 Microsoft Confidential
Lesson 4 | Providers

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

46 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

47 Microsoft Confidential
Demonstration

Lesson 4 | Providers
Instructor-led demonstration

PowerShell ISE
C:\pshell\part1\lesson4\lesson4-demo.txt

48 Microsoft Confidential
Lab 4 | Providers (30 minutes)
Scenario
This lab will provide you hands-
on experience with PowerShell
providers.

Goals

Work with Environment Provider


Work with Certificate Provider
Work with Registry Provider

49 Microsoft Confidential
Lesson 5 | Variables and Type Fundamentals

50 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

51 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

52 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 BaseType


-------- -------- ---- --------
True True Int32 System.ValueType
53 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
$Home Home directory of the user
$True Check for Boolean Value of True
$False Check for Boolean Value of False

54 Microsoft Confidential
Lesson 5 | Variables and Type Fundamentals
Strings & Spaces

String
Expandable – double quotes “”

$a = “Hello World!”
$b = “$a” Hello World!
$b

Literals – single quote ‘’

$a = “Hello World!”
$b = ‘$a’ $a
$b

55 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 Object 2 Object 3 Object 4 Object 5

56 Microsoft Confidential
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:
Tip: Useful with iteration statements. Ex:
$arr2.count
for ($a=0;$a -le $arr2.count-1;$a++)
{$arr2[$a]}
Add element to array, and assign a value:
$arr2 += “d”

57 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 0,1


Index 1,0 Index 1,1

59 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

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

61 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

62 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


$name = Read-Host “Enter your name”
Use Read-Host to assign to Write-Host "Hello $name”
variable

63 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

Write-Host
Out-GridView
Out-GridView Display output in a Grid view
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

64 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

65 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

66 Microsoft Confidential
Lesson 5 | Variables and Type Fundamentals
ErrorActionPreference Variable

•Do not display messages on host


SilentlyContinue •Continue processing following elements

Continue •Display message on host


(default) •Continue processing following elements

•Display message on host


Stop •Stop all processing

•Display message on host


Inquire •Prompt user if processing should continue

67 Microsoft Confidential
Demonstration

Lesson 5 | Variables and Type


Fundamentals
Instructor-led demonstration

PowerShell ISE
C:\pshell\part1\lesson5\lesson5-demo.txt
68 Microsoft Confidential
Lab 5 | Variables and Type Fundamentals
(30 minutes)
Scenario
This lab will provide you hands-
on 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

69 Microsoft Confidential
Lesson 6 | Scripting

70 Microsoft Confidential
Lesson 6 | Scripting
Security | Execution Policy | Settings

• Scripts cannot be run


Restricted • PowerShell interactive-mode only
• Default Setting

• Runs a script only if signed


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

• Runs all local scripts


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

Unrestricted • All scripts from all sources can be run without


signing

71 Microsoft Confidential
Lesson 6 | Scripting
Security | Execution Policy | Scope

• Affects current session only


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

• Affects current user only


CurrentUser • Stored in HKCU registry subkey

• Affects all users on computer


LocalMachine • Stored in HKLM registry subkey

set-executionpolicy -scope CurrentUser -executionPolicy Unrestricted

72 Microsoft Confidential
Lesson 6 | Scripting
Security | Execution Policy | Cmdlets

Get-Help about_execution_policies • Get help

Get-ExecutionPolicy • Current policy

Get-ExecutionPolicy -list • All policies in precedence order

Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined • Group Policy
UserPolicy Undefined
Process Undefined • Effective Execution Policy
CurrentUser RemoteSigned
LocalMachine AllSigned

Requires Elevated
Set-ExecutionPolicy remotesigned • Set Policy
PowerShell Session

73 Microsoft Confidential
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

74 Microsoft Confidential
Lesson 6 | Scripting
Security | Execution Policy | All Signed | Script Signing

Get-Help about_signing Requires self-signed


or CA cert on
machine

Set-AuthenticodeSignature .\test.ps1 $cert

$Cert

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

75 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 $env:path=$envpath+”;c:\scripts”

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

77 Microsoft Confidential
Lesson 6 | Scripting
PowerShell Comments

Requires comment:
#requires –version 2

Single line comment:


#

Delimited comment:
<#
Author:
Date:
#>

78 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
;

79 Microsoft Confidential
Lesson 6 | Scripting
Iteration Statements (Loops) $a=1
do
{write-host “Loop:$a”}
Do While while ($a++ -le 5)

While
$a=1
While ($a –lt 10) Do Until
{$a; $a++}
$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}

80 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

81 Microsoft Confidential
Lesson 6 | Scripting
Other Statements

If Statement Switch Statement


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

Labeled :outer while ($true)


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

82 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

83 Microsoft Confidential
Lesson 6 | Scripting
Scripts | Command Line Arguments

Positional Parameters
$Args

Passed to script with spaces Named Parameters


.\myscript.ps1 server1 benp
Passed to script with parameter name

Accessed in script by $args array


.\myscript.ps1 -server srv1 –user benp

$servername = $args[0]
$username = $args[1] User parameter name directly in script
Param($server, $user)
Write-Host $server
Write-Host $user

84 Microsoft Confidential
Lesson 6 | Scripting
Profiles

Start
PowerShell

Execute Profile
Scripts
Profile 1

Profile 2

Profile 3

PS:/>

85 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

Scope Name
Current User, Current Host $Home\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profil
e.ps1
All Users, Current Host $PsHome\Microsoft.PowerShellISE_profile.ps1

86 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

87 Microsoft Confidential
Demonstration

Lesson 6 | Scripting
Instructor-led demonstration

PowerShell ISE
C:\pshell\part1\lesson6\lesson6-demo.txt
88 Microsoft Confidential
Lab 6 | Scripting (30 minutes)
Scenario
This lab will provide you hands-
on experience with PowerShell
Scripting.

Goals

Create PowerShell scripts


Create Functions in scripts
Create PowerShell Profiles

89 Microsoft Confidential
Lesson 7 | Active Directory Administration (ADSI)

90 Microsoft Confidential
Lesson 7 | AD (ADSI)
DirectoryEntry Class
[System.DirectoryServices.DirectoryEntry] or simply [ADSI]

.put()
.create() .get()

.delete() Directory Entry .setinfo()


(.Net Type)

.set() .putex()
.setex()

$user | Get-Member $user.psbase | Get-Member

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

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

93 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: All user


objects
$dirSearch.FindAll() All objects in
domain
Set search filter: Windows
$dirSearch.Filter = “(objectCategory=user)” Server
computer
objects

“(&(objectCategory=computer)(operatingSystem=Windows Server*))”

94 Microsoft Confidential
Lesson 7 | AD (ADSI)
Organizational Unit Management

Create $objRoot = [ADSI]”LDAP://DC=contoso,DC=com”


$objOU = $objRoot.Create(“organizationalunit”,”OU=Finance”)
OU $objOU.SetInfo()

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

Delete $objRoot = [ADSI]”LDAP://DC=contoso,DC=com”


$objOU = $objRoot.Delete(“organizationalunit”,”OU=Finance”)
OU

95 Microsoft Confidential
Lesson 7 | AD (ADSI)
User Management

Create $objOU = [ADSI]”LDAP://OU=Finance,DC=contoso,DC=com”


$objUser = $objOU.Create(“user”,“CN=FinanceUser01”)
User $objUser.SetInfo()

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

User
$objUser.AccountDisabled = $false
$objUser.Setinfo()

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

Delete $objOU = [ADSI]”LDAP://OU=Finance,DC=contoso,DC=com”

User
$objOU.Delete('User', 'CN=FinanceUser01')

96 Microsoft Confidential
Demonstration

Lesson 7 | AD (ADSI)
Instructor-led demonstration

PowerShell ISE
C:\pshell\part1\lesson7\lesson7-demo.txt
97 Microsoft Confidential
Lab 7 | AD (ADSI) (30 minutes)
Scenario
This lab will provide you hands-
on experience administering
Active Directory using
PowerShell and ADSI.

Goals

Create Multiple AD Users

98 Microsoft Confidential
Lesson 8 | Active Directory Administration
(cmdlets)

99 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

100 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

101 Microsoft Confidential


Lesson 8 | AD (cmdlets)
Cmdlets

102 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

103 Microsoft Confidential


Lesson 8 | AD (cmdlets)
Active Directory Web Services

ADWS

Windows 2008 R2 Windows 7


RSAT
AD Module

104 Microsoft Confidential


Lesson 8 | AD (cmdlets)
AD Management Gateway Service

Updates

.Net 3.5 SP1

AD DS
Windows 7
RSAT
Windows 2008 AD Module
Windows 2003 SP2
Windows 2003 R2 SP2

105 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: Do not hardcode DC names in scripts!


(Use Domain FQDN to discover DC)

106 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>

107 Microsoft Confidential


Lesson 8 | AD (cmdlets)
AD Provider

AD Provider is available once AD Module is imported:


Get-PSProvider Name Capabilities Drives
-------- ---------------- --------
ActiveDirectory Include... {AD}

Use common Provider cmdlets to manage AD drive:

Set-location ad: dir | ft pschildname


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

108 Microsoft Confidential


Lesson 8 | AD (cmdlets)
User Account Management | AD Cmdlets
New-ADUser –name benp -SamAccountName “benp"
Create User -GivenName “ben" -Surname “Pearce"
-DisplayName “Ben Pearce"

Enumerate Get-ADUser -Filter * -Properties *


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

Modify User Set-ADUser -Identity “benp" –Title “Engineer"

Target Single AD Object Only!

Delete User Remove-ADUser benp

109 Microsoft Confidential


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

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

Find Stale $OneYearAgo = (Get-Date).AddYears(-1)


Computer Get-ADComputer -Filter {LastLogonTimeStamp –lt`
$OneYearAgo} | Disable-ADAccount
Accounts

110 Microsoft Confidential


Lesson 8 | AD (cmdlets)
Group Management | AD Cmdlets
Nested group
Enumerate membership
Group Get-ADGroupMember IT -Recursive

New-ADGroup –name “Sales” `


Create -Path “OU=Groups,DC=Contoso,DC=com” `
Group -GroupScope “Global” `
-GroupCategory “Security” To return group
object

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


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

111 Microsoft Confidential


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

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

TIP: 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

112 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. @{}
New-ADUser `
-Path "ou=sales,ou=departments,dc=contoso,dc=com" `
-name "Sales1" -SamAccountName "Sales1" `
-UsePrincipalName "Sales1@contoso.com" `
User -department "sales" `
Telephone -OtherAttributes `
Numbers @{otherTelephone="555-555-5555","123-456-7890"}

113 Microsoft Confidential


Demonstration

Lesson 8 | AD (cmdlets)
Instructor-led demonstration

PowerShell ISE
C:\pshell\part1\lesson8\lesson8-demo.txt

114 Microsoft Confidential


Lab 8 | AD (cmdlets) (30 minutes)
Scenario
This lab will provide you hands-
on experience with the AD
Module.

Goals

Create Users
Modify AD Objects
Search AD

115 Microsoft Confidential


Lesson 9 | Windows Management
Instrumentation

116 Microsoft Confidential


Lesson 9 | WMI
WMI in Microsoft Windows

PowerShell

Class Class

Class Class Class


Class
CIMV2 Virtualization
Namespace Namespace

117 Microsoft Confidential


Lesson 9 | WMI
WMI & Remote Machines | Requirements

No PS required!
PowerShell Admin Remote Machine

PowerShell
WMI Service
Get-WMIObject

DCOM DCOM

Other:
RPC RPC DNS
Permission
TCP/IP TCP/IP

118 Microsoft Confidential


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

119 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

120 Microsoft Confidential


Lesson 9 | WMI
Instantiate WMI Object

$bios = Gwmi –namespace “root\cimv2” –class Win32_Bios


$bios | gm

Properties

BIOSVersion

InstallDate

$bios.BIOSVersion

121 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

122 Microsoft Confidential


Demonstration

Lesson 9 | WMI
Instructor-led demonstration

PowerShell ISE
C:\pshell\part1\lesson9\lesson9-demo.txt

123 Microsoft Confidential


Lab 9 | WMI (1 hour)
Scenario
This lab will provide you hands-
on experience with WMI.

Goals

WMI Classes & Queries


Basic filtering
WMI Method Execution

124 Microsoft Confidential


Lesson 10 | Registry, Event Log and ACL
Management

125 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")

126 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

127 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

128 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

129 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

130 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

131 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

132 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

133 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

134 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

135 Microsoft Confidential


Demonstration

Lesson 10 | Registry, Event Log and


ACL Management
Instructor-led demonstration

PowerShell ISE
C:\pshell\part1\lesson10\lesson10-demo.txt

136 Microsoft Confidential


Lab 10 | Registry, Event Log and ACL Management
(30 minutes)

Scenario
This lab will provide you hands-
on experience with basic
windows management.

Goals

Reading remote registry information


Searching event logs
File and Folder ACL management

137 Microsoft Confidential


Lesson 11 | Remoting

138 Microsoft Confidential


Lesson 11 | Remoting
Remoting Technologies

PowerShell Remoting
Raw WS-Man
(WinRM)

-ComputerName

PowerShell
WMI Cmdlets Remoting

RPC, WS-
DCOM, WMI
LDAP MAN
139 Microsoft Confidential
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 *

140 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

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

142 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

143 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

144 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

145 Microsoft Confidential


Lesson 11 | Remoting
Remoting Architecture

PSSession

Get-Process
SOAP

SSL

TCP Port
XML5985

146 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

147 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

148 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}

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

150 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

151 Microsoft Confidential


Lesson 11 | Remoting
Background Jobs

Run local Or remotely

Job1

Job1
Job2

Job2
Job3

152 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 Name State HasMoreData Location Command


-- ---- ----- ----------- -------- -------
1 Job1 Running True localhost dir c:\

153 Microsoft Confidential


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 Name State HasMoreData Location Command


-- ---- ----- ----------- -------- -------
11 Job11 Running True localhost gps vpc*

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

CPU : 849.6282463

Receive-Job –keep prevents deleting of the job results

154 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

155 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

156 Microsoft Confidential


Demonstration

Lesson 11 | Remoting
Instructor-led demonstration

PowerShell ISE
C:\pshell\part1\lesson11\lesson11-demo.txt

157 Microsoft Confidential


Lab 11 | Remoting (30 minutes)
Scenario
This lab will provide you hands-
on experience with PowerShell
remoting.

Goals

Execute remote commands


Execute commands via sessions
Use an interactive remote console

158 Microsoft Confidential

You might also like