Sunil phani's take on windows powershell

433 views

Published on

learn powershell with me

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
433
On SlideShare
0
From Embeds
0
Number of Embeds
8
Actions
Shares
0
Downloads
8
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Sunil phani's take on windows powershell

  1. 1. A Sunil Phani’s take on Windows powershell
  2. 2. Windows powershell- course - Why should we care? What powershell is? Securing the shell File and folder management Command line tips , tricks & gotchs
  3. 3. Windows powershell- course - Cmdlets, snapins, aliases ,help - Basic cmdlets : processes , services, & event logs - Retriving mgmt info from Remote computers (WMI)
  4. 4. Windows powershell- course - using variables ,objects , & Members Understanding pipeline Math & comparison operators Sorting, measuring, selecting & filtering Working with collection of objects
  5. 5. Windows powershell- course - Formatting subsystem - Exporting, converting, importing & comparing - Managing active directory(and local), users, groups etc,. - Windows powershell scripts
  6. 6. 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
  7. 7. Windows powershell- intro • • • • The old way vs new way An administrative engine Existing and up coming products Customizing shell
  8. 8. Windows powershell- intro • Interim (phase 1) C.E.C Snap in T-SQL GUI (MMC) Service Product ( eg. SQL 2005) exe data PSH Config
  9. 9. Windows powershell- intro • New way (Phase 2) CLI Scripts GUI Powershell Product ( eg. Ex change 2007 )
  10. 10. Windows powershell- intro • Old way C.E.C Snap in GUI (MMC) Service Product ( eg. Ex change ) exe Bat WMI data COM VBS Config
  11. 11. Windows powershell- intro • Ideal way CLI Ps1 Script GUI PowerShell Admin Engine APP Product (any) Any future tech
  12. 12. Windows powershell- intro Products build on Phase 2 model: Exchange 2007 Windows 7 System center VM manager (SCVMM) System center data protection manager(SCDPM) System center common object manager (SCOM)
  13. 13. Windows powershell- intro Products built on Phase 1 model: System center configuration manager (SCCM) SQL server 2008 VMware EXS Citrix F5 Networks
  14. 14. Windows powershell- intro Tap in existing admin products such as: WMI ADSI (Active directory services interface) .NET Framework COM (common object model)
  15. 15. 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
  16. 16. Securing the shell Scripting disadvantages : • • • • No integrity No identity Command hijacking (path required to run ps1) Double click to run
  17. 17. Securing the shell Execution policy :     restricted all signed remote signed unrestricted
  18. 18. Securing the shell script signing : Script PS1 ID Encr Script
  19. 19. Securing the shell script signing : CA Certificate (PKI) Class III  Is the script signed Script Sign Get-ExecutionPolicy Set-ExecutionPolicy Set-AuthenticodeSignature  Is the script signature intact  Do u trust this CA
  20. 20. 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
  21. 21. Using shell for file and folder management PSDrive: Get-psdrive New-psdrive www.codeplex/powershellcx
  22. 22. Command-lets, Snap-Ins, Aliases, and Help • • • • • • Quotes ‘ and “ Escaping Tab completion & cmd history -path vs –literalpath Transcripts (Start-Transcript) Different consoles Diff consoles CLI PrmilSciript Power shell PowerGUI PowerShell+
  23. 23. Command-Line Tips, Tricks, and Gotchas Get-command (gcm): Get-command Get-command -verb –noun Get-command -noun services Get-command -verb new
  24. 24. Command-Line Tips, Tricks, and Gotchas Cmdlets: Verb Get Set New - Singular noun Eventlog ChildItem ExecutionPolicy AuthenticodeSignature Location process space name Security 'Program Files‘ svchost space -Paramter / -parameters -Recurse -Filter -Path -LiteralPath -Newest space values
  25. 25. Command-lets, Snap-Ins, Aliases, and Help Get-command (gcm): Get-command Get-command -verb –noun Get-command -noun services Get-command -verb new
  26. 26. 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)
  27. 27. 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
  28. 28. Basic Command-lets for Processes, Services, and Event Logs Services: Get-Service(gsv) Stop-Service Start-Service Suspend-Service Resume-Service Restart-Service Set-Service New-Service (Get-Credentila)
  29. 29. Basic Command-lets for Processes, Services, and Event Logs Cmdlets Built on .Net framework Non-remoting Easy Built-in help WMI it’s own architure remoting complicated no built-in help
  30. 30. Retrieving Management Information from Remote Computers • • • • • Interdiction to WMI Exploring WMI Remote WMI Alternative credentials Filtering WMI data
  31. 31. 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
  32. 32. Retrieving Management Information from Remote Computers What is WMI WMI CIM provider provider provider provider windows Exchange IIS SQL
  33. 33. 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
  34. 34. Retrieving Management Information from Remote Computers What is WMI WMIExplorer : (Methods , instance, properties ) Eg: Win32_operatingsystem Win32_diskpartiation win32_service
  35. 35. 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_operatingsystem gwmi 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)
  36. 36. Retrieving Management Information from Remote Computers(mmc)
  37. 37. Retrieving Management Information from Remote Computers Powershell relational operators for WMI: For all numeric and date : = > >= < <= Eg: =80 For strings (with an ‘ ’) Like Eg: like name =‘svc%’
  38. 38. Retrieving Management Information from Remote Computers • • • • • Interdiction to WMI Exploring WMI Remote WMI Alternative credentials Filtering WMI data
  39. 39. 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
  40. 40. Using Variables, Objects, and Members New-Variable -name a -value 10 $b = 3 PS C:> $b 3 PS C:> $a 10 PS C:> $sum = $a + $b PS C:> $sum 13 $object = “hello” $object.length $object.toupper() [string]$var =“hello” $dt=get-date [string], [int], [datetime] Get-Member(gm) $dt|gm $var|gm ps | gm Get-service | gm Gwmi | gm $proc = get-process $proc*0+,*1+…. *-1] $proc[0] | gm $proc[0].kill()
  41. 41. Using Variables, Objects, and Members Remove-Variable –name a Del $cred = Get-Credential
  42. 42. 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
  43. 43. Understanding the Pipeline The unix / linux way Clear txt or some character file CMD GREP PID Name Responding 01 xxy 02 xxz 03 xxx config true true false KILL
  44. 44. Understanding the Pipeline Bill gates never shamed to copy Get-services | Where-object | Objects after filtering | Formit-list | objects Get-services | | out-default Formatted Object as o/p
  45. 45. 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 –whatif Get-process | stop-process –whatif
  46. 46. Understanding the Pipeline BDL scenario Get-wmiobjet | Where –object {filetype = mp3} | del Get-wmiobjet | Where –object {versiontype = xx.o} | update Get-wmiobjet | Where –object {file = xxx} | copy Eg: Get-WmiObject Win32_Directory | where-object {filetype = mp3} | del
  47. 47. Understanding the Pipeline Write-Out (-verb out) Get-Service | Out-File c:sun.txt Get-Service | Out-Printer hp1005 Write-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)
  48. 48. 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"}
  49. 49. Sorting, Measuring, Selecting and Filtering Objects in the Pipeline • • • • • • Sorting Measuring Selecting properties Selecting subset Filtering Powershell work flow
  50. 50. 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
  51. 51. 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"}
  52. 52. Working with Collections of Objects in the Pipeline • • • • Object collections Working with groups Working with individuals Foreach-object (%) & wmi
  53. 53. 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() } }
  54. 54. 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
  55. 55. Understanding and Using the Formatting Subsystem PS Out-default Format subsystem Out-host
  56. 56. Understanding and Using the Formatting Subsystem Get-Service | Format-Wide Get-Service | fw displayname Get-Service | Fw displayname -col 3 Get-Service | Format-List displayname,name,status Get-Service | sort status | Fl displayname,name,status -GroupBy status Get-Service | sort status| Format-Table displayname,status,DependentServices –auto Get-Service | sort status| Format-Table displayname,status,DependentServices -auto -GroupBy status gwmi win32_logicaldisk FileSystem gwmi win32_logicaldisk | ft deviceid,volumename,size gwmi 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
  57. 57. Exporting, Importing, Comparing, and Converting Objects • • • • • Exporting to csv Importing from csv CLIxml import/export Comparing collections Converting to html
  58. 58. 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 –auto Get-Service | select -first 2 | Export-Clixml c:serx.xml import-Clixml c:serx.xml Compare-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 | ConvertToHtml | Out-File c:rep.html

×