sunil phani's take on windows powershell
DESCRIPTION
learn powershell with meTRANSCRIPT
A 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
Windows powershell- course
- Cmdlets, snapins, aliases ,help - Basic cmdlets : processes , services, & event logs- Retriving mgmt info from Remote computers (WMI)
Windows powershell- course
- using variables ,objects , & Members - Understanding pipeline - Math & comparison operators- Sorting, measuring, selecting & filtering- Working with collection of objects
Windows powershell- course
- Formatting subsystem - Exporting, converting, importing & comparing - Managing active directory(and local), users, groups
etc,.- Windows powershell scripts
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
Windows powershell- intro
• The old way vs new way • An administrative engine • Existing and up coming products • Customizing shell
Windows powershell- intro
• Interim (phase 1)
Product ( eg. SQL 2005)
GUI (MMC)
exe PSH
Snap in
Service
data
Config
C.E.C
T-SQL
Windows powershell- intro
• New way (Phase 2)
Product ( eg. Ex change 2007 )
Powershell
CLI Scripts GUI
Windows powershell- intro
• Old way
Product ( eg. Ex change )
GUI (MMC)
exe WMI COM
Bat VBS
Snap in
Service
data
Config
C.E.C
Windows powershell- intro
• Ideal way
CLI GUI
Ps1 Script
APP
Any future tech
PowerShell Admin Engine
Product (any)
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)
Windows powershell- intro
Products built on Phase 1 model:
System center configuration manager (SCCM)SQL server 2008VMware EXSCitrix F5 Networks
Windows powershell- intro
Tap in existing admin products such as:
WMIADSI (Active directory services interface).NET FrameworkCOM (common object model)
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
Securing the shell
Scripting disadvantages :
• No integrity• No identity• Command hijacking (path required to run ps1)• Double click to run
Securing the shell
Execution policy : restricted all signed remote signed unrestricted
Securing the shell
script signing :
Script
PS1
EncrScript ID
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
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
Using shell for file and folder management
PSDrive:
Get-psdriveNew-psdrive www.codeplex/powershellcx
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
Command-Line Tips, Tricks, and Gotchas
Get-command (gcm):
Get-command Get-command -verb –nounGet-command -noun servicesGet-command -verb new
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
Command-lets, Snap-Ins, Aliases, and Help
Get-command (gcm):
Get-command Get-command -verb –nounGet-command -noun servicesGet-command -verb new
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)
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
Basic Command-lets for Processes, Services, and Event Logs
Services:
Get-Service(gsv)Stop-ServiceStart-ServiceSuspend-ServiceResume-ServiceRestart-ServiceSet-ServiceNew-Service (Get-Credentila)
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
Retrieving Management Information from Remote Computers
• Interdiction to WMI • Exploring WMI• Remote WMI• Alternative credentials • Filtering WMI data
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
Retrieving Management Information from Remote Computers
What is WMI
windows Exchange IIS SQL
provider provider provider provider
WMI
CIM
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
Retrieving Management Information from Remote Computers
What is WMI
WMIExplorer : (Methods , instance, properties )Eg:Win32_operatingsystem Win32_diskpartiation win32_service
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)
Retrieving Management Information from Remote Computers(mmc)
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%’
Retrieving Management Information from Remote Computers
• Interdiction to WMI • Exploring WMI• Remote WMI• Alternative credentials • Filtering WMI data
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
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()
Using Variables, Objects, and Members
Remove-Variable –name aDel $cred = Get-Credential
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
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
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
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
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
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)
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"}
Sorting, Measuring, Selecting and Filtering Objects in the Pipeline
• Sorting • Measuring• Selecting properties • Selecting subset • Filtering • Powershell work flow
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
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"}
Working with Collections of Objects in the Pipeline
• Object collections• Working with groups • Working with individuals • Foreach-object (%) & wmi
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() } }
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
Understanding and Using the Formatting Subsystem
PS Out-default
Out-hostFormat subsystem
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
Exporting, Importing, Comparing, and Converting Objects
• Exporting to csv• Importing from csv• CLIxml import/export• Comparing collections• Converting to html
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