PowerShell for the IT Administrator Part 1 v1.1
Transcript of PowerShell for the IT Administrator Part 1 v1.1
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
1/160
Microsoft Confidential
2011 Microsoft Corporation. All rights reserved.
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
2/160
Conditions and Terms of Use
This training package is proprietary and confidential, and is intended only for uses described in the training materials. Content and softwareis provided to you under a Non-Disclosure Agreement and cannot be distributed. Copying or disclosing all or any portion of the contentand/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 Microsoftmust respond to changing market conditions, the content should not be interpreted to be a commitment on the part of Microsoft, andMicrosoft 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 noassociation with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or shouldbe inferred.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in thisdocument. Except as expressly provided in written license agreement from Microsoft, the furnishing of this document does not give you anylicense 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 athttp://www.microsoft.com/about/legal/permissions/
Microsoft, Internet Explorer, and Windows are either registered trademarks or trademarks of Microsoft Corporation in the UnitedStates and/or other countries. Other Microsoft products mentioned herein may be either registered trademarks or trademarks of MicrosoftCorporation in the United States and/or other countries. All other trademarks are property of their respective owners.
Copyright and Trademarks 2011 Microsoft Corporation. All rights reserved.
Microsoft Confidential
http://www.microsoft.com/about/legal/permissions/http://www.microsoft.com/about/legal/permissions/http://www.microsoft.com/about/legal/permissions/http://www.microsoft.com/about/legal/permissions/ -
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
3/160
PowerShell for the IT Administrator
Part 1
Microsoft Confidential
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
4/160
Meet your trainer
Microsoft Confidential3
Patricio Belardo
Senior Premier Field Engineer
IIS / Dev
alias
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
5/160
Introductions
About You:Name
Company Affiliation
Title/Function/Area of ResponsibilityProduct experience
Expectations for this Course
Microsoft Confidential4
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
6/160
Logistics
Microsoft Confidential5
Rest Rooms
Class Hours
Computers
Phones
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
7/160
Workshop Information
Course Material:Student Lab Manual
Demonstration Scripts
Hands-On Lab Solutions
Delivery Method:Slides Demonstration Hands-On
Lab Environment:
Microsoft Confidential6
SYDDC01 W7Client
C:\pshell\part1\lesson C:\pshell\part1\lesson\labs
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
8/160
Virtual Lab Environment
Microsoft Confidential7
alias
https://www.premier-education-services.com/
Login with Microsoft Account
Enter POWERSHELL as Lab ID
https://www.premier-education-services.com/https://www.premier-education-services.com/https://www.premier-education-services.com/https://www.premier-education-services.com/https://www.premier-education-services.com/https://www.premier-education-services.com/https://www.premier-education-services.com/ -
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
9/160
Agenda
Lesson 1 | Introduction
Lesson 2 | Commands
Lesson 3 | Pipeline
Lesson 4 | Providers
Lesson 5 | Variables and Type FundamentalsLesson 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
Microsoft Confidential8
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
10/160
Lesson 1 | Introduction
Microsoft Confidential9
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
11/160
Lesson 1 | IntroductionWhat is PowerShell?
10 Microsoft Confidential
What? Why?
New Scripting
Language
Object-oriented
Consistent Methodof AdministrationRevolutionary
Interactive Shell
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
12/160
Lesson 1 | IntroductionConsole & Integrated Scripting Environment (ISE)
11 Microsoft Confidential
Lightweight
Quick
Not as user friendly
Used for script development User friendly
Very extensible
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
13/160
Lesson 1 | IntroductionPrerequisites and Installation
12 Microsoft Confidential
XP
Operating System
2003 Vista 2008 Win7 2008 R2
.Net Framework 2 .Net Framework 3.5WinRM
Middleware
PowerShell v2 Installed ByDefault
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
14/160
Lesson 1 | Introduction
Cmdlet pronounced Command-let
Smallest unit of functionality
Always of the form Verb-Noun
Parameter names are always passed with - as switch
Basic PowerShell Commands | Cmdlets
13 Microsoft Confidential
Get-Service name Bits
Set-Location -path c:\windows
Get-Help
Set-Location c:\windows
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
15/160
Lesson 1 | Introduction
Built-In HelpCmdlet Help:
Concept Help e.g. about topics:
PowerShell Help
14 Microsoft Confidential
Get-Help Get-Command Full
Get-Help Get-Command Detailed
Get-Help Get-Command Examples
Get-Help about_
Get-Help about_wildcards
Get-Help about_Variables
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
16/160
Lesson 1 | Introduction
Start-TranscriptCreate record of PowerShell session in a text file
Get-HistoryReturns last 32 commands
Use $MaximumHistoryCount automatic variable to return last 64
Use Invoke-History to re-run a command
PowerShell Command History
15 Microsoft Confidential
start-transcript PowerShell_transcript.txt
stop-transcript
get-history
Invoke-history id id#
$MaximumHistoryCount
get-history count $MaximumHistoryCount
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
17/160
Demonstration
Lesson 1 | IntroductionInstructor-led demonstration
PowerShell ISEC:\pshell\part1\lesson1\lesson1-demo.txt
Microsoft Confidential16
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
18/160
Lab 1 | Introduction (30 minutes)
Goals
Scenario
Create transcripts of PowerShellcommands
Practice using the top 3 cmdlets
Execute multiple commands in a singleline.
This lab will provide you hands-on experience with PowerShellcommands.
Microsoft Confidential17
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
19/160
Lesson 2 | Commands
Microsoft Confidential18
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
20/160
Lesson 2 | CommandsImportant Cmdlets
19 Microsoft Confidential
Get-Command Get-Member
Get-Command -Verb set
Get-Command -Type cmdlet
Get-Service | Get-Member
$a = Get-Service
$a | Get-Member
Or
Discovers CmdletsGets all properties and methods
of an object.
Get-Command Noun service
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
21/160
Lesson 2 | CommandsObjects
20 Microsoft Confidential
An object is a collection of parts andhow to use them
How to useMethods
PartsProperties
Front Wheel
Back Wheel
Pedals
Saddle
Frame
Pedal
Brake
Steer Left
Steer Right
Wheelie
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
22/160
Lesson 2 | CommandsObject (Service)
21 Microsoft Confidential
MethodsProperties
Service
Service Name
Status
Start()
Stop()
Pause()
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
23/160
Lesson 2 | Commands
A shortened name for a commandEg dir => get-childitem
Allows you to provide a new term for an existing cmdlet
Aliases
Get-Help *alias*
New-Alias gh Get-Help
Get-Alias - Shows existing aliases
- Creates new alias
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
24/160
Lesson 2 | Commands
.Net Framework
COM
WMI (Lesson 9)
Object Models
23 Microsoft Confidential
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
25/160
Lesson 2 | Commands.Net Framework
24 Microsoft Confidential
Operating SystemWin32 API
PowerShell C#VB
.Net
ObjectObjectObjectObjectObject
.Net Framework
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
26/160
Lesson 2 | CommandsNamespaces & Types
25 Microsoft Confidential
Namespace:Collection of Types i.e.
Classes(template of properties and methods tocreate an object)
Type:The class used to create an
object instance can be said to be thetype of that object.
Namespace
System.String
Type
Namespace
System.DirectoryServices.DirectoryEntry
Type
.Net Class Library: Hierarchy ofnamespaces
Example of Type in PowerShell:[math] or [system.math]
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
27/160
Lesson 2 | CommandsUtilising .Net Framework | Instantiate Object
26 Microsoft Confidential
$webClient = new-object System.Net.WebClient
$output = $webClient.DownloadString("http://www.tvguide.co.uk")
if ($output -like "*Top Gear*")
{ "Wahoo Top Gear is on
}
$webClient = new-object System.Net.WebClient
$webClient | Get-Member
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
28/160
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
29/160
Lesson 2 | CommandsUtilising .Net Framework | Classes and Static Members
28 Microsoft Confidential
A static member can be used without first creating aninstance of the class
Display static members of the math class:
Example use of a static member of the math class:
[math] | get-member -static
(gwmi win32_logicaldisk | ?{$_.drivetype -le 4}) `
| %{[math]::round($_.freespace/1gb,2)}
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
30/160
[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()
Lesson 2 | CommandsUtilising .Net Framework | Windows Forms
29 Microsoft Confidential
May need to load assemblies
Nasty syntax
Not all .net assemblies areavailable to PowerShell by
default!
Add-Type cmdlet can also beused to add a type to a PS session
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
31/160
Lesson 2 | CommandsComponent Object Model (COM)
30 Microsoft Confidential
HKEY_CLASSES_ROOT
Lists all installedCOM components
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
32/160
Lesson 2 | CommandsComponent Object Model (COM) | Instantiate Object
31 Microsoft Confidential
Get-Help New-Object -det
$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)
-ComObject parameter todifferentiate from .Net Object
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
33/160
Demonstration
Lesson 2 | Commands
Instructor-led demonstration
PowerShell ISEC:\pshell\part1\lesson2\lesson2-demo.txt
Microsoft Confidential32
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
34/160
Lab 2 | Commands (30 minutes)
Goals
Scenario
Work with CmdletsWork with New Object
This lab will provide you hands-on experience with PowerShellcommands.
Microsoft Confidential33
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
35/160
Lesson 3 | Pipeline
Microsoft Confidential34
|
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
36/160
Lesson 3 | PipelineIntroduction
35 Microsoft Confidential
| pipes (or sends) output from left to a command onthe 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 ObjectsCurrent Object On Pipeline(the pipeline variable)
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
37/160
3 | i li
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
38/160
Lesson 3 | Pipeline
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:
Examples:
Comparison Operators
37 Microsoft Confidential
-eq -ne -gt -ge -lt
-le -like -notlike -match -notmatch
-contains -notcontains -replace
PowerShell eq powershell 4 gt 4
L 3 | Pi li
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
39/160
Lesson 3 | Pipeline
Join multiple operations
Check for compound conditions
True/False
5 logical and 4 bitwise operators:
Examples:
Logical Operators
38 Microsoft Confidential
-and -or -xor
-not !
(4 ge 8) and (5 lt 10) ! (4 eq 4)
-band -bor
-bxor -bnot
L 3 | Pi li
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
40/160
Lesson 3 | Pipeline
PS only sends the most pertinent data to the console
Select-Object, Format-List and Format-Table cmdlets allowcontrol over the properties displayed:
Filtering, Sorting, and Grouping data | Display
39 Microsoft Confidential
Get-ChildItem | Select-Objectproperty Name, Length, LastWriteTime
gci | SelectName, @{Name=Size(MB);Expression={[Math]::Round($_.Length/1MB, 2)}}
Get-Process | Format-List-Property ID, Name
Get-Process | FL*
Get-Service | FTProperty Name, Status AutoSize -Wrap
L 3 | Pi li
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
41/160
Lesson 3 | Pipeline
Where-Object can be used to filter results:
Filtering, Sorting, and Grouping data | Filtering
40 Microsoft Confidential
Get-Process | Where-Object { $_.WS -gt 50MB }
Get-Process | Where{ $_.Name -eq notepad }
Get-Process | ?{ $_.Threads.Count -gt 25 }
L 3 | Pi li
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
42/160
Lesson 3 | Pipeline
Sort-Object can be used to sort objects by a specified
property:
Position in pipeline is important!
Group-Object can be used to group values based onspecified properties:
Filtering, Sorting, and Grouping data | Sort and Group
41 Microsoft Confidential
Get-Process | SortWS | Select -First 10
Get-Process | Select -First 10 | SortWS
Get-Process | Sort-Object-Property WS
get-eventlog -logname system -newest 1000 | group-property entrytype
L 3 | Pi li
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
43/160
Lesson 3 | Pipeline
Text file input to pipeline
Text file output from pipeline
Key cmdlets:Get-Content
Set-Content
Add-Content
Input and Output | Text File
42 Microsoft Confidential
Get-Process | Set-Contentc:\test\processes.txt
winlogon, dnscache |Add-Contentc:\test\services.txt
Get-Contentc:\test\services.txt | Get-Service
L 3 | Pi li
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
44/160
Lesson 3 | Pipeline
CSV file input to pipeline
CSV file output from pipeline
Key cmdlets:Import-CSV
Export-CSV
Input and Output | CSV Files
43 Microsoft Confidential
Import-CSV c:\test\famous.csv | Sort Surname | Select GivenName
Get-Process | Export-CSVc:\test\processinfo.csv
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
45/160
Demonstration
Lesson 3 | Pipeline
Instructor-led demonstration
PowerShell ISEC:\pshell\part1\lesson3\lesson3-demo.txt
Microsoft Confidential44
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
46/160
Lab 3 | Pipeline (30 minutes)
Goals
Scenario
Work with PowerShell Operators
Work with PowerShell Pipeline
Filter and sort with the Pipeline
This lab will provide you hands-on experience with thePowerShell pipeline.
Microsoft Confidential45
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
47/160
Lesson 4 | Providers
Microsoft Confidential46
Lesson 4 | Providers
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
48/160
Lesson 4 | Providers
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.
Overview
47 Microsoft Confidential
Lesson 4 | Providers
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
49/160
Lesson 4 | ProvidersCmdlets
48 Microsoft Confidential
Get-Help about_providers
Get-PSProvider
Set-Location HKLM:
List installed providers
Connect to provider
Get-PSDrive List PowerShell Drive
Get help
new-psdrive name HKCR psprovider registry root HKEY_CLASSES_ROOT
Create New PSDrive:
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
50/160
Demonstration
Lesson 4 | Providers
Instructor-led demonstration
PowerShell ISEC:\pshell\part1\lesson4\lesson4-demo.txt
Microsoft Confidential49
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
51/160
Lab 4 | Providers (30 minutes)
Goals
Scenario
Work with Environment Provider
Work with Certificate Provider
Work with Registry Provider
This lab will provide you hands-on experience with PowerShellproviders.
Microsoft Confidential50
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
52/160
Lesson 5 | Variables and Type Fundamentals
Microsoft Confidential51
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
53/160
Lesson 5 | Variables and Type Fundamentals
A way of storing dynamic data
All variables begin with $
Holds object or collection of objects (array or hash table)
Variables
52 Microsoft Confidential
$MyNum = 32
$Netlogon = get-service name netlogon
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
54/160
Lesson 5 | Variables and Type Fundamentals
Use Here-String to assign multi-line string values to avariable:
PowerShell Constants
Variable whose value cannot be changed once definedWrite protected variable
Variables
53 Microsoft Confidential
$MultiLine = @
"Curiouser and curiouser!"
cried Alice (she was so muchsurprised, that for the
"@
Set-Variable name Pi value 3.142 option constant
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
55/160
Lesson 5 | Variables and Type Fundamentals
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
Variables | Types
54 Microsoft Confidential
$MyNum.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
[int]$MyNum = 32
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
56/160
Lesson 5 | Variables and Type Fundamentals
Predefined variables
Examples (use help for full list):
Automatic Variables
55 Microsoft Confidential
$Args Stores values of parameters passed to a function
$Error Stores information about the error object when an error hasoccurred 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
Get-Help about_Automatic_Variables
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
57/160
Lesson 5 | Variables and Type Fundamentals
StringExpandable double quotes
Literals single quote
Strings & Spaces
56 Microsoft Confidential
$a = Hello World!
$b = $a
$b
Hello World!
$a = Hello World!
$b = $a$b
$a
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
58/160
Lesson 5 | Variables and Type FundamentalsArrays
57 Microsoft Confidential
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
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
59/160
Lesson 5 | Variables and Type FundamentalsArrays
58 Microsoft Confidential
Create empty array:
Automatically created arrays:
Count elements in array:
Add element to array, and assign a value:
$arr1 = @()
$arr2 = a,b,c $arrProcesses = Get-Process
$arr2.count
$arr2 += d
Tip:Useful with iteration statements. Ex:
for ($a=0;$a -le $arr2.count-1;$a++){$arr2[$a]}
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
60/160
Lesson 5 | Variables and Type FundamentalsArrays | Access Elements
Access array compartments using []
Index Numbers
Object 1 Object 2 Object 3 Object 4 Object 5
$arrProcesses = Get-Process
$arrProcesses[0].name $arrProcesses[4].name
Zero-based(Index 0)
$arrProcesses[0] Value of the 1st element
$arrProcesses[-1] Value of the last element in array
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
61/160
Lesson 5 | Variables and Type Fundamentals
One-dimensional array:
Multi-dimensional array:
Arrays
60 Microsoft Confidential
Index 0 Index 1 Index 2 Index 3 Index 4
$arrProcesses = Get-Process
$arrProcesses[0]
$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
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
62/160
Lesson 5 | Variables and Type Fundamentals
Kind of array
Key-Value pair
Dictionary array form
Can access value using a corresponding label
Hash Tables
61 Microsoft Confidential
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
63/160
Lesson 5 | Variables and Type FundamentalsHash Table
62 Microsoft Confidential
Create empty hash table:
Create and populate hash table:
Add element to hash table:
$hash1 = @{}
$hash2[Type3] = Laptop
$hash2 = @{"Type1"="Desktop";"Type2"="Server"}
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
64/160
Lesson 5 | Variables and Type FundamentalsHash Table | Access Elements
63 Microsoft Confidential
Consider following hash table
Use dot notation to find the value of Type 1:$hash2.type1
$hash2 = @{"Type1"="Desktop";"Type2"="Server"}
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
65/160
Lesson 5 | Variables and Type FundamentalsWorking with Console Input-Output
64 Microsoft Confidential
Writing to ConsoleWrite-Host $a foregroundcolor green
Use either variable name orWrite-Host
$a
or
Reading From Console
$name = Read-Host Enter your nameWrite-Host "Hello $nameUse Read-Host to assign to
variable
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
66/160
Lesson 5 | Variables and Type Fundamentals
Additional output options:
Working with Console Input-Output
65 Microsoft Confidential
Out-File Sends output to a file
Out-Printer Sends output to a printer
Out-Host Default output window
Out-GridView Display output in a Grid view
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 inthe console
Out-GridView
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
67/160
Lesson 5 | Variables and Type Fundamentals
Check if file exists:
Copying files:
Moving files:
Use Rename-Item and Delete-Item to rename or delete
filesAlso works on directories
Working with Files
66 Microsoft Confidential
$Fileinfo = Test-Path C:\Windows\System32\drivers\ntfs.sys
if ($Fileinfo -eq "True") {Write-Host "File Exists"}
Copy-Item C:\setup.log d:\
Move-Item C:\setup.log d:\
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
68/160
Lesson 5 | Variables and Type Fundamentals
Error recording variable:Global setting: $Error$Error stores last 256 errorsPer cmdlet: -ErrorVariable
Error handling variables:Global setting: $ErrorActionPreferencePer cmdlet:-ErrorAction
Execution status:Last command run: $?
Applies to last commandBoolean (true = success, false = failure)
Exit Code: $LastExitCodeApplies to external command or script0 = success, anything else = failure
Error Automatic Variables
67 Microsoft Confidential
Lesson 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
69/160
Lesson 5 | Variables and Type FundamentalsErrorActionPreference Variable
68 Microsoft Confidential
Do not display messages on hostContinue processing following elements
SilentlyContinue
Display message on host
Continue processing following elements
Continue
(default)
Display message on host
Stop all processingStop
Display message on host
Prompt user if processing should continueInquire
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
70/160
Demonstration
Lesson 5 | Variables and TypeFundamentals
Instructor-led demonstration
PowerShell ISEC:\pshell\part1\lesson5\lesson5-demo.txt
Microsoft Confidential69
Lab 5 | Variables and Type Fundamentals
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
71/160
| yp(30 minutes)
Goals
Scenario
To use different types of variables forvarious operations
To create, modify and understand use of anarray
To create, modify and understand use of ahash table
This lab will provide you hands-on experience with PowerShellvariables and type fundamentals.
Microsoft Confidential70
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
72/160
Lesson 6 | Scripting
Microsoft Confidential71
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
73/160
| p gSecurity | Execution Policy | Settings
72 Microsoft Confidential
Scripts cannot be run
PowerShell interactive-mode only Default Setting
Restricted
Runs a script only if signed Signature must be trusted on local machine
(i.e. cert on local machine must sign script)
All Signed
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
RemoteSigned
All scripts from all sources can be run withoutsigningUnrestricted
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
74/160
| p gSecurity | Execution Policy | Scope
73 Microsoft Confidential
Affects current session only Stored in $PSExecutionPolicyPreference Lost upon exit of session (i.e. host process)
Process
Affects current user only Stored in HKCU registry subkeyCurrentUser
Affects all users on computer
Stored in HKLM registry subkeyLocalMachine
set-executionpolicy -scope CurrentUser -executionPolicy Unrestricted
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
75/160
| p gSecurity | Execution Policy | Cmdlets
74 Microsoft Confidential
Get-Help about_execution_policies
Get help
Get-ExecutionPolicy Current policy
Get-ExecutionPolicy -list All policies in precedence order
Scope ExecutionPolicy----- ---------------MachinePolicy UndefinedUserPolicy UndefinedProcess Undefined
CurrentUser RemoteSignedLocalMachine AllSigned
Group Policy
Effective Execution Policy
Set-ExecutionPolicy remotesigned Set PolicyRequires Elevated
PowerShell Session
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
76/160
| p gSecurity | Execution Policy | Remote Signed
75 Microsoft Confidential
NTFS
Zone Identifier
API.ps1
To run an unsigned script:
1. Save the script file on your computer.2. Click Start, click My Computer, and
locate the saved script file.3. Right-click the script file, and then click
Properties.4. Click Unblock.
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
77/160
| p gSecurity | Execution Policy | All Signed | Script Signing
76 Microsoft Confidential
$Cert
Set-AuthenticodeSignature .\test.ps1 $cert
Get-Help about_signing
Test.ps1Get-Service
Test.ps1Get-Service# SIG # Begin signature block# MIIEMwYJKoZIhvcNAQcCoIIEJDC# gjcCAQSgWzBZMDQGCisGAQQBgj
Requires self-signed
or CA cert onmachine
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
78/160
| p g
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 containspaces:
& c:\my scripts\script.ps1
Or use just filename if script is in environment path:Script.ps1
Running Scripts
77 Microsoft Confidential
$env:path=$envpath+;c:\scripts
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
79/160
| p g
Command line to execute script:
Ensure remote execution policy allows local scriptexecution:
(Or use ExecutionPolicy Bypass)
Running Scripts
78 Microsoft Confidential
powershell.exe noexit file c:\myscript.ps1
Set-Executionpolicy remotesigned
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
80/160
| p g
Requires comment:
Single line comment:
Delimited comment:
PowerShell Comments
79 Microsoft Confidential
#requires version 2
#
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
81/160
| p g
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
Statement Termination
80 Microsoft Confidential
;
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
82/160
| p gIteration Statements (Loops)
81 Microsoft Confidential
$a=1
While ($a lt 10)
{$a; $a++}
While
$a=1
Do {$a; $a++}
Until ($a gt 10)
Do Until
For ($a=1; $a lt 10; $a++){$a}
For
Foreach ($i in Get-Childitem c:\windows)
{$i.name}
For Each
$a=1
do
{write-host Loop:$a}
while ($a++ -le 5)Do While
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
83/160
BreakUse to exit loop
ContinueUse to continue a loop (i.e. print $i when divisible by 2)
Return
Return control back to caller of script/functionOptionally return output to console
ExitExit current script or shell session
Flow Control Statements
82 Microsoft Confidential
$counter=0; while ($true)
{if ($counter++ -ge 3) {break} $counter}
foreach ($i in 1..10) {If ($i % 2) {Continue} $i}
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
84/160
Other Statements
83 Microsoft Confidential
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"}
$a = "red"
switch ($a)
{
"red" {"The colour is red"}
"white"{"The colour is white"}default{"Another colour"}
}
LabeledStatements
:outer while ($true)
{:inner while ($true)
{Get-Date -displayhint time
break outer}
Get-Date displayhint date}
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
85/160
Reusable piece of code
Parameters (separated by spaces) can be passed in
Functions must be defined before they are called
Functions
84 Microsoft Confidential
function sum ([int]$a,[int]$b){
return $a + $b
}
sum 4 5
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
86/160
Scripts | Command Line Arguments
85 Microsoft Confidential
Positional Parameters$Args
$servername = $args[0]
$username = $args[1]
Passed to script with spaces
.\myscript.ps1 server1 benp
Accessed in script by $args array
Named Parameters
Param($server, $user)
Write-Host $server
Write-Host $user
Passed to script with parameter name
.\myscript.ps1 -server srv1 user benp
User parameter name directly in script
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
87/160
Profiles
86 Microsoft Confidential
StartPowerShell
Execute Profile
ScriptsProfile 1
Profile 2
Profile 3
PS:/>
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
88/160
Profile Locations
87 Microsoft Confidential
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
Scope Name
Current User, Current Host $Home\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
All Users, Current Host $PsHome\Microsoft.PowerShellISE_profile.ps1
PowerShell Console
Integrated Scripting Environment
Lesson 6 | Scripting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
89/160
Use dot sourcing to make items from script library availablein 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 fromthe console or other scopes
How to dot source a script: .\script.ps1
. .\script.ps1
c:\scripts\script.ps1. C:\scripts\script.ps1
Place dot sourced scripts in ProfileCode will be available to all child scopes in PowerShell host
Dot Sourcing & Script Libraries
88 Microsoft Confidential
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
90/160
Demonstration
Lesson 6 | Scripting
Instructor-led demonstration
PowerShell ISEC:\pshell\part1\lesson6\lesson6-demo.txt
Microsoft Confidential89
Lab 6 | Scripting (30 minutes)
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
91/160
Lab 6 | Scripting (30 minutes)
Goals
Scenario
Create PowerShell scripts
Create Functions in scriptsCreate PowerShell Profiles
This lab will provide you hands-on experience with PowerShellScripting.
Microsoft Confidential90
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
92/160
Lesson 7 | Active Directory Administration (ADSI)
Microsoft Confidential91
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
93/160
Lesson 7 | AD (ADSI)
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
94/160
ADSI Type Accelerator:
Or (from domain member):
Alternate credentials:
Note: It is not good practice to embed passwords in scripts.
Binding To AD
93 Microsoft Confidential
$domain = [ADSI]LDAP://DC=contoso,DC=com
$domain = [ADSI]
$domain = New-Object ADSI(LDAP://DC=contoso,DC=com,
CONTOSO\Administrator,Password123)
Lesson 7 | AD (ADSI)
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
95/160
Bind to DC (DNS name, NetBIOS name or IP address):
Bind to nearest GC:
Bind to specific GC:
Binding To DC/GC
94 Microsoft Confidential
[ADSI]LDAP://DC01/DC=contoso,DC=com
[ADSI]GC://DC=contoso,DC=com
[ADSI]GC://GC01/DC=contoso,DC=com
Lesson 7 | AD (ADSI)i h
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
96/160
Bind to AD:
Create searcher object instance:
Use FindAll() method to search:
Set search filter:
Directory Searcher
95 Microsoft Confidential
$domain = [ADSI]LDAP://DC=contoso,DC=com
$dirSearch = [ADSISEARCHER]$domain
$dirSearch.FindAll() All objects indomain
$dirSearch.Filter = (objectCategory=user)
All userobjects
(&(objectCategory=computer)(operatingSystem=Windows Server*))
Windows
Servercomputer
objects
Lesson 7 | AD (ADSI)O i i l U i M
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
97/160
Organizational Unit Management
96 Microsoft Confidential
CreateOU
$objRoot = [ADSI]LDAP://DC=contoso,DC=com
$objOU = $objRoot.Create(organizationalunit,OU=Finance)
$objOU.SetInfo()
ModifyOU
$objFinOU=[ADSI]LDAP://OU=Finance,DC=contoso,DC=com
$objFinOU.Put("Description", "Test OU")
$objFinOU.SetInfo()
DeleteOU
$objRoot = [ADSI]LDAP://DC=contoso,DC=com
$objOU = $objRoot.Delete(organizationalunit,OU=Finance)
Lesson 7 | AD (ADSI)U M
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
98/160
User Management
97 Microsoft Confidential
CreateUser
$objOU = [ADSI]LDAP://OU=Finance,DC=contoso,DC=com
$objUser = $objOU.Create(user,CN=FinanceUser01)$objUser.SetInfo()
ModifyUser
$objUser=[ADSI]LDAP://CN=FinanceUser01,OU=Finance,DC=contoso,DC=com
$objUser.Put(samaccountname,FinanceUser01)
$objUser.SetInfo()
DeleteUser
$objOU = [ADSI]LDAP://OU=Finance,DC=contoso,DC=com
$objOU.Delete('User', 'CN=FinanceUser01')
Enable
User
$objUser=[ADSI]LDAP://CN=FinanceUser01,OU=Finance,DC=contoso,DC=com
$objUser.SetPassword(P@ssword1)
$objUser.AccountDisabled = $false
$objUser.Setinfo()
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
99/160
Demonstration
Lesson 7 | AD (ADSI)
Instructor-led demonstration
PowerShell ISEC:\pshell\part1\lesson7\lesson7-demo.txt
Microsoft Confidential98
Lab 7 | AD (ADSI) (30 minutes)
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
100/160
Lab 7 | AD (ADSI) (30 minutes)
Goals
Scenario
Create Multiple AD Users
This lab will provide you hands-on experience administeringActive Directory usingPowerShell and ADSI.
Microsoft Confidential99
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
101/160
Lesson 8 | Active Directory Administration(cmdlets)
Microsoft Confidential100
Lesson 8 | AD (cmdlets)AD M d l | O i
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
102/160
AD PowerShell Module named ActiveDirectorySelf-contained package
Consolidates a group of cmdlets
Cmdlets used to manage one or multiple AD forests anddomains
AD Module | Overview
101 Microsoft Confidential
Lesson 8 | AD (cmdlets)AD M d l | P
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
103/160
AccountUser
Computer
Group
OUPassword Policy
Default domain password policy
Fine-grained password policy
Forest & DomainDC & FSMO
Optional Features
AD Module | Purpose
102 Microsoft Confidential
Lesson 8 | AD (cmdlets)Cmdlets
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
104/160
Cmdlets
103 Microsoft Confidential
Lesson 8 | AD (cmdlets)AD Module Prerequisites
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
105/160
At least one 2008 R2 DC in the targeted domainOR
A 2003 or 2008 DC running the Active DirectoryManagement Gateway Service
Client: Windows 7 or Windows Server 2008 R2Windows 7: Remote Server Administration Tools + AD ModuleFeature
Windows 2008 R2: AD Module via Add Features Wizard
Import and use the AD module in a PowerShell session viathe Import-Module cmdlet
AD Module Prerequisites
104 Microsoft Confidential
Lesson 8 | AD (cmdlets)Active Directory Web Services
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
106/160
Active Directory Web Services
105 Microsoft Confidential
Windows 2008 R2
ADWS
Windows 7RSAT
AD Module
Lesson 8 | AD (cmdlets)AD Management Gateway Service
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
107/160
AD Management Gateway Service
106 Microsoft Confidential
Windows 2008Windows 2003 SP2
Windows 2003 R2 SP2
AD DS
.Net 3.5 SP1
Updates
Windows 7RSAT
AD Module
Lesson 8 | AD (cmdlets)Connecting To AD
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
108/160
Binding to AD DN is required to work with AD objectsCmdlets connect to local domain using current usercredentials by default
All 76 cmdlets have credential & server parameters
To target other domains & specific servers
Global Catalog connection possible using Port #
Connecting To AD
107 Microsoft Confidential
TIP: Do not hardcode DC names in scripts!(Use Domain FQDN to discover DC)
Get-ADUser filter * -server contoso.com:3268
Lesson 8 | AD (cmdlets)Connection Reuse (New PSDrive)
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
109/160
Create PSDrive for frequently managed other domainsSaves time, avoids tedious re-entering of credentials
Increases risk
AD cmdlets inherit credentials & search base from new
PSDriveSet search base to desired path of new PSDrive
Connection Reuse (New-PSDrive)
108 Microsoft Confidential
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>
$cred = Get-Credential
Lesson 8 | AD (cmdlets)AD Provider
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
110/160
AD Provider is available once AD Module is imported:
Use common Provider cmdlets to manage AD drive:
AD Provider
109 Microsoft Confidential
Get-PSProvider
Set-location ad: dir | ft pschildname
cd "DC=contoso,DC=com
dir | ft pschildname
md OU=Test
cd OU=Test
Name Capabilities Drives-------- ---------------- --------ActiveDirectory Include... {AD}
Lesson 8 | AD (cmdlets)User Account Management | AD Cmdlets
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
111/160
User Account Management | AD Cmdlets
110 Microsoft Confidential
Create User
New-ADUser name benp -SamAccountName benp"
-GivenName ben" -Surname Pearce"
-DisplayName Ben Pearce"
Modify User Set-ADUser -Identity benp" Title Engineer"
Delete User Remove-ADUser benp
Target Single AD Object Only!
EnumerateUser
Get-ADUser -Filter * -Properties *
Get-ADUser -Filter * `
-Properties *,msDS-ReplAttributeMetaData
Lesson 8 | AD (cmdlets)Computer Account Management | AD Cmdlets
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
112/160
Computer Account Management | AD Cmdlets
111 Microsoft Confidential
Find StaleComputerAccounts
$OneYearAgo = (Get-Date).AddYears(-1)
Get-ADComputer -Filter {LastLogonTimeStamp lt`
$OneYearAgo} | Disable-ADAccount
ComputerInformation
Get-ADComputer -Filter * `
-property name,OperatingSystem,`
OperatingSystemServicePack,OperatingSystemVersion `
| Out-GridView
Lesson 8 | AD (cmdlets)Group Management | AD Cmdlets
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
113/160
Group Management | AD Cmdlets
112 Microsoft Confidential
PopulateGroup
$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 $ITUsersOR
$ITUsers | Add-ADPrincipalGroupMembership -MemberOf "IT"
Create
Group
New-ADGroup name Sales `
-Path OU=Groups,DC=Contoso,DC=com `
-GroupScope Global `
-GroupCategory Security To return groupobject
EnumerateGroup Get-ADGroupMember IT -Recursive
Nested groupmembership
Lesson 8 | AD (cmdlets)Group Management (continued) | AD Cmdlets
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
114/160
Group Management (continued) | AD Cmdlets
113 Microsoft Confidential
RemoveFrom Group
$ITUsers | Remove-ADPrincipalGroupMembership `
-MemberOf "IT
OR
Remove-ADGroupMember -Identity "IT" -members $ITUsers
$OrignalConfirmPreference = $ConfirmPreference$ConfirmPreference = "none"
Remove-ADGroupMember -Identity "IT" -members $itusers
$ConfirmPreference = $OrignalConfirmPreference
TIP: There will be a prompt to confirm.
Consider setting $ConfirmPreferenceautomatic variable in scripts.
Lesson 8 | AD (cmdlets)Multi-Valued Attributes | AD Cmdlets
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
115/160
Example:OtherTelephone
Multi-valued attribute can contain a single or multiplevalues
Each value must be uniqueUse Hash Table (Key/Value pair) i.e. @{}
Multi Valued Attributes | AD Cmdlets
114 Microsoft Confidential
UserTelephoneNumbers
New-ADUser `
-Path "ou=sales,ou=departments,dc=contoso,dc=com" `
-name "Sales1" -SamAccountName "Sales1" `-UsePrincipalName "[email protected]" `
-department "sales" `
-OtherAttributes `
@{otherTelephone="555-555-5555","123-456-7890"}
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
116/160
Demonstration
Lesson 8 | AD (cmdlets)Instructor-led demonstration
PowerShell ISEC:\pshell\part1\lesson8\lesson8-demo.txt
Microsoft Confidential115
Lab 8 | AD (cmdlets) (30 minutes)
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
117/160
| ( ) ( )
Goals
Scenario
Create Users
Modify AD ObjectsSearch AD
This lab will provide you hands-on experience with the ADModule.
Microsoft Confidential116
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
118/160
Lesson 9 | Windows ManagementInstrumentation
Microsoft Confidential117
Lesson 9 | WMIWMI in Microsoft Windows
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
119/160
WMI in Microsoft Windows
118 Microsoft Confidential
CIMV2
Namespace
Class
PowerShell
Class
Class
Virtualization
Namespace
Class
Class
Class
Lesson 9 | WMIWMI & Remote Machines | Requirements
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
120/160
WMI & Remote Machines | Requirements
119 Microsoft Confidential
PowerShellGet-WMIObject
DCOM
RPC
WMI Service
TCP/IP
DCOM
RPC
TCP/IP
PowerShell Admin Remote Machine
Other:DNSPermission
No PS required!
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
121/160
Lesson 9 | WMIGet-WmiObject | Cmdlet
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
122/160
Aliasesgwmi
Key Parameters-namespace, -class, -list, -computername
j |
121 Microsoft Confidential
Gwmi -Namespace "root\cimv2" -List | Select Name
Gwmi -Namespace "root" -Class "__NAMESPACE" | Select Name
List Namespaces
List Classes (root\cimv2 namespace)
Lesson 9 | WMIInstantiate WMI Object
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
123/160
j
122 Microsoft Confidential
$bios = Gwmi namespace root\cimv2 class Win32_Bios$bios | gm
Properties
BIOSVersion
InstallDate
$bios.BIOSVersion
Lesson 9 | WMIWMI & Remote Machines | Get-WmiObject Cmdlet
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
124/160
Key Parameters-computername, -credential
| j
123 Microsoft Confidential
$creds=Get-Credential
Gwmi win32_bios computername w7client,syddc01 credential $creds
Gwmi win32_bios computername w7client,syddc01,sydsql01OR
Gwmi win32_bios computername (Get-Content .\servers.txt)
-ComputerName
-Credential
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
125/160
Demonstration
Lesson 9 | WMI
Instructor-led demonstration
PowerShell ISEC:\pshell\part1\lesson9\lesson9-demo.txt
Microsoft Confidential124
Lab 9 | WMI (1 hour)
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
126/160
Goals
Scenario
WMI Classes & Queries
Basic filteringWMI Method Execution
This lab will provide you hands-on experience with WMI.
Microsoft Confidential125
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
127/160
Lesson 10 | Registry, Event Log and ACLManagement
Microsoft Confidential126
Lesson 10 | Registry, Event Log and ACL Management
Registry Classes
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
128/160
Microsoft.Win32.RegistryHiveRetrieve root registry keys
Microsoft.Win32.RegistryStatic 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\CurrentVersion\Run")
127 Microsoft Confidential
Lesson 10 | Registry, Event Log and ACL Management
Registry Classes | Return Root Keys
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
129/160
128 Microsoft Confidential
[enum]::GetValues(Microsoft.Win32.RegistryHive)
ClassesRootCurrentUser
LocalMachineUsers
PerformanceData
CurrentConfigDynData
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
130/160
Lesson 10 | Registry, Event Log and ACL Management
Registry Classes | Identify Instance Members
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
131/160
130 Microsoft Confidential
[Microsoft.Win32.Registry]::localmachine | Get-Member
MethodsProperties
Name
SubKeyCount
GetSubKeyNames
GetValueNames
ValueCount GetValue
OpenSubKey
Lesson 10 | Registry, Event Log and ACL Management
Registry Classes | Static and Instance Members
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
132/160
131 Microsoft Confidential
$regHKLM = [Microsoft.Win32.Registry]::localmachine
$regHKLM.GetSubKeyNames()
BCD00000000COMPONENTSHARDWARESAMSECURITY
SOFTWARESYSTEM
Lesson 10 | Registry, Event Log and ACL Management
Event Logs | Two Cmdlets
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
133/160
Get-WinEventNew and legacy event log formats
-ComputerName
Limited to reading from event logs
Get-EventLogLegacy event log formats (2003, XP)
-ComputerName
*EventLog cmdlets for new event logs, etc
132 Microsoft Confidential
New-EventLog -LogName MyEventLog -Source MySourceComputername SYDDC01
Write-EventLog -LogName MyEventLog -Source MySource -EntryType Warning `
-Category 2 -EventId 3 -Message "New Event from MySource" `
Computername SYDDC01
Lesson 10 | Registry, Event Log and ACL Management
Files, Folders & Shares | System IO Namespace
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
134/160
System.IO.FileAttributesRetrieve file & folder attributes
System.IO.FileSystemInfoCreate 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
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
135/160
134 Microsoft Confidential
$myfile = Get-Item c:\PShell\lesson7\debug.txt
$myfile.GetType()
System.IO.FileSystemInfo
$myfile | Format-List name,attributes
$myfile.attributes = archive,readonly,hidden
$myfile | Format-List name,attributes
Name : debug.txtAttributes : Archive
Name : debug.txtAttributes : ReadOnly, Hidden, Archive
Lesson 10 | Registry, Event Log and ACL Management
Files, Folders & Shares | Reading File & Folder Permissions
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
136/160
135 Microsoft Confidential
(Get-ACL c:\PShell\lesson7\debug.txt).access | fl *
FileSystemRights : FullControlAccessControlType : AllowIdentityReference :BUILTIN\Administrators
IsInherited : TrueInheritanceFlags : NonePropagationFlags : None
FileSystemRights : FullControlAccessControlType : AllowIdentityReference : NT
AUTHORITY\SYSTEMIsInherited : TrueInheritanceFlags : NonePropagationFlags : None
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
137/160
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
138/160
Demonstration
Lesson 10 | Registry, Event Log and
ACL ManagementInstructor-led demonstration
PowerShell ISEC:\pshell\part1\lesson10\lesson10-demo.txt
Microsoft Confidential137
Lab 10 | Registry, Event Log and ACL Management(30 minutes)
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
139/160
Goals
Scenario
Reading remote registry information
Searching event logsFile and Folder ACL management
This lab will provide you hands-on experience with basicwindows management.
Microsoft Confidential138
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
140/160
Lesson 11 | Remoting
Microsoft Confidential139
Lesson 11 | RemotingRemoting Technologies
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
141/160
140 Microsoft Confidential
WMI WS-MAN
RPC,
DCOM,
LDAP
WMI CmdletsPowerShell
Remoting
Raw WS-Man
(WinRM)
-ComputerName
PowerShell Remoting
Lesson 11 | RemotingWMI
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
142/160
Easiest way to remote in PowerShell v1.0
141 Microsoft Confidential
$s = Get-WmiObject win32_bios -ComputerName dc$s | format-List *
Get-WmiObject -Class -ComputerName
Lesson 11 | Remoting-ComputerName
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
143/160
Uses Application specific remoting technology(RPC, DCOM, LDAP)
142 Microsoft Confidential
-ComputerName
Get-Help * -Parameter ComputerName
$p = Get-Process -ComputerName billpc, benpc$p |ft machinename,name
Lesson 11 | RemotingWS-Management | WinRM (Microsoft)
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
144/160
Management initiative driven by DMTF
Platform independent, interoperable & industry standardmanagement solution
CIM based standards for Server and Desktop management
WS-Management (WSMAN)
143 Microsoft Confidential
WS-MAN
Lesson 11 | RemotingRequirements & Configuration
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
145/160
Local & remote machine:PowerShell 2.0.NET Framework 2.0 or later
WinRM 2.0
Get-Help:
about_Remote_FAQabout_Remote_TroubleShooting
Enable via PowerShell:Enable-PSRemoting [-force]
Runs the Set-WSManQuickConfig cmdlet
Enables all registered Windows PowerShell session configurations toreceive instructions from a remote computer
Force suppresses all user prompts
144 Microsoft Confidential
Lesson 11 | RemotingConfiguration
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
146/160
Enable via GPO:Computer Configuration\Administrative Templates\WindowsComponents\Windows Remote Management (WINRM)\WinRMService
Edit Allow automatic configuration of listenersClick Enable, Enter * against both the the Ipv4 and Ipv6 filter
Computer Configuration\Windows Settings\SecuritySettings\System Services\Windows Remote Management
Click Automatic
Computer Configuration\AdministrativeTemplates\Network\Network Connections\Windows
Firewall\Domain ProfileEdit Define inbound port exceptions
Click Enabled
Click Show
Define the port exception as 5985:TCP:*:Enabled:AllowWinRM
145 Microsoft Confidential
Lesson 11 | RemotingVerify Configuration
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
147/160
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
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
148/160
Lesson 11 | RemotingThree Methods To Use Remoting
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
149/160
I. Execute a Single Command or ScriptII. Create a Persistent Session
III. Create an Interactive Session
148 Microsoft Confidential
Lesson 11 | RemotingI. Execute a Single Command or Script
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
150/160
Invoke-CommandOne or many machines
Run a command scriptblock
Run a local script remotely -FilePath
149 Microsoft Confidential
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
Lesson 11 | RemotingII. Create a Persistent Session
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
151/160
New-PSSession
Get-PSSession
150 Microsoft Confidential
$s = New-PSSession -ComputerName Billpc
Invoke-Command -Session $s scriptblock {gps}
New-PSSession ComputerName Bill
$s = Get-PSSession Id 1
Invoke-Command session $s scriptblock {Get-Culture}
Lesson 11 | RemotingIII. Create an Interactive Session
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
152/160
Enter-PSSession (etsn)
Exit-PSSession (exit)
151 Microsoft Confidential
PS C:\> Enter-PSSession -ComputerName Billpc
[Billpc]: PS C:\Windows\system32>
$env:computername
Billpc
Lesson 11 | RemotingThrottleLimit
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
153/160
Parameter of many cmdlets including Invoke-Command-ThrottleLimit
Default to 32 concurrent connections if parameter omittedTo find cmdlets that support ThrottleLimit:
Get-Help * -parameter Throttlelimit
Use Invoke-Command to wrap cmdlets that do not nativelysupport throttling
152 Microsoft Confidential
Lesson 11 | RemotingBackground Jobs
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
154/160
153Microsoft Confidential
Job3
Job2
Job1
Job2
Job1
Run local Or remotely
Lesson 11 | RemotingStarting Background Jobs
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
155/160
Jobs can be run locally or remotely using:Start-Job:
Get-Job:
154Microsoft Confidential
Start-Job -ScriptBlock {dir path c:\windows rec}
Start-Job -Filepath c:\scripts\sample.ps1
ICM -computername s1 -scriptblock {get-eventlog system} -asjob
Id Name State HasMoreData Location Command
-- ---- ----- ----------- -------- -------
1 Job1 Running True localhost dir c:\
Lesson 11 | RemotingStarting Background Jobs
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
156/160
Receive-Job gets job results (or partial results if the job isincomplete)
Receive-Job keep prevents deleting of the job results
155Microsoft Confidential
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
Lesson 11 | RemotingJob Completion
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
157/160
Wait-JobSuppresses the PowerShell prompt until the job is complete
Stop-Job
Remove-JobThe Job must be stopped before it can be removed
156Microsoft Confidential
Get-Job name n*| Stop-Job
Stop-Job *
Lesson 11 | RemotingConstrained Session Configuration
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
158/160
Default session config allows builtin\administrators fullcontrol
Restrict local activity from remote session with a newsession config:
Register-PSSessionConfigurationAssign Execute (Invoke) permission to use custom sessionconfig to AD group:
Set-PSSessionConfiguration ShowSecurityDescriptorUI
Usage:Specify name of new session config in -ConfigurationNameparameter of remoting cmdlets
Use -Credential parameter of remoting cmdlets
157Microsoft Confidential
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
159/160
Lab 11 | Remoting (30 minutes)
-
8/10/2019 PowerShell for the IT Administrator Part 1 v1.1
160/160
Goals
Scenario
Execute remote commands
Execute commands via sessions
Use an interactive remote console
This lab will provide you hands-on experience with PowerShellremoting.