1 / 75

CVUT-Silvie Pavlosková studentpartnerka @ gmail

Powershell. CVUT-Silvie Pavlosková studentpartnerka @ gmail.com. Mazání adresářů v textovém shellu. ls -l | grep '^d' | awk '{print " rm -r "$9}' | sh. ls.exe. brw -r--r-- 1 unixguy staff 64, 64 Jan 27 05:52 block

gregory
Download Presentation

CVUT-Silvie Pavlosková studentpartnerka @ gmail

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Powershell CVUT-Silvie Pavlosková studentpartnerka@gmail.com

  2. Mazání adresářů v textovém shellu ls -l | grep '^d' | awk '{print "rm -r "$9}' | sh ls.exe brw-r--r-- 1 unixguy staff 64, 64 Jan 27 05:52 block drwxrwx--x 2 unixguy staff 48 Jan 26 11:28 directory lrwxrwxrwx 1 unixguy staff 3 Jan 26 11:44 link -> dir -rw-rw---- 1 unixguy staff 217 Jan 26 14:08 regularfile grep.exe drwxrwx—x 2 unixguy staff 48 Jan 26 11:28 directory awk.exe rm –r directory sh.exe

  3. Mazání adresářů v PowerShellu ls | where {$_.PSIsContainer} | rm PowerShell.exe Get-ChildItem DirectoryInfo FileSystemProvider RegistryProvider Where-Object DirectoryInfo FileSystemProvider RegistryProvider FileInfo FileInfo Remove-Item

  4. PowerShell jako produktX produktem v pravém smyslu slovaShell X záložek s tlačítky…naštěstí!X„ohraničeným“ produktem s jasněvymezenými možnostmiProtože tyto jsou neomezené! Je spíše technologií a principem s obrovskýmpotenciálem Sourozenci v UNIXu se zdárně vyvíjejí k lepšímuuž 30 let… pro by nemohlPowerShell?

  5. Obsah • Roura • Práce s objekty –zeštíhlování,select,for-each • Errorhandling • Activedirectory • Psdrive,wrapper • Com a office • Vlastní Cmddlet • Providers • Hosting

  6. Nástroje kdysi • CMd.exe -externí příkaz • WindowScript Host -objektový přístup -zpřístupnění ADSI • KiXtart • Dnes Powershell! s WSH .NET!

  7. Why you are going to love PowerShell? • VBScript • DimSWBemlocator • DimobjWMIService • DimcolItems • DimobjFSO • DimobjFile • strTitle="Mailbox Report" • strComputer = “MyServer" • UserName = "" • Password = "" • strLog="Report.csv" • Set objFSO=CreateObject("Scripting.FileSystemObject") • Set objFile=objFSO.CreateTextFile(strLog,True) • strQuery="Select * from Exchange_Mailbox" • Set SWBemlocator = CreateObject("WbemScripting.SWbemLocator") • Set objWMIService = • SWBemlocator.ConnectServer(strComputer,"\root\MicrosoftExchangeV2",UserName,Password) • Set colItems = objWMIService.ExecQuery(strQuery,,48) • ForEachobjItemIncolItems • objFile.writelineobjItem.ServerName & "," &objItem.StorageGroupName&_ • "," & objItem.StoreName & "," & Chr(34) & objItem.MailboxDisplayName • Next • objFile.close

  8. Proč další nové command-line prostředí? Management UI (Exchange, SystemCenter, …) Windows PowerShell Textové shelly (bash cmd.exe csh ksh zsh ...) Skriptovací jazyky (JScript IronPython IronRuby …) ADSI COM WMI .NET Framework

  9. Powershell 2 • PowerShellRemoting: • Background Jobs: • Transactions: Start-PSTransaction New-ItemProperty -path HKCU:\Test -name NontransactedValue -value "This is a test." New-ItemProperty -path HKCU:\Test -name TransactedValue -value "This is a test." -useTransaction • ScriptCmdlets: • SteppablePipelines: BeginProcessing(), ProcessRecord() and EndProcessing()

  10. Powershell 2 • Modules(dalšíslide) • Script Debuggingbp New-PSBreakpoint –script C:\Scripts\Test.ps1 –line 4 Get-PSBreakpoint • Eventing • PS >$timer = New-Object Timers.TimerPS >$timer | Get-Member -Type Event • Get-PsEventSubscriber

  11. Powershell 2 • Windows PowerShell Integrated Scripting Environment: GUI-based PowerShell host integrated debugger, syntax highlighting, • Network File Transfer PS C:\> get-childitem *.txt | select Name | set-ftp -server myserver -user lancer • New Cmdlets: Out-GridView, • New Operators: -Split, -Join • Exception Handling with Try-Catch-Finally • Nestable Here-Strings • New APIs

  12. Remoting • Invoke-Expression -computername atl-fs-001 -command "Get-Content C:\Scripts\Test.txt"

  13. Modules • scripts with functions, scripts assemblies (DLLs) withCmdlets or providers • separate code • depend on other code • private variables or functions • as a .PSM1

  14. Out-Grid

  15. Here-strings • $x = @" "Curiouser and curiouser!" cried Alice (she was so much surprised, that for the moment she quite forgot how to speak good English); "now I'm opening out like the largest telescope that ever was! Good-bye, feet!" "@ $x

  16. Session 1 Ending Úvod do powershell

  17. Konstrukce jazyka • if;elseif;else • if(podmínka){blok příkazů} • - • eq;ne;gt;ge;lt;le;like;notlike;match;notmatch • switch • switch($pom) Hodnota1{blok } default {blok}

  18. Cykly • while • do while • do until • foreach • for

  19. Přípustné výrazy • Cmdlet-vlastní příkazy powershellu • Funkce • Spustitelný program-ipconfig • Skript \.soubor.ps1 !Set-ExecutionPolicy .psm1 • Vyhodnotitelný výraz

  20. Cmdlet • Standardizované názvy cmdletů • get-* set-* …

  21. Skripty • Bezpečnostní politika !Set-ExecutionPolicy • Alias profile.ps1 • Set –alias kde get-location • *Function now{Get-Date –format g} • Cmd.exe powershell c:\Neco\skript.ps1 • Davkovesoubory –NoLogo,-NoProfile,-Noninteractive

  22. Cmdlet • Interní příkaz *Get-Process –Nameexplo*

  23. nápověda • MAML • *get-command • *Get-Command Get-Process |Format-List • *Get-Service|Get-Member

  24. Roura-textová • Textová *Get-Process|more *Get-Process|Format-List

  25. Roura Objektová • !unix versus Powershell • Kolekce a instance • Properties jak? * Get-Service|Get-Member • Uchopenivlastnosti: *Get-Service|where($_.status –eq “sleeping”)

  26. Knihovny ve system32(PatrikMalina Microsoft Windows Powershell) • $Dir = get-Childitem C:\windows\system32 -recurse $Dir |get-Member$List = $Dir | where {$_.extension -eq ".dll"}$List | format-Table name

  27. Data ze souborů: • *Get-Content C:\Neco\textak.txt • Catsoub*.txt>>celkem.txt • *!!$obsah|Get-Member • (get-content c:\boot.ini)[5..7]

  28. XML a CSV • Vstup a výstupdat v xml • Import-Clixml

  29. Xml • $d = [xml] "<top><a>one</a><b>two</b><c>3</c></top>" • $d.top

  30. Objekty-Zeštíhlování objektů a Select-Object • Vybereme to co potřebujeme • Obecný tvar *Get-WmiObject –Class Win32_Podtrida|SelectObject property1, Description|ft * -AutoSize

  31. Zahazování objektů • Where-Object - FilterScript • $_ ……….objektproudicirourou Vice kriterií and

  32. Kolekce v roure:ForEach-Object • ForEach-Object • Obarvení *get-service | select-objectname, status | foreach-object { if ($_.status -eq "running") {write-host $_.name -foregroundcolor „black"}}

  33. Error Handling • Chybová hlašení oddělené jiným kanálem jaká chyba nastala? *$chyba=Get-ChildItem c:\temps 2>&1 *$chyba|Get-member *$Chyba.CategoryInfo *$Chyba.InvocationInfo-provokater

  34. Error • Chyby v objekt.podobě Error[0].targetobject-teckova *$LastExitCode • Parametr suspend-dava uzivatelicas na reakci stop(default) • Potlačení chyby trap: *Trap{continue}Get-Processes;Write-Host “a tak dale” • Do textaku:Start-Transcript ……

  35. LADĚNÍ • Jak skript postupuje? • *Set-PSDebug-Trace Uroven 1 a 2

  36. Prace s registry • *Dir ,ls • Get-ChildrenItem|Get-adresaru: *Get-ChildItem –include*.txt –recurse

  37. PSDrive • různédatovéstruktury *Get-ChildItem HKLM:\SYSTEM\ • Simulace: Regedit • Cd “HKML:\SOFTWARE\Microsoft\Libovolne”

  38. Zmenaregistru:Microsoft Windows PowerShell - PatrikMalina ISBN: 80-251-1816-9 *Cd HKCU:\ *MkdirKlic Hive::Microsoft.Powershell.Core\Registry::Libovolne *CdKlic *New-ItemProperty -path . -name "priznak" -PropertyType String -Value "ano"

  39. .Net • Ne zbytečné cmdlety,ale instance $cas=New-Object System.DataTime $cas.getDate() *[system.console]|Get-Member -static

  40. Wrapper-Psbase • Přístup do ActiveDirectory přes wrapper Přístup v chráněném režimu $domena.psbase.get_childern()

  41. ActiveDirectory • Databáze LDAP • Intuitivní přístup díky objektům v PS • Dotaz řetězec ve formátu LDAP-předepsaný formát • Objekt typu: “LDAP://cn=tech,ou=firma,dc=oddeleni,dc=int”

  42. Správa ActiveDirectory pomocí ADsI • $AD=[ADSI]”” “” dosazenivychozichhodnot $ou=$ad.psbase.Childern.Find(“OU=Foundation”); localpropertycache • $Novy_uzivatel.setinfo()!!!!! • PozměníPu • heslo:$Novy_uzivatel.psbase.set_password($pwd) • Zapnout: InvokeSet(“Accoundisabled”,$false) refreshcache()

  43. Info pomoci WMI • $colItems = get-wmiobject -class "XXXXXXXXXX" -namespace "XXXXXXXXXX" ` -computername "XXXXXXXXXX" –filter "XXXXXXXXXX" • Konfigurace sitovky * get-wmiobject Win32_NetworkAdapterConfiguration | Format-Table IPaddress, descr* -AutoSize • Dalsi pr:

  44. WBSCRIPT • strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer &"\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * From Win32_Process") ForEachobjItem in colItemsWscript.EchoobjItem.Name, objItem.WorkingSetSizeNext

  45. PS • $strComputer = "." $colItems = get-wmiobject -class "Win32_Process" -namespace "root\cimv2" -computername $strComputerforeach ($objItem in $colItems) { write-host $objItem.Name, $objItem.WorkingSetSize }

  46. WBScriptKoliksibereproces? • ConstadVarChar = 200 ConstMaxCharacters = 255 ConstadFldIsNullable = 32 ConstadInteger = 3 Set DataList = CreateObject("ADOR.Recordset") DataList.Fields.Append "ProcessName", adVarChar, MaxCharacters, adFldIsNullableDataList.Fields.Append "WorkingSetSize", adInteger, adFldIsNullableDataList.OpenstrComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colProcesses = objWMIService.ExecQuery("Select * From Win32_Process") ForEachobjProcess in colProcessesDataList.AddNewDataList("ProcessName") = objProcess.NameDataList("WorkingSetSize") = objProcess.WorkingSetSizeDataList.UpdateNextDataList.Sort = "WorkingSetSize" DataList.MoveFirst Do UntilDataList.EOFWscript.EchoDataList.Fields.Item("ProcessName"),_ DataList.Fields.Item("WorkingSetSize") DataList.MoveNextLoop • ActiveX Data Objects (ADO)

  47. PS • $strComputer = "." $colItems = get-wmiobject -class "Win32_Process" -namespace "root\cimv2" ` -computername $strComputer | sort "WorkingSetSize" foreach ($objItem in $colItems) { write-host $objItem.Name, $objItem.WorkingSetSize }

  48. COM • komunikace aplikací ve windows • Objektová podstata

More Related