This shows you the differences between two versions of the page.
— |
os:powershell [2022/01/26 11:38] (current) |
||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ======Powershell====== | ||
+ | ====Externi odkazy==== | ||
+ | [[http:// | ||
+ | [[https:// | ||
+ | [[https:// | ||
+ | ====Programy managovatelne PS==== | ||
+ | Exchange 2007+\\ | ||
+ | SQL 2008+\\ | ||
+ | System Center Data Protection\\ | ||
+ | System Center Operations Manager\\ | ||
+ | System Center Virtual Machine Manger\\ | ||
+ | atd.\\ | ||
+ | |||
+ | ====Help, debugging==== | ||
+ | get-help .. napoveda\\ | ||
+ | get-help get-member ... napoveda k get-member\\ | ||
+ | get-member $aaa ... popise objekt $aaa, informace o objekty - tridy, hodnoty, vlastnosti\\ | ||
+ | get-command notepad ... ukaze cestu k programu nebo plny nazev prikazu\\ | ||
+ | |||
+ | ====Prikazy==== | ||
+ | shell.set --enabled true ... zapnuti Bash shellu\\ | ||
+ | & spustitelny_soubor parametrt ... spusti spustitelny soubor s parametry, ktere se neinterpretuji jako PS parametry\\ | ||
+ | CALL D: | ||
+ | |||
+ | ====Nahrady z shellu/ | ||
+ | '' | ||
+ | '' | ||
+ | get-childitem | select string -Pattern " | ||
+ | '' | ||
+ | '' | ||
+ | '' | ||
+ | '' | ||
+ | '' | ||
+ | '' | ||
+ | '' | ||
+ | '' | ||
+ | '' | ||
+ | '' | ||
+ | '' | ||
+ | select | ||
+ | format-table -Property Name," | ||
+ | '' | ||
+ | ====Promenne==== | ||
+ | Promenne jsou objekty, mohou obsahovat 1-dimenzionalni promenne, ale i sady promennych | ||
+ | help variables\\ | ||
+ | get-variable ... seznam promennych\\ | ||
+ | $p | get-member ... vsechny vlastnosti a tridy objektu - popis objektu\\ | ||
+ | $PSVersionTable ... objekt obsahujici hodnotu verze \\ | ||
+ | $profile ... profilovy powershell\\ | ||
+ | $a=%%" | ||
+ | $a=%%" | ||
+ | $text=%%" | ||
+ | $d=Get-Date; | ||
+ | $a=' | ||
+ | $? ... true posledni prikaz bez chyby. False- posledni prikaz selhal\\ | ||
+ | [xml]$pes="& | ||
+ | $pes.dogs.dog[0] ... ukaze vlastnost dogs, prvni prvek z pole\\ | ||
+ | $cells = @((1, | ||
+ | $cells.length, | ||
+ | $p[5..-1] ... vsechny prvky od 5teho do posledniho\\ | ||
+ | $soubor | Get-Content C:\aaa.txt ... nacte vsechny radky do promenne typu pole\\ | ||
+ | ${C: | ||
+ | $pole=@() ... definice prazdneho pole\\ | ||
+ | $pole=1, | ||
+ | $pole+=,6 .. pridani dalsiho prvku do pole\\ | ||
+ | $asocpole = New-Object PSObject; ... definice prazdneho asociativniho pole (hashtable), | ||
+ | $asocpole=@{ " | ||
+ | $asocpole.keys, | ||
+ | $asocpole.add( ' | ||
+ | $null ... prazdny objekt\\ | ||
+ | $error ... pole chyb od startu powershellu\\ | ||
+ | $multiline=@%%" | ||
+ | vice radku%%" | ||
+ | $mycredentials = Get-Credential … interaktivni graficke okno na zadani kredenci (jmeno, heslo)\\ | ||
+ | $password = [System.Web.Security.Membership]:: | ||
+ | $secpasswd = ConvertTo-SecureString %%" | ||
+ | $mycreds = New-Object System.Management.Automation.PSCredential (%%" | ||
+ | [string]:: | ||
+ | $person = new-object PSObject ... novy prazdy objekt\\ | ||
+ | [string]:: | ||
+ | $aaa.contains(' | ||
+ | $person | add-member -type NoteProperty -Name First -Value $FirstName ... prida objektu podpromennou\\ | ||
+ | $person | Add-Member -NotePropertyName rodina -NotePropertyValue ([PSCustomObject]@{}) ... prida podobjekt\\ | ||
+ | ($aaa.GetType()).Name ... vrati typ promenne\\ | ||
+ | ====Argumenty skriptu==== | ||
+ | param([string]$soubor = " | ||
+ | $MyInvocation.MyCommand.Name ... jmeno spusteneho skriptu prave jedouciho, neco jako v Bash basename $0\\ | ||
+ | $pid ... cislo PID aktualniho procesu\\ | ||
+ | $MyInvocation.MyCommand.Path ... cela cesta spusteneho skriptu (jake $0 v bashi)\\ | ||
+ | |||
+ | |||
+ | ====Konfigurace==== | ||
+ | $profile ... profily - skripty co se vykonaji pri startu PS\\ | ||
+ | C: | ||
+ | |||
+ | ====Operatory==== | ||
+ | help operators | ||
+ | #, <# #> ... komentare\\ | ||
+ | > & | ||
+ | -and -or -not -xor ... logicke operatory\\ | ||
+ | -gt -lt -le ge -eq -like -clike ... binarni operatory (kdyz zacina na c - case sensitive, i - case insensitive)\\ | ||
+ | -cne -ne ... case-sensitive not eqal, not equal = nerovnosti\\ | ||
+ | + - * / % ... aritmeticke operatory\\ | ||
+ | () ... operatorove zavorky\\ | ||
+ | $p -is " | ||
+ | "ahoj pane" -replace " | ||
+ | " | ||
+ | " | ||
+ | (1..10) -join ";" | ||
+ | " | ||
+ | Test-Path a.txt ... vrati True/False podle toho, jestli soubor/ | ||
+ | |||
+ | ====Funkce==== | ||
+ | Funkce ulozene v souboru psm1 (modul), mohou byt naimportovany | ||
+ | Function Pozdrav ($jmeno) { write-host "ahoj $jmeno" | ||
+ | pozdrav " | ||
+ | function secti ([int]$cislo1=0, | ||
+ | |||
+ | ====rizeni toku==== | ||
+ | foreach-object ($i in $array) { Write-Host $i; $_ } ... (foreach, %) pro kazdy prvek $i v poli $array, vypis ho a vrat ho jako objekt\\ | ||
+ | if ($promenna -eq $null) { "neni definovano" | ||
+ | get-service | foreach ... jina moznost for foreach\\ | ||
+ | for ( $i=1 ; $i -lt 5 ; $i++ ) {} ... for smycka\\ | ||
+ | while ( $i -ne 2 ) {} ... while smycka\\ | ||
+ | break ... prerusi cyklus\\ | ||
+ | continue ... preskoci zbytek bloku a skoci zase na dalsi beh bloku\\ | ||
+ | & { write-out " | ||
+ | |||
+ | ====Chyby, debugging==== | ||
+ | -ErrorAction SilentlyContinue ... potlaceni chybovych hlaseni - akce jako $errorview, ale jen pro tento beh\\ | ||
+ | -errorVariable x ... chyba se ulozi do promenne $x pro tento beh prikazu i do $error\\ | ||
+ | throw " | ||
+ | trap {" | ||
+ | write-error " | ||
+ | $error ... seznam vsech chyb od startu powershellu\\ | ||
+ | $errorview ... prepinani runych vzhledu chyb\\ | ||
+ | [[https:// | ||
+ | try { dir \asd } catch { write-host Error happen: $_.Exception.Message } ... try a catch blok pro akce v pripade chyby v try bloku\\ | ||
+ | Set-PSDebug -Trace 1 ... zapne debug mod urovne 1\\ | ||
+ | Set-PSDebug -Step ... pta se me, kdyz chci skocim do interaktivniho modu prohlizet promenne, vratim se exit-em\\ | ||
+ | Set-PSDebug -off ... vypnu debug mode\\ | ||
+ | Set-StrictMode -version " | ||
+ | Set-StrictMode -version " | ||
+ | Set-StrictMode -off ... Vypne strict mode\\ | ||
+ | $host.EnterNestedprompt() ... skoci v tomto radku do debug modu ve skriptu a po exit zase pokracuje\\ | ||
+ | Set-PSBreakPoint -Command Stop-Process ... definice break pointu pro prikazu Stop-Process (jine uziti: pri zmene promenne, na radku x), h help v interaktivnim modu\\ | ||
+ | Get-PSBerakPoint ... vylistovani break pointu\\ | ||
+ | return ... konec behu smycky (for, while, ..) nebo funkce\\ | ||
+ | ====MSSQL==== | ||
+ | Import-Module SQLPS\\ | ||
+ | cd SQLSERVER:/ | ||
+ | cd SQL\ROCKET\DEFAULT\DATABASES\DATABASE\TABLES\Schema.Table\Columns\\ | ||
+ | Invoke-SqlCmd " | ||
+ | import-csv C: | ||
+ | Invoke-SqlCmd " | ||
+ | |||
+ | ====Comlet-y==== | ||
+ | add-content ... to same jako >>, podporuje parametr -encoding, prida dalsi obsah do soubory\\ | ||
+ | add-windowsfeatire / install-windowsfeature\\ | ||
+ | [[https:// | ||
+ | Compare-Object $(Get-Content a.txt) $(Get-Content b.txt) ... porovna 2 soubory\\ | ||
+ | compress-archive -Path C: | ||
+ | convertTo-html\\ | ||
+ | convertTo-csv\\ | ||
+ | Expand-Archive -Path jmeno_archivy.zip -DestinationPath C: | ||
+ | export-clixml C:\a.xml ... vystup objektu do xml\\ | ||
+ | export-clixml C:\a.xml ... vystup objektu do csv\\ | ||
+ | format-disk\\ | ||
+ | format-table ... zobrazi vystup jako tabulku (vychozi vystup)\\ | ||
+ | FT id, | ||
+ | format-list * ... (fl) naformatuje vystup jako seznam " | ||
+ | get-alias ... vypise nadefinovane aliasy\\ | ||
+ | get-command ... seznam vsech prikazu (aliasu, comandletu atd.)\\ | ||
+ | get-childitem -recurse... (dir) rekurzivni seznam souboru\\ | ||
+ | get-childitem | where { $_.Lenght -ge 10MB } ... ukaze soubory vetsi nez 10 MB\\ | ||
+ | get-childitem HKCU: | ||
+ | Get-content soubor.txt ... vypise obsah souboru\\ | ||
+ | Get-content soubor.txt -tail 20 ... vypise poslednich 20 radek ze souboru\\ | ||
+ | Get-Content [filename] | Select-Object -Last 10 ... Powershell 2.0 a starsi - tail ekvivalent\\ | ||
+ | Get-Content server.log -wait ... zobrazi a zobrazuje vsechny nove radku\\ | ||
+ | get-executionpolicy (-list)... zobrazi nastaveni pro spousteni ps skriptu\\ | ||
+ | get-help *alias* ... seznam vsech prikazu obsahujici alias v nazvu\\ | ||
+ | get-help help -full ... kompletni info o prikazu help\\ | ||
+ | get-help add-comupter -examples ... priklady\\ | ||
+ | get-help -? ... help\\ | ||
+ | get-history ... ukaze historii prikazu\\ | ||
+ | get-itemProperty HKCU: | ||
+ | get-member ... ziska vlastnosti objektu (metody, vlastnosti, atd.)\\ | ||
+ | get-process | where { $_.handles -gt 80 }\\ | ||
+ | get-psdrive ... vylistuje vsechny "ps disky" - aliasy pro ruzne objekty - disky, adresare, registry, promenne atd.</ | ||
+ | Get-Random -Min 0 -Max 256 ... nahodne cislo 0 - 265\\ | ||
+ | Get-Service | Where-Object {$_.displayName.StartsWith(" | ||
+ | get-wmiObject Win32_LogicalDisk|select DeviceID, | ||
+ | get-wmiObject Win32_OperatingSystem | fl $_.caption ... vytiskne verzi operacniho systemu\\ | ||
+ | group-Object Status ... (group) seskupi polozky z objeku pomdle sloupce Status\\ | ||
+ | Invoke-History 85 ... vyvola prikaz z historie\\ | ||
+ | Invoke-Item C: | ||
+ | Invoke-Expression ( Invoke-WebRequest " | ||
+ | import-clixml ... vypise objekty z xml zachycene pomoci export-clixml\\ | ||
+ | import-csv ... importuje z csv souboru\\ | ||
+ | Install-WindowsFeature -name Web-Server -IncludeManagementTools ... nainstaluje windows feature Web Server\\ | ||
+ | join-path ([Environment]:: | ||
+ | (Measure-Command {dir -include *.ps1 -recursive}).totalSeconds ... meri kolik sekund trva prikaz\\ | ||
+ | measure-object -property sum -minimum -maximum sum ... (measure) kdyz se presmeruji objekty do measure, umi je zmerit - pocet objekty, min, | ||
+ | new-item -path . -name new_dir -type directory ... vytvori novy adresar\\ | ||
+ | new-item -path . -name new_file -type file -value " | ||
+ | New-Item -Path $link -ItemType SymbolicLink -Value $target … (PS5) vytvori symbolicky link\\ | ||
+ | new-itemProperty \\ | ||
+ | out-gridview ... zobrazi vystup v grafickem okne, filtr a trideni k dispozici\\ | ||
+ | out-null ... /dev/null\\ | ||
+ | out-printer ... \\ | ||
+ | out-host ... standartni vystup\\ | ||
+ | out-file ... vystup do souboru, nativni prikaz pro >\\ | ||
+ | out-string -strea ... vypise objekty jako retezec\\ | ||
+ | Push-Location ... ulozi si aktualni adresar do pameti (stack)\\ | ||
+ | Push-Location -stack job1 ... pojmenovani stacku, mozno mit vice ulozenych\\ | ||
+ | Pop-Location ... vrati aktualni adresar\\ | ||
+ | read-host ... vstup z std. vstupu\\ | ||
+ | remove-Variable aaa ... dealokuje promennou\\ | ||
+ | remove-windowsfeature\\ | ||
+ | resolve-path ... konvertuje relativni cestu na absolutni\\ | ||
+ | restart-computer\\ | ||
+ | send-mailMessage ... posle mail\\ | ||
+ | set-content ... zapis do souboru, > ma spatne kodovani. Vytvori novy soubor s obsahem z argumentu\\ | ||
+ | Set-Content script.cmd '@echo ahoj' -Encoding ASCII ... Zapis do souboru, musi se pouzit ASCII, vychozi kodovani PS1 je UTF a skripty nejsou pak citelne\\ | ||
+ | set-executionpolicy remoteSigned ... povoli spousteni PowerShell skriptu z lokalni masiny\\ | ||
+ | Set-Service -Name sshd -StartupType Automatic ... aktivace sluzby - automaticky se spusti po startu\\ | ||
+ | select -property Name,VM -first 10 ... ukaze jen vlastnosti (parametry) Name a VM, jen 10 prvnich radku\\ | ||
+ | select-object | ||
+ | select-string " | ||
+ | sort -property CPU -descending ... setridi vystup podle vlastnosti\\ | ||
+ | split-path " | ||
+ | split-path " | ||
+ | start-process ... (start) spusti soubor vychozi aplikaci\\ | ||
+ | start-process powershell ... spusti powershell v novem okne\\ | ||
+ | Start-Process -NoNewWindow pomaly_skript.ps1 ... pusti skript na pozadi aktualniho PS okna/ | ||
+ | start-process " | ||
+ | -NoNewWindow ... spusti ve stejnem okne, pocka na konec programu\\ | ||
+ | & " | ||
+ | tee-object ... ulozi objekt do souboru ale i na std. vystup\\ | ||
+ | [[https:// | ||
+ | | ||
+ | ? name -eq notepad ... jiny zapis where { $_.name -eq notepad}\\ | ||
+ | write-host $profile -foregroundcoler red ... vypise na obrazovku promennou $profile cervene\\ | ||
+ | write-host " | ||
+ | |||
+ | ====Uzivatele==== | ||
+ | Get-WmiObject -Class Win32_UserAccount ... seznam vsech uzivatelu\\ | ||
+ | | ||
+ | ndProperty SID ... seznam lokalnich uzivatelu - jejich SID\\ | ||
+ | Get-LocalGroupMember -name users ... lokalnich uzivatelu\\ | ||
+ | ([Security.Principal.SecurityIdentifier]' | ||
+ | (New-Object System.Security.Principal.NTAccount(" | ||
+ | al.SecurityIdentifier]).value ... preklad uzivatele na SID\\ | ||
+ | | ||
+ | |||
+ | ====Prava k souborum==== | ||
+ | ACL - Access Control List se sklada z ACE - Access Control Entries - objekty typu Security.AccessControl.FileSystemAccessRule. Kazde ACE se sklada z 5 parametru: "Kdo - uzivatel, skupina, ..", " | ||
+ | |||
+ | get-acl C:/windows | **fl * ** ... naformatuje vystup ze ukaze vsechny pole objektu\\ | ||
+ | $acl=get-acl C:/ | ||
+ | $accessRule=new-object System.Security.AccessControl.FileSystemAccessRule " | ||
+ | $acl.AddAccessRule($accessRule) ... pridani noveho prava k existujicim pravum\\ | ||
+ | Set-Acl C: | ||
+ | New-Object Security.AccessControl.FileSystemAccessRule ' | ||
+ | |||
+ | ====Prace s registry==== | ||
+ | Set-Location HKCU: ... prepne se do virtualniho souboroveho systemu registru\\ | ||
+ | Test-Path .\Software\hsg | ||
+ | New-Item -Path HKLU: | ||
+ | get-item -path %%" | ||
+ | Get-ItemProperty -Path Registry:: | ||
+ | … seznam promennych daneho registru\\ | ||
+ | Set-ItemProperty HKLM: | ||
+ | |||
+ | ====Certifikaty, | ||
+ | Get-ChildItem Cert:\ -recursive -CodeSigningCert | where { $_.thumbprint -eq %%" | ||
+ | set-authenticodesignature -filepath | ||
+ | Import-Certificate -FilePath cert.cer -CertStoreLocation LocalComputer\Root ... import certifikatu do knihovny certifikatu\\ | ||
+ | Import-PfxCertificate -Exportable -Password " | ||
+ | Export-Certificate\\ | ||
+ | Export-PfxCertificate\\ | ||
+ | ==Zjisteni prav certifikatu== | ||
+ | < | ||
+ | $cert=Get-ChildItem CERT: | ||
+ | $rsaFile = " | ||
+ | $acl=Get-Acl -Path $rsaFile | ||
+ | $acl.Access </ | ||
+ | |||
+ | ==Pridani prav== | ||
+ | < | ||
+ | $permission=" | ||
+ | $accessRule=new-object System.Security.AccessControl.FileSystemAccessRule $permission | ||
+ | $acl.AddAccessRule($accessRule) | ||
+ | Set-Acl $rsaFile $acl | ||
+ | $acl=Get-Acl -Path $rsaFile | ||
+ | $acl.Access </ | ||
+ | |||
+ | ====vzdalene spousteni==== | ||
+ | $Host.ui.PromptForCredential(%%" | ||
+ | $cred=get-credential ... ziska interaktivne kredence\\ | ||
+ | $password=ConvertTo-Securestring -asPlainText -Force %%" | ||
+ | Invoke-Command -scriptblock { cls } -credential $cred -computername ROCKET\\ | ||
+ | |||
+ | ====Sit, firewall, networking==== | ||
+ | New-NetFirewallRule –DisplayName %%" | ||
+ | New-NetFirewallRule -Name " | ||
+ | -DisplayName " | ||
+ | -Description " | ||
+ | -Group " | ||
+ | -Program " | ||
+ | -Protocol TCP `\\ | ||
+ | -LocalPort " | ||
+ | -Action Allow `\\ | ||
+ | -Profile Domain, | ||
+ | Disable-NetFirewallRule -Name " | ||
+ | Get-NetIPConfiguration ... sitove nastaveni\\ | ||
+ | Get-NetIPAddress ... sitove adresy\\ | ||
+ | Get-NetAdapter ... seznam sitovych adapteru\\ | ||
+ | Test-NetConnection -Port 53 -ComputerName 1.2.3.4 ... test sitoveho spojeni (ping nebo jako nettcat -z)\\ | ||
+ | New-Object System.Net.Sockets.TcpClient(" | ||
+ | Set-ItemProperty -Path HKLM: | ||
+ | ====NUPKG - nuget packages==== | ||
+ | Get-Package ... seznam nainstalovanych balicku\\ | ||
+ | [[https:// | ||
+ | Find-Package .\aaa* | [[https:// | ||
+ | |||
+ | ====Moduly==== | ||
+ | Get-module -listavailable ... seznam vsech nainstalovanych modulu, vcetne starych verzi, vcetne cest\\ | ||
+ | Get-InstalledModule ... seznam nainstalovanych modulu - posledni verze\\ | ||
+ | Import-Module C: | ||
+ | Import-module SQLPS ... nacte modul pro praci MS SQL server\\ | ||
+ | Install-Module AAA -RequiredVersion 0.4 ... instalace konkretni verze\\ | ||
+ | Uninstall-Module AAA ... odinstalace posledni verze modulu AAA\ | ||
+ | get-command -module SQLPS ... ukaze prikazy modulu SQLPS\\ | ||
+ | Register-PSRepository -Name FileShareRepo -SourceLocation ' | ||
+ | Publish-Module -Name TestModule -Repository FileShareRepo ... ulozi modul do repozitare\\ | ||
+ | Get-PSRepository -Name FileShareRepo ... informace o repozitari\\ | ||
+ | Find-Module -repository FileShareRepo ... zobrazi balicky v repozitari\\ | ||
+ | Unregister-PSRepository -Name FileShareRepo ... odregistruje repozitar\\ | ||
+ | |||
+ | ====Active Directory==== | ||
+ | Import-Module ActiveDirectory\\ | ||
+ | |||
+ | cd AD:\\\ | ||
+ | cd " | ||
+ | cd " | ||
+ | dir | where {$_.name -eq tomas} | select *, | ||
+ | remove-ADUser tomas\\ | ||
+ | $secure=ConvertTo-SecureString " | ||
+ | new-ADUser franta -AccountPassword $sercure -Enabled $true\\\\ | ||
+ | Invoke-SqlCmd -hostname . -Database AdventureWorks2012 -query " | ||
+ | \\ | ||
+ | Get-ADGroup Skupina ... (portebuje RSAT) informace o AD skupine\\ | ||
+ | Get-ADUser TLipensky ... (portebuje RSAT) informace o AD uzivateli\\ | ||
+ | [[https:// | ||
+ | Add-Computer -DomainName # | ||
+ | ====COM integrace - COM objekty==== | ||
+ | $object=New-Object -comObject WScript.Shell\\ | ||
+ | $object|Get-Member -memberType *Method\\ | ||
+ | $path=[system.environment]:: | ||
+ | $link=$wshell.CreateShortcut(" | ||
+ | $link | get-member\\ | ||
+ | $link.TargetPath=' | ||
+ | $link.Description=' | ||
+ | $link.WorkingDirectory=$profile\\ | ||
+ | $link.IconLocation=' | ||
+ | $link.save() ... ulozeni linku z objektu, pokud nenadefinujeme povinne parametry, tak bude chyba\\ | ||
+ | \\ | ||
+ | $IE=New-Object -ComObject ' | ||
+ | Eie.navigate(" | ||
+ | $ie.visible=$true\\ | ||
+ | $ie.quit\\ | ||
+ | \\ | ||
+ | $o=New-Object -ComObject Shell.Application\\ | ||
+ | $o.ToggleDesktop() ... minimalizace vsech oken\\ | ||
+ | \\ | ||
+ | [threading.thread]:: | ||
+ | $Excel=New-Object -Com Excel.Application\\ | ||
+ | $excel.visible=$true\\ | ||
+ | $excel.workbook.add()\\ | ||
+ | |||
+ | ====WMI==== | ||
+ | Informace poskytuje WMI sluzba (Windows Management Instrumentation) | ||
+ | Get-WmiObject -list\\ | ||
+ | Get-WmiObject Win32_OperatingSystem | fl *\\ | ||
+ | Get-WmiObject Win32_Process | fl * ... seznam procesu vcetne plneho prikazu\\ | ||
+ | Get-WmiObject Win32_Process -Filter "name = ' | ||
+ | Get-WmiObject Win32_NetworkAdapter | fl *\\ | ||
+ | Get-CimInstance CIM-Processor\\ | ||
+ | Get-CimInstance CIM-Processor -ComputerName .\\ | ||
+ | Get-CimInstance Win32_Process -Filter "name = ' | ||
+ | Get-WmiObject -class Win32_LogicalDisk\\ | ||
+ | Get-WmiObject -Query " | ||
+ | |||
+ | ====Remoting==== | ||
+ | WinRM sluzba, jede na HTTP/HTTPS a SOAP, potrebuje PSv2, .NET2 a vyssi, ..., HTTP jede na portu 5985, HTTPS na portu 5986\\ | ||
+ | Elegantni cesta jak nastavit WinRM remoting (neomezeny) : [[https:// | ||
+ | |||
+ | Enable-PSRemoting ... spusti Set-WSManQuickConfig a ruzna pravidla na povoleni\\ | ||
+ | WinRM quickconfig ... Win prikaz - nastavi listener, dovoli administratorum pristup\\ | ||
+ | Set-WSManQuickConfig ... to same, ale z PS\\ | ||
+ | winrm get winrm/ | ||
+ | Set-Item WSMan: | ||
+ | new-pssession ... vytvori noe pripojeni, ale nepripoji se\\ | ||
+ | enter-pssession ... vytvori a pripoji se\\ | ||
+ | $s=new-session|enter-session ... pripoji se k existujicimu spojeni\\ | ||
+ | get-pssession ... seznam PS spojeni\\ | ||
+ | exit-pssession ... vyskoci ze spojeni\\ | ||
+ | remove-pssession ... ukonci spojeni\\ | ||
+ | [[https:// | ||
+ | Invoke-Command -Session $s -ScriptBlock {Get-Culture} ... spusti prikaz v otevrene session $s (pomoci new-session)\\ | ||
+ | ====Jobs==== | ||
+ | Start-Job -name NewJob -Scriptblock {Get-Service} ... spusti ulohu na pozadi, napr. na jinem pocitaci\\ | ||
+ | Get-Job ... informace of ulohach\\ | ||
+ | Receive-Job -name newJob ... obdrzi vysledky - objekty z bufferu, muze to byt job ze scheudleru, vysledky se ulozi na pocitaci v xml\\ | ||
+ | Receive-Job -name newJob -keep ... vysledky se nechaji na pocitaci, neprepisi se | ||
+ | Remove-Job -name newJob ... smaze vysledky\\ | ||
+ | Get-SchedulerJob\\ | ||
+ | Set-SchedulerJob\\ | ||
+ | Set-ScheduledTask\\ | ||
+ | get-SchedulerTask\\ | ||
+ | $akce = New-ScheduledTaskAction -Execute ' | ||
+ | $spoustec = New-ScheduledTaskTrigger -Once -At 9am -User " | ||
+ | Register-ScheduledTask -Action $akce -Trigger $spoustec -TaskName " | ||
+ | Start-ScheduledTask -TaskName " | ||
+ | Get-ScheduledTask -TaskName " | ||
+ | ====Logovani, | ||
+ | [[https:// | ||
+ | |||
+ | ====Regularni vyrazy==== | ||
+ | "cislo 00420 111 222 333" - match " | ||
+ | $matches ... vysledek hledani\\ | ||
+ | $text -replace " | ||
+ | |||
+ | ====prace s xml==== | ||
+ | [xml]$xml="< | ||
+ | $xml2=[xml] (Get-Content | ||
+ | $xml.a.b.text=" | ||
+ | $xml.save(" | ||
+ | ($xml | Select-Xml -XPath / | ||
+ | Select-Xml -xml $xml -XPath //c | foreach { $_.node } … obsah vsech nodu\\ | ||
+ | Select-Xml -xml $xml -XPath "/ | ||
+ | (Select-Xml -xml $xml -XPath "// | ||
+ | |||
+ | |||
+ | ====prace s JSON==== | ||
+ | $structure = get-content a.json | ConvertFrom-Json ... prevede JSON na pametovou strukturu\\ | ||
+ | $structure.neco.z.jasona = 35 … zmena struktury, ze ktere pak provedeme json\\ | ||
+ | ConvertTo-Json -InputObject $structure\\ | ||
+ | |||
+ | ====base64==== | ||
+ | [Convert]:: | ||
+ | [System.Text.Encoding]:: | ||
+ | |||
+ | ====HTTP requesty==== | ||
+ | $base64AuthInfo = [Convert]:: | ||
+ | Invoke-RestMethod -Headers @{Authorization=(" | ||
+ | |||
+ | $pwd = ConvertTo-SecureString " | ||
+ | $cred = New-Object Management.Automation.PSCredential (' | ||
+ | Invoke-RestMethod ' | ||
+ | |||
+ | [Net.ServicePointManager]:: | ||
+ | |||
+ | |||
+ | ====Eventlog (Windows udalosti)==== | ||
+ | Get-Eventlog -list ... stara metoda, pomale, ne vsechny eventy, funguje vsude\\ | ||
+ | Get-EventLog Application | where { $_.EventType -eq " | ||
+ | Get-EventLog Security -ComputerName $(hostname) -Source Microsoft-Windows-Security-Auditing | Where {$_.InstanceID -like " | ||
+ | Get-WinEvent -ListLog *operational*\\ | ||
+ | [xml]$filter=Get-Content(" | ||
+ | Get-WinEvent -filterXml $filter\\ | ||
+ | Get-WinEvent -ListLog * |Where-Object {$_.RecordCount} ... seznam event log slozek a pocty eventu\\ | ||
+ | |||
+ | ====Statistiky systemu (metriky)==== | ||
+ | get-counter ... zakladni statistiky systemu (CPU, pamet)\\ | ||
+ | Get-Counter -listSet * | where { $_.CounterSetName -like " | ||
+ | get-Counter -Counter " | ||
+ | get-counter -Counter "\.NET CLR Memory(*)\# Gen 0 Collections" | ||
+ | Get-Counter -ListSet * | Select-Object CounterSetName, | ||
+ | |||
+ | ====Disky, operace, enkrypce - BitLocker==== | ||
+ | New-StoragePool -FriendlyName storagepool1 -StorageSubsystemFriendlyName " | ||
+ | New-VirtualDisk -StoragePoolFriendlyName storagepool1 -FriendlyName virtualdisk1 -Size 2046GB -ResiliencySettingName Simple -ProvisioningType Fixed ... vytvori z poolu disku novy virtualni disk\\ | ||
+ | Initialize-Disk -VirtualDisk (Get-VirtualDisk -FriendlyName virtualdisk1) ... iniciuje novy disk\\ | ||
+ | New-Partition -DiskNumber 4 -UseMaximumSize -DriveLetter Z ... namontuje novy disk za disk Z:\\ | ||
+ | Suspend-BitLocker C: ... docasne vypne ochranu disku\\ | ||
+ | Resume-BitLocker C: ... opet aktivuje ochranu disku\\ | ||
+ | ====Sanpin-y==== | ||
+ | Stare moduly v PS v.1. V novych verzich je nahradily moduly, ale snapiny jsou furt podporovane | ||
+ | |||
+ | ====Moduly==== | ||
+ | |||
+ | ====.NET integrace==== | ||
+ | PowerShell is .NET aplikace (.NET alternativa Javy na Win platformach) | ||
+ | |||
+ | $p=new-object System.Net.NetworkInformation.Ping ... iniciace noveho objektu dane tridy\\ | ||
+ | $p.send ... help k metode\\ | ||
+ | $a=$p.send(' | ||
+ | $a.Address.IPAddressToString ... vypise vlastnost objektu - ipadresu\\ | ||
+ | $message=New-Object System.Net.Mail.MailMessage(From, | ||
+ | $message.Subject=" | ||
+ | $message.Body=" | ||
+ | $attachment=New-Object System.Net.Mail.Attachment(" | ||
+ | $message.Attachments.Add($attachment)\\ | ||
+ | $client=New-Object System.Net.Mail.SmtpClient($SMTPServer)\\ | ||
+ | $client.Send($message)\\ | ||
+ | [system.math]:: | ||
+ | [Math] | get-member - static -membertype ... ziskani vlastnosti a metod staticke tridy\\ | ||
+ | [System.Math]:: | ||
+ | [Environment]:: | ||
+ | [System.IO.Path]:: | ||
+ | [System.IO.Path] | gm -static ... seznam statickych metod a vlastnosti\\ | ||
+ | [[https:// | ||
+ | System.Text ... prace s texty\\ | ||
+ | System.Data ... prace z databazemi\\ | ||
+ | System.Threading\\ | ||
+ | System.Collections ... prace s poli, asoc. poli atd\\ | ||
+ | System.Xml ... prace s xml\\ | ||
+ | System.Net ... prace se siti\\ | ||
+ | System.Security ... prace s bezpecnosti - enkrypce, dekrypce, certifikaty\\ | ||
+ | System.Globalization ... lokalizace\\ | ||
+ | $a=New-Object System.Globalization.Cultureinfo(" | ||
+ | $b=13.45; $b.toString(" | ||
+ | $b.toString(" | ||
+ | $a.NumberFormat.CurrencySymbol=" | ||
+ | [System.IO.Path]:: | ||
+ | \\ | ||
+ | Add-Type -assembly " | ||
+ | [io.compression.zipfile]:: | ||
+ | [Reflection.Assembly]:: | ||
+ | $z=[IO.Compression.ZipFile]:: | ||
+ | [System.IO.Compression.ZipArchive]$ZipFile = [System.IO.Compression.ZipFile]:: | ||
+ | [System.IO.Compression.ZipFileExtensions]:: | ||
+ | $ZipFile.Dispose() … zavre archiv\\ | ||
+ | |||
+ | ====Priklady==== | ||
+ | Get-Mailbox | Sort Size | Select -first 100 | Move-Mailbox Server2 | ||
+ | |||
+ | == Test syntaxe powershell skriptu == | ||
+ | < | ||
+ | $errors = $null | ||
+ | $null = [System.Management.Automation.PSParser]:: | ||
+ | |||
+ | ==Kultura a lokalizace== | ||
+ | [[https:// | ||
+ | Add-Type -AssemblyName " | ||
+ | [Reflection.Assembly]:: | ||
+ | [System.Globalization.CultureInfo]:: | ||
+ | $cbuilder = [System.Globalization.CultureAndRegionInfoBuilder]:: | ||
+ | [System.Globalization.CultureAndRegionInfoBuilder]:: | ||
+ | $BaseCulture = [cultureinfo]:: | ||
+ | $BaseRegion = New-Object System.Globalization.RegionInfo ' | ||
+ | $CultureBuilder = New-Object System.Globalization.CultureAndRegionInfoBuilder @(' | ||
+ | $CultureBuilder.LoadDataFromCultureInfo($BaseCulture) ... naimportovani kultury\\ | ||
+ | $CultureBuilder.LoadDataFromRegionInfo($BaseRegion) ... naimportovani regionu\\ | ||
+ | $CultureBuilder.save(C: | ||
+ | |||
+ | ====Powershell scripting - ps1==== | ||
+ | |||
+ | Write-Host " | ||
+ | write-output " | ||
+ | [console]:: | ||
+ | [system.io.file]:: | ||
+ | Get-Content a.txt ... vypise obsah souboru\\ | ||
+ | Get-Content a.txt -totalcount 2 ... vypise prvni 2 radky souboru\\ | ||
+ | Get-Content a.txt -last 2 ... vypise posledni 2 radky souboru\\ | ||
+ | |||
+ | ====Promenne==== | ||
+ | $aaa=" | ||
+ | $heslo=$(Read-Host "Vloz heslo: ") ... nacte retezec z klavesnice\\ | ||
+ | $PSVersionTable.PSVersion ... verze Powershellu\\ | ||
+ | [System.Environment]:: | ||
+ | [Environment]:: | ||
+ | $[[https:// | ||
+ | $aaa=" | ||
+ | $ccc=$aaa.Split(" | ||
+ | Write-Host $ccc[0] | ||
+ | forEach ($line in (Get-Content a.txt) ) { $items=$line.split("," | ||
+ | $password=$(Read-Host -AsSecureString "Enter password: ") ... nacteni hesla jako secure string\\ | ||
+ | $BSTR = [System.Runtime.InteropServices.Marshal]:: | ||
+ | $PlainPassword = [System.Runtime.InteropServices.Marshal]:: | ||
+ | \\ | ||
+ | $directory=$( Read-Host "Enter directory with dsx files: ") | ||
+ | $files = Get-ChildItem $directory | ||
+ | for ($i=0; $i -lt $files.count; | ||
+ | $filename=$files[$i].FullName | ||
+ | Write-Host $filename | ||
+ | if ( $filename -like " | ||
+ | if ( $filename -contains " | ||
+ | } | ||
+ | Invoke-Expression " | ||
+ | |||
+ | ====Scenare==== | ||
+ | ===Preposilani paketu - rerouting=== | ||
+ | Install-WindowsFeature RemoteAccess -IncludeManagementTools\\ | ||
+ | Install-WindowsFeature -Name Routing -IncludeManagementTools -IncludeAllSubFeature\\ | ||
+ | Install-WindowsFeature -Name " | ||
+ | Install-RemoteAccess -VpnType RoutingOnly\\ | ||
+ | Get-NetAdapter | Set-NetIPInterface -Forwarding Enabled\\ |