sunil phani's take on windows powershell

58
A Sunil Phani’s take on Windows powershell

Upload: sunil-phani

Post on 24-May-2015

102 views

Category:

Technology


0 download

DESCRIPTION

learn powershell with me

TRANSCRIPT

Page 1: Sunil phani's take on windows powershell

A Sunil Phani’s take on Windows powershell

Page 2: Sunil phani's take on windows powershell

Windows powershell- course

- Why should we care?- What powershell is?- Securing the shell - File and folder management - Command line tips , tricks & gotchs

Page 3: Sunil phani's take on windows powershell

Windows powershell- course

- Cmdlets, snapins, aliases ,help - Basic cmdlets : processes , services, & event logs- Retriving mgmt info from Remote computers (WMI)

Page 4: Sunil phani's take on windows powershell

Windows powershell- course

- using variables ,objects , & Members - Understanding pipeline - Math & comparison operators- Sorting, measuring, selecting & filtering- Working with collection of objects

Page 5: Sunil phani's take on windows powershell

Windows powershell- course

- Formatting subsystem - Exporting, converting, importing & comparing - Managing active directory(and local), users, groups

etc,.- Windows powershell scripts

Page 6: Sunil phani's take on windows powershell

Windows powershell- course

- The scripting language (with just 14 key words)- Script blocks & functions - Custom blocks in functions - Err or trapping & handling- Script debugging- Regular expressions

Page 7: Sunil phani's take on windows powershell

Windows powershell- intro

• The old way vs new way • An administrative engine • Existing and up coming products • Customizing shell

Page 8: Sunil phani's take on windows powershell

Windows powershell- intro

• Interim (phase 1)

Product ( eg. SQL 2005)

GUI (MMC)

exe PSH

Snap in

Service

data

Config

C.E.C

T-SQL

Page 9: Sunil phani's take on windows powershell

Windows powershell- intro

• New way (Phase 2)

Product ( eg. Ex change 2007 )

Powershell

CLI Scripts GUI

Page 10: Sunil phani's take on windows powershell

Windows powershell- intro

• Old way

Product ( eg. Ex change )

GUI (MMC)

exe WMI COM

Bat VBS

Snap in

Service

data

Config

C.E.C

Page 11: Sunil phani's take on windows powershell

Windows powershell- intro

• Ideal way

CLI GUI

Ps1 Script

APP

Any future tech

PowerShell Admin Engine

Product (any)

Page 12: Sunil phani's take on windows powershell

Windows powershell- intro

Products build on Phase 2 model:

Exchange 2007Windows 7System center VM manager (SCVMM)System center data protection manager(SCDPM)System center common object manager (SCOM)

Page 13: Sunil phani's take on windows powershell

Windows powershell- intro

Products built on Phase 1 model:

System center configuration manager (SCCM)SQL server 2008VMware EXSCitrix F5 Networks

Page 14: Sunil phani's take on windows powershell

Windows powershell- intro

Tap in existing admin products such as:

WMIADSI (Active directory services interface).NET FrameworkCOM (common object model)

Page 15: Sunil phani's take on windows powershell

Securing the shell

• Scripts : the big concern• Execution policy • script signing• profile (and back doors )• Path required (to prevent Command hijacking )• File extension , double click etc

Page 16: Sunil phani's take on windows powershell

Securing the shell

Scripting disadvantages :

• No integrity• No identity• Command hijacking (path required to run ps1)• Double click to run

Page 17: Sunil phani's take on windows powershell

Securing the shell

Execution policy : restricted all signed remote signed unrestricted

Page 18: Sunil phani's take on windows powershell

Securing the shell

script signing :

Script

PS1

EncrScript ID

Page 19: Sunil phani's take on windows powershell

Securing the shell

script signing :

CA (PKI)

Certificate Class III

Script

Sign

Get-ExecutionPolicy Set-ExecutionPolicy Set-AuthenticodeSignature

Do u trust this CA

Is the script signed

Is the script signature intact

Page 20: Sunil phani's take on windows powershell

Using shell for file and folder management

• Common commands • Slight difference (-recursive, -filter )• Spaces & quotes • PSDrive -adding and using - differences • Redirecting out put (| Out-file )• Displaying text files

Page 21: Sunil phani's take on windows powershell

Using shell for file and folder management

PSDrive:

Get-psdriveNew-psdrive www.codeplex/powershellcx

Page 22: Sunil phani's take on windows powershell

Command-lets, Snap-Ins, Aliases, and Help

• Quotes ‘ and “• Escaping • Tab completion & cmd history• -path vs –literalpath • Transcripts (Start-Transcript)• Different consoles

Powershell

CLI

PrmilSciript

PowerGUI

PowerShell+

Diff consoles

Page 23: Sunil phani's take on windows powershell

Command-Line Tips, Tricks, and Gotchas

Get-command (gcm):

Get-command Get-command -verb –nounGet-command -noun servicesGet-command -verb new

Page 24: Sunil phani's take on windows powershell

Command-Line Tips, Tricks, and Gotchas

Cmdlets:

Verb - Singular noun

GetSet

New

EventlogChildItem ExecutionPolicy AuthenticodeSignatureLocationprocess

space

-Paramter / -

parametersspace values

-Recurse-Filter-Path-LiteralPath-Newest

space name

Security'Program

Files‘svchost

Page 25: Sunil phani's take on windows powershell

Command-lets, Snap-Ins, Aliases, and Help

Get-command (gcm):

Get-command Get-command -verb –nounGet-command -noun servicesGet-command -verb new

Page 26: Sunil phani's take on windows powershell

Command-lets, Snap-Ins, Aliases, and Help

• Aliases & cmdlets • Get-command • Ask for help • Reading the help• Parameter prompting • All about aliases (New-Alias, Export-Alias, import- -Alias)• Pssnapins (Get-PSSnapin –Registered, add-PSSnapin, Export-Console psc1 , -

PSConsoleFile)• Custom console s (& profiles)

Page 27: Sunil phani's take on windows powershell

Basic Command-lets for Processes, Services, and Event Logs

• Process (Get-Process,ps , Stop-Process kill)• Services • Eventlogs(Common Parameters, -whatif, Get-EventLog security -Newest 5 |

Format-List *, fl)• Display tips• What’s missing • Local vs remote

Page 28: Sunil phani's take on windows powershell

Basic Command-lets for Processes, Services, and Event Logs

Services:

Get-Service(gsv)Stop-ServiceStart-ServiceSuspend-ServiceResume-ServiceRestart-ServiceSet-ServiceNew-Service (Get-Credentila)

Page 29: Sunil phani's take on windows powershell

Basic Command-lets for Processes, Services, and Event Logs

Cmdlets WMI

Built on .Net framework it’s own architure Non-remoting remoting Easy complicatedBuilt-in help no built-in help

Page 30: Sunil phani's take on windows powershell

Retrieving Management Information from Remote Computers

• Interdiction to WMI • Exploring WMI• Remote WMI• Alternative credentials • Filtering WMI data

Page 31: Sunil phani's take on windows powershell

Retrieving Management Information from Remote Computers

What is WMI

DMTF(Desktop (or distributed) Management Task Force)CIM (Common Information Model ) (CIM v2)WBEM(Web Base Enterprise Model) (with IIS v5)

WMI

Page 32: Sunil phani's take on windows powershell

Retrieving Management Information from Remote Computers

What is WMI

windows Exchange IIS SQL

provider provider provider provider

WMI

CIM

Page 33: Sunil phani's take on windows powershell

Retrieving Management Information from Remote Computers

What is WMI

Namespaces (IIS,DNS) (each namespace have a class) root/CIMv2 for core OS

Classes (CIM) (each class is an manageable object ) -disk -CPU -A rec DNS -web IIS

Instance (each instance is a subset of a class object ) each object will have separate instance eg: hdd CPU

Page 34: Sunil phani's take on windows powershell

Retrieving Management Information from Remote Computers

What is WMI

WMIExplorer : (Methods , instance, properties )Eg:Win32_operatingsystem Win32_diskpartiation win32_service

Page 35: Sunil phani's take on windows powershell

Retrieving Management Information from Remote Computers

Back to powershell

Get-WmiObject(gwmi) win32_service Get-WmiObject win32_service -Filter "name like 'sh%'“gwmi win32_service -Filter "name =‘SharedAccess'“gwmi win32_operatingsystemgwmi win32_operatingsystem | fl *gwmi win32_operatingsystem -computername (or -comp) “itdse”,”swpark” gwmi win32_operatingsystem -comp (type c:\abc.txt) gwmi win32_operatingsystem -comp localhost –cre(Get-Credential)

Page 36: Sunil phani's take on windows powershell

Retrieving Management Information from Remote Computers(mmc)

Page 37: Sunil phani's take on windows powershell

Retrieving Management Information from Remote Computers

Powershell relational operators for WMI:

For all numeric and date :=>>=<<=Eg: =80For strings (with an ‘ ’)LikeEg: like name =‘svc%’

Page 38: Sunil phani's take on windows powershell

Retrieving Management Information from Remote Computers

• Interdiction to WMI • Exploring WMI• Remote WMI• Alternative credentials • Filtering WMI data

Page 39: Sunil phani's take on windows powershell

Using Variables, Objects, and Members

• What are variables• Creating, populating, displaying• Interdiction to objects• Simple objects • Viewing object members • Objects in variables • Removing variables • Example credential storage

Page 40: Sunil phani's take on windows powershell

Using Variables, Objects, and Members

New-Variable -name a -value 10$b = 3PS C:\> $b3PS C:\> $a10PS C:\> $sum = $a + $bPS C:\> $sum13$object = “hello”$object.length$object.toupper()[string]$var =“hello”$dt=get-date[string], [int], [datetime]Get-Member(gm) $dt|gm $var|gm ps | gmGet-service | gmGwmi | gm$proc = get-process$proc[0],[1]…. [-1]$proc[0] | gm$proc[0].kill()

Page 41: Sunil phani's take on windows powershell

Using Variables, Objects, and Members

Remove-Variable –name aDel $cred = Get-Credential

Page 42: Sunil phani's take on windows powershell

Understanding the Pipeline

• Why pipeline ? (it is the power in powershell) • Visualizing pipeline• Services in pipeline• Process in pipeline • Piping to file or printer• Write-output• Write-host

Page 43: Sunil phani's take on windows powershell

Understanding the Pipeline

The unix / linux way

PID Name Responding 01 xxy true 02 xxz true 03 xxx false

CMD GREP

KILL

config

Clear txt or some character file

Page 44: Sunil phani's take on windows powershell

Understanding the Pipeline

Bill gates never shamed to copy

| |

Get-services | Where-object Formit-list|

Formatted Object as o/p objects Objects after filtering

Get-services | | out-default

Page 45: Sunil phani's take on windows powershell

Understanding the Pipeline

Piping is the power in powershell Get-Service | Where-Object {$_.status -eq "running"}Get-Service | Where-Object {$_.status -eq "running“}| fl *Get-Service | Where-Object {$_.status -eq "running"} | out-default Get-Service | Where-Object {$_.status -eq "stopped" } | Set-Service -StartupType disabled –whatif Get-Service | Where-Object {$_.status -eq "stopped" } | start-serivace –whatifGet-process | stop-process –whatif

Page 46: Sunil phani's take on windows powershell

Understanding the Pipeline

BDL scenario

Eg: Get-WmiObject Win32_Directory | where-object {filetype = mp3} | del

Get-wmiobjet | Where –object {filetype = mp3} | del

Get-wmiobjet | Where –object {versiontype = xx.o} | update

Get-wmiobjet | Where –object {file = xxx} | copy

Page 47: Sunil phani's take on windows powershell

Understanding the Pipeline

Write-Out (-verb out) Get-Service | Out-File c:\sun.txtGet-Service | Out-Printer hp1005Write-output “Hello” (Writes objects to the success pipeline) Write-host “Hello” (Displays objects by using the host user interface)Write-Output "Hello" | Where-Object {$_.Length -gt 100 } (will display nothing)Write-Host "Hello" | Where-Object {$_.Length -gt 100 } (will display Hello)

Page 48: Sunil phani's take on windows powershell

Mathematical and Comparison Operators

• Basic +, -, *, /,%• Comparison operators –eq, -gt, -lt, -ge , -le(for both numiric, and string and concatenate –c

before cmp operator to obtain case sensitive cmp)• Bolin operators –and, -or , -not,• Advance math• Basic comparisons• Case sensitivity • Parsing model -command -expression

Eg: Get-WmiObject win32_service -computername localhost,sunil | where {$_.StartAuto -eq "Auto" -and $_.State -ne "Running"}

Page 49: Sunil phani's take on windows powershell

Sorting, Measuring, Selecting and Filtering Objects in the Pipeline

• Sorting • Measuring• Selecting properties • Selecting subset • Filtering • Powershell work flow

Page 50: Sunil phani's take on windows powershell

Sorting, Measuring, Selecting and Filtering Objects in the Pipeline

Sorting :Eg: get-process | Sort-Object CPU ps | Sort CPU –Descending

Measuring eg: get-process | Measure-Object gsv | Measure-Object get-process | Measure-Object -Property pm -sum -min -max –average get-service | Measure-Object -Property displayname -line -word -Character

Page 51: Sunil phani's take on windows powershell

Sorting, Measuring, Selecting and Filtering Objects in the Pipeline

Select object and where object:Eg: get-service | Select-Object displayname, dependentservices get-process | select-object ProcessName,Id,VM Get-Process | Where { $_.Name -Eq "calc" } | Kill Get-service | Where { $_.status -eq "stopped" } | Start-Service –WhatIf Get-service | Where { $_.name -eq "browser" } | Start-Service Get-WmiObject win32_service -comp "sunil" | where {$_.name -match

"browser"} Get-WmiObject win32_service -comp “itdse“,”swpark” | where {$_.name -like

"browser"}

Page 52: Sunil phani's take on windows powershell

Working with Collections of Objects in the Pipeline

• Object collections• Working with groups • Working with individuals • Foreach-object (%) & wmi

Page 53: Sunil phani's take on windows powershell

Working with Collections of Objects in the Pipeline

Object collections & foreach-object(%)

Eg: type c:\abc.txt| ForEach-Object {gwmi win32_operatingsystem -computername $_}

type c:\abc.txt| % {gwmi win32_operatingsystem -computername $_ | % { $_.reboot() } }

Page 54: Sunil phani's take on windows powershell

Understanding and Using the Formatting Subsystem

• How objects become text• Text in the console window• Formatting the sub system -format-wide -format-list -format-table• Custom columns in table • Hash table

Page 55: Sunil phani's take on windows powershell

Understanding and Using the Formatting Subsystem

PS Out-default

Out-hostFormat subsystem

Page 56: Sunil phani's take on windows powershell

Understanding and Using the Formatting Subsystem

Get-Service | Format-WideGet-Service | fw displaynameGet-Service | Fw displayname -col 3Get-Service | Format-List displayname,name,statusGet-Service | sort status | Fl displayname,name,status -GroupBy statusGet-Service | sort status| Format-Table displayname,status,DependentServices –autoGet-Service | sort status| Format-Table displayname,status,DependentServices -auto -GroupBy statusgwmi win32_logicaldisk FileSystemgwmi win32_logicaldisk | ft deviceid,volumename,sizegwmi win32_logicaldisk | ft deviceid,volumename,size,freespace –auto

PS C:\> gwmi win32_logicaldisk | ft deviceid,volumename,@{ Label="Size" ; Expression = {$_.size / 1gb } },@{ Label="Free"; Expression = {$_.freespace / 1gb } } -auto

PS C:\> gwmi win32_logicaldisk | ft deviceid,volumename,@{ Label ="Size(G)"; Expression={($_.size / 1gb) -as [int]}},@{Label ="Free(G)";Expression={($_.freespace/1gb) -as [int] } }-auto

Page 57: Sunil phani's take on windows powershell

Exporting, Importing, Comparing, and Converting Objects

• Exporting to csv• Importing from csv• CLIxml import/export• Comparing collections• Converting to html

Page 58: Sunil phani's take on windows powershell

Exporting, Importing, Comparing, and Converting Objects

Exporting /import csv,html

ps | Export-Csv c:\pro.csv$impps = import-Csv c:\pro.csv$impps[0] | ft –autoGet-Service | select -first 2 | Export-Clixml c:\serx.xmlimport-Clixml c:\serx.xmlCompare-Object (ps) (import-clixml c:\serx.xml)Diff (ps) (import-clixml c:\serx.xml) –property name

gwmi win32_service -computername localhost,sunil | where {$_.StartAuto -eq "Auto" -and $_.State -ne “Running"}| select startmode, state, name | ConvertTo-Html | Out-File c:\rep.html