Documente Academic
Documente Profesional
Documente Cultură
Microsoft Confidential
Microsoft Confidential
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
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
Microsoft Confidential
Lesson 1 | Introduction
Prerequisites and Installation
Middleware
.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-Help
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
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
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
Or
$a = Get-Service
$a | Get-Member
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
Get-Alias
New-Alias gh Get-Help
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
System.String
Type
Namespace
System.DirectoryServices.DirectoryEntry
Type
Microsoft Confidential
Lesson 2 | Commands
Utilising .Net Framework | Instantiate Object
$webClient | Get-Member
26
Microsoft Confidential
Lesson 2 | Commands
Classes & Objects
Class = Object Template
5 points
Size
Colour
Orientation
27
Microsoft Confidential
Lesson 2 | Commands
Utilising .Net Framework | Classes and Static Members
28
Microsoft Confidential
Lesson 2 | Commands
Utilising .Net Framework | Windows Forms
Not all .net assemblies are
available to PowerShell by
default!
[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()
Microsoft Confidential
Lesson 2 | Commands
Component Object Model (COM)
HKEY_CLASSES_ROOT
30
Microsoft Confidential
Lesson 2 | Commands
Component Object Model (COM) | Instantiate Object
-ComObject parameter to
differentiate from .Net Object
31
Microsoft Confidential
Demonstration
Lesson 2 | Commands
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson2\lesson2-demo.txt
32
Microsoft Confidential
Goals
Work with Cmdlets
Work with New Object
33
Microsoft Confidential
Lesson 3 | Pipeline
34
Microsoft Confidential
Lesson 3 | Pipeline
Introduction
Get-Service
Objects
35
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)}}
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
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
43
Microsoft Confidential
Demonstration
Lesson 3 | Pipeline
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson3\lesson3-demo.txt
44
Microsoft Confidential
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
47
Microsoft Confidential
Lesson 4 | Providers
Cmdlets
Get-Help about_providers
Get help
Get-PSProvider
Get-PSDrive
Set-Location HKLM:
Connect to provider
48
Microsoft Confidential
Demonstration
Lesson 4 | Providers
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson4\lesson4-demo.txt
49
Microsoft Confidential
Goals
Work with Environment Provider
Work with Certificate Provider
Work with Registry Provider
50
Microsoft Confidential
51
Microsoft Confidential
52
Microsoft Confidential
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
BaseType
-------System.ValueType
Microsoft Confidential
$Error
55
$Home
$True
$False
Hello World!
56
$a
Microsoft Confidential
Object 1
57
Object 2
Object 3
Microsoft Confidential
Object 4
Object 5
$arrProcesses = Get-Process
58
Microsoft Confidential
Object 1
Object 2
Object 3
Object 4
Object 5
Zero-based
(Index 0)
$arrProcesses[0].name
$arrProcesses[4].name
Index Numbers
$arrProcesses[0]
$arrProcesses[-1]
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
61
Microsoft Confidential
62
Microsoft Confidential
63
Microsoft Confidential
Writing to Console
Write-Host $a foregroundcolor green
or
$a
64
Microsoft Confidential
Out-Printer
Out-Host
Out-GridView
65
Write-Host
Write-Output
Tee-Object
Microsoft Confidential
Copying files:
Copy-Item C:\setup.log d:\
Moving files:
Move-Item C:\setup.log d:\
66
Microsoft Confidential
Execution status:
67
Microsoft Confidential
Inquire
68
Microsoft Confidential
Demonstration
Microsoft Confidential
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
All Signed
Remote
Signed
Unrestricted
72
Microsoft Confidential
Lesson 6 | Scripting
Security | Execution Policy | Scope
Process
CurrentUser
LocalMachine
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
Zone Identifier
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
$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
$env:path=$envpath+;c:\scripts
Microsoft Confidential
Lesson 6 | Scripting
Running Scripts
Command line to execute script:
powershell.exe noexit file c:\myscript.ps1
78
Microsoft Confidential
Lesson 6 | Scripting
PowerShell Comments
Requires comment:
#requires version 2
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"}
}
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
Named Parameters
Passed to script with parameter name
.\myscript.ps1 -server srv1 user benp
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
$Profile or
$Profile.CurrentUserCurrentHost
$Profile.CurrentUserAllHosts
$Profile.AllUsersCurrentHost
$Profile.AllUsersAllHosts
87
Scope
Name
$Home\Documents\WindowsPowerShell\Microsoft.PowerS
hellISE_profile.ps1
$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
Microsoft Confidential
Demonstration
Lesson 6 | Scripting
Instructor-led demonstration
PowerShell ISE
C:\pshell\part1\lesson6\lesson6-demo.txt
89
Microsoft Confidential
Goals
Create PowerShell scripts
Create Functions in scripts
Create PowerShell Profiles
90
Microsoft Confidential
91
Microsoft Confidential
Lesson 7 | AD (ADSI)
DirectoryEntry Class
[System.DirectoryServices.DirectoryEntry] or simply [ADSI]
.put()
.get()
.create()
.delete()
.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
Alternate credentials:
$domain = New-Object ADSI(LDAP://DC=contoso,DC=com,
CONTOSO\Administrator,Password123)
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
94
Microsoft Confidential
Lesson 7 | AD (ADSI)
Directory Searcher
Bind to AD:
$domain = [ADSI]LDAP://DC=contoso,DC=com
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
99
Microsoft Confidential
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
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
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
TIP:
107
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
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}
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
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
To return group
object
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
$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
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
Goals
Create Users
Modify AD Objects
Search AD
116
Microsoft Confidential
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
Remove-WmiObject
Set-WmiInstance
Get-WSManInstance
Invoke-WmiMethod
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)
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
Goals
WMI Classes & Queries
Basic filtering
WMI Method Execution
125
Microsoft Confidential
126
Microsoft Confidential
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
Microsoft Confidential
[enum]::GetValues(Microsoft.Win32.RegistryHive)
ClassesRoot
CurrentUser
LocalMachine
Users
PerformanceData
CurrentConfig
DynData
128
Microsoft Confidential
Properties
Methods
ClassesRoot
GetValue
CurrentUser
SetValue
LocalMachine
129
Microsoft Confidential
Properties
Methods
Name
GetSubKeyNames
SubKeyCount
GetValueNames
ValueCount
GetValue
OpenSubKey
130
Microsoft Confidential
$regHKLM = [Microsoft.Win32.Registry]::localmachine
$regHKLM.GetSubKeyNames()
BCD00000000
COMPONENTS
HARDWARE
SAM
SECURITY
SOFTWARE
SYSTEM
131
Microsoft Confidential
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
Microsoft Confidential
System.IO.FileAttributes
Retrieve file & folder attributes
System.IO.FileSystemInfo
Create instance of type to set attributes using instance members
133
Microsoft Confidential
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
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
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
137
Microsoft Confidential
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
141
Microsoft Confidential
Lesson 11 | Remoting
-ComputerName
-ComputerName
Microsoft Confidential
Lesson 11 | Remoting
WS-Management | WinRM (Microsoft)
WS-MAN
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
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\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
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
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
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*
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
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
Goals
Execute remote commands
Execute commands via sessions
Use an interactive remote console
159
Microsoft Confidential