ING Services Polska, ING Bank Śląski oraz IBM zapraszają studentów kierunków informatycznych do uczestnictwa w prestiżowym programie Corporate Readiness Certificate (CRC) realizowanym w Gliwicach, Katowicach i Wrocławiu.
http://www.ingservicespolska.pl/pl/aktualnosci,10/841,studencie-zapisz-sie-do-programu-crc.html
W ramach programu CRC będę miał przyjemność poprowadzić wykłady poświęcone automatyzacji systemu Windows z wykorzystaniem języka skryptowego Powershell. Podczas pierwszych zajęć, które odbędą się… w Prima Aprilis opowiem o:
- tym, co to jest i jak powstał Powershell
- różnicach między językami skryptowymi znanymi ze świata Unix, a obiektowym Powershellem
- narzędziach, w których można tworzyć skrypty
- podstawowych komendach Powershell
- tworzeniu potoków
- sortowaniu, filtrowaniu, iteracji…
Skrypt poniżej:
#Version $PSVersionTable.psversion #Comments are also important ;) <# Block comments for more text... #> #Some cmdlets Get-Service cls Get-Service -Name bits cls Get-Service -Name b* cls Get-Service | Out-File c:\temp\services.txt cls #More complicated example Get-WmiObject -Class Win32_logicalDisk -Filter "DeviceId='C:'" -ComputerName localhost | Select-Object -Property Deviceid, @{n="SizeGB";e={$_.Size/1GB -as [int]}},@{n='FreeGB';e={$_.Freespace/1gb -as[int]}} cls #--- #Messages echo "Hello" echo 'Hello' echo Hello print Hello Write 'Hello' Write-Host 'Hello' Write-Host 'Hello' -BackgroundColor Red Write-Output 'Hello' #Do not use Write-Host write-host 'abc' | gm Write-Output 'abc' | gm Write-warning 'Uwaga urzadzenie elektryczne' Write-Error "HALT" Write-Host "What's your name?" $name = Read-Host Write-Host "Hello $name" $years = Read-Host -Prompt "How old are you?" Write-Host "So ISP is $($years-10) younger!" #--- #Start in powershell window! Start-Transcript 'c:\temp\day_1.txt' Get-Service -Name b* Get-Date echo $env:COMPUTERNAME Stop-Transcript 'c:\temp\day_1.txt' notepad c:\temp\day_1.txt #--- #Aliases Get-PSDrive Dir Alias: Get-Alias cd hklm c: set-alias -Name l -Value dir l remove-item alias:\l #--- #Version check $PSVersionTable #--- #Help in ISE Get-EventLog –Logname system –Newest 3 Get-Help Get-EventLog -ShowWindow Get-Help about_ get-help about_* Get-Help -Category some_stupid_text Get-Help -Category Provider #--- #Get-Command Get-Command -Noun alias Get-Command -Verb get Get-Command "*Service*" Get-Command "*Service" Get-Command "Service*" Get-Command –Module NetAdapter get-module -ListAvailable get-command -noun module Import-Module -Name ISE get-command -module ISE Get-IseSnippet get-command -module sqlps #--- get-help *service* get-help g*service* Get-Verb #Get-Module Get-Module -ListAvailable Update-Help #Multiple value parameter Get-EventLog -LogName Application -ComputerName Cantor8,Cantor9 -Newest 3 Get-Content c:\temp\computrs.txt Get-EventLog -LogName Application -ComputerName (Get-Content c:\temp\computers.txt) -Newest 3 Get-Content c:\temp\computrs.txt | Get-EventLog -LogName Application -Newest 3 cls #--- #Output it to file Get-Service | Out-File c:\temp\services.txt #This works, but it is not a pipeline Get-Service > c:\temp\services.txt #Getting outut into viewer Get-Service | Out-GridView Get-EventLog Security | Out-GridView #Browsing events Get-EventLog –LogName Security –Newest 5 | Out-GridView #Some cmdlets return mixed output Get-ChildItem . | GM Get-ChildItem -Path hklm:\ | gm Get-ChildItem -Path HKLM:\software\Microsoft\Windows -Recurse | gm Cd HKCU:\Software\Microsoft\Windows\CurrentVersion Get-ChildItem . | GM #Sorting------------------------------------------------ Get-Service | Sort-Object –Property Name –Descending Get-Service | Sort Name –Desc Get-Service | Sort Status,Name #Mark the strange sorting (first S than R)! Get-Service | Sort status #Getting latest Security events Get-EventLog –LogName Security –Newest 10 | Sort-Object –Property TimeWritten #simmulation of Unix tail command: Get-Content c:\temp\log.txt -wait #...and with filter Get-Content c:\temp\log.txt -wait | where { $_ -match “ERROR” } #Count number of services Get-Service | Measure-Object Get-Service | Group-Object status #Count number of processes Get-Process | Measure-Object #Better! Count the amount of used virtual memory Get-Process | Measure-Object –Property VM –Sum –Average #Count number of elements in text file (Unix command wc) Get-Content C:\temp\hosts.txt | Measure-Object –Line Get-Content C:\temp\hosts.txt | Measure-Object -Line -Character -Word #count number of files Get-ChildItem c:\temp -Recurse | Measure-Object #and more complicated example:------------------------------------------------------- function GetDirSize ($dir) { Get-ChildItem $dir -Recurse | Measure-Object | Select-Object @{Name="Path";Expression={$dir}}, @{Name="Count";Expression={$_.Count}} } $dirs=Get-ChildItem 'c:\temp\' $dirs | % { GetDirSize $_.FullName } | Sort-Object -Property Count -Descending #------------------------------------------------------------------------------------ #Selecting only some properties - the largest processes Get-Process | Sort-Object –Property VM | Select-Object –First 10 #Selecting only nme and sorting Get-Service | Sort-Object –Property Name | Select-Object –Last 10 #Selecting based on CPU the most heavy processes Get-Process | Sort-Object –Property CPU –Descending | Select-Object –First 5 –Skip 1 #Select only some properties (the display!) Get-Process | Select-Object –Property Name,ID,VM,PM,CPU #Take only so much, you need Get-Process | Sort-Object –Property VM –Descending | Select-Object –Property Name,VM –First 10 #... not good idea Get-Process | Select-Object –Property * #another examples Get-Process | Sort-Object –Property VM –Descending | Select-Object –First 10 Get-Date | Select-Object –Property DayOfWeek Get-date "1973-09-06" | select dayofweek Get-EventLog –Newest 10 –LogName Security | Select-Object –Property EventID,TimeWritten,Message Get-EventLog –Newest 10 –LogName Security | Select-Object –Property EventID,TimeWritten,Message #type returned get-process | select name Get-Process | select name | gm #if you wish string Get-Process | select -expandproperty name Get-Process | select -expandproperty name | gm #Counted properties------------------------------- Get-Process | Select-Object Name,ID,@{n='VirtualMemory';e={$PSItem.VM}},@{n='PagedMemory';e={$PSItem.PM}} #real calculation inside expression Get-Process | Select-Object Name,ID,@{n='VirtualMemory(MB)';e={$PSItem.VM / 1MB}},@{n='PagedMemory(MB)';e={$PSItem.PM / 1MB}} #and formatting Get-Process | Select-Object Name,ID,@{n='VirtualMemory(MB)';e={'{0:N2}' –f ($PSItem.VM / 1MB) }},@{n='PagedMemory(MB)';e={'{0:N2}' –f ($PSItem.PM / 1MB) }} #let's check what have you doone today! Get-History Get-History | Get-Member Get-History | Select-Object -Property *,@{n='ExecutionTime';e={$PSItem.EndExecutionTime -$PSItem.StartExecutionTime}} #which operation was the longest one? Get-History | Select-Object -Property *,@{n='ExecutionTime';e={$PSItem.EndExecutionTime -$PSItem.StartExecutionTime}} | Sort-Object –Property ExecutionTime –Descending | Select -First 3 #select only one property Get-Date | Select-Object –Property DayOfYear #list Hotfixes installed on local system Get-Hotfix | Select-Object –Property HotFixID,InstalledOn,InstalledBy #to test on server... Get-DHCPServerv4Scope –ComputerName DC1 | Select-Object –Property ScopeId,SubnetMask,Name Get-NetFirewallRule –Enabled True | Select-Object –Property DisplayName,Profile,Direction,Action | Sort-Object –Property DisplayName #equality operators ------------------------------------------- 10 -gt 100 100 -gt 10 10 -ge 9 -and 8 -eq 8 'cat' -eq 'CAT' 'cat' -ceq 'CAT' 'category' -like 'cat*' 'category' -like 'cat' 'b' -in ('b','c','d') #basic syntax of where-------------------------------------- Get-Service | Where-Object Status –eq Running Get-Service | Where Status –eq Running Get-Service | ? Status –eq Running #You are not allowed to use any expressions in this syntax Get-Service | Where Name.Lenght –gt 10 #Advanced syntax Get-Service | Where Status –eq Running Get-Service | Where-Object –FilterScript { $PSItem.Status –eq 'Running' } Get-Service | Where-Object –FilterScript { $_.Status –eq 'Running' } Get-Service | Where { $PSItem.Status –eq 'Running' } Get-Service | ? { $_.Status –eq 'Running' } #Filtering the event log Get-EventLog –LogName Security –Newest 10 | Where { $PSItem.EventID –eq 4672 –and $PSItem.EntryType –eq 'SuccessAudit' } #are the command different? Get-EventLog –LogName Security | Where { $PSItem.EventID –eq 4672 –and $PSItem.EntryType –eq 'SuccessAudit' } | Select -First 10 #searching for heavy processes Get-Process | Where { $_.CPU –gt 30 –and $_.VM –lt 10000 } #searching for active services Get-Service | Where { $PSItem.Status –eq 'Running' –or $PSItem.'Starting' } #Searching for responding processes Get-Process | Where { $PSItem.Responding –eq $True } #shorter syntax Get-Process | Where { $PSItem.Responding } #searching for not responding proceses Get-Process | Where { -not $PSItem.Responding } #this did not work in basic syntax, and now... Get-Service | Where { $PSItem.Name.Length –gt 8 } #PS 4.0 Get-SMBShare | Where Name –like '*$*' #PS 4.0 Get-PhysicalDisk | Where-Object –FilterScript { $PSItem.HealthStatus –eq 'Healthy' } #PS 4.0 Get-Volume | Where { $PSItem.DriveType –eq 'Fixed' –and $PSItem.FileSystem –eq 'NTFS' } #looking for commands Get-Verb | Where { $_.Verb –like 'c*' } #optimalization - use filter built into commands Measure-Command {Get-ChildItem c:\temp | Where { -not $PSItem.PSIsContainer }} Measure-Command {Get-ChildItem –File} #optimalization Measure-Command { Get-ChildItem c:\temp -recurse | Sort Name | Where { $_.Name -like 's*'} } Measure-Command { Get-ChildItem c:\temp -recurse | Where { $_.Name -like 's*'} |Sort Name } Measure-Command {Get-ChildItem c:\temp -Recurse -Filter "s*" | Sort Name} #which one is faster? Get-Service | Where Name –like s* Get-Service –Name s* #REAL EXAMPLE - find empty long not modified AD groups and export them to CSV Get-ADGroup -Filter 'name -like "*sql*"' -properties members,whenchanged | ? {!$_.members} | select-object name,whenchanged | where-object {$_.whenchanged -gt (get-date).AddMonths(-1)} | Sort-Object -Property whenchanged -Descending | Select-Object @{n="nazwa";e={$_.name}},@{n="Data zmiany";e={$_.whenchanged}}| Export-Csv "nazwa_pliku_$(get-date -format yyyyMMdd).csv" #Killing a process - why it works!?------------------------------ Get-Process –Name Notepad | Stop-Process Stop-Process –Name Notepad #using methods of objects in pipe - Basic syntax Get-ChildItem –Path C:\temp\2170 -File | ForEach-Object –MemberName Encrypt #advanced syntax Get-ChildItem –Path C:\temp\2170 -File | ForEach-Object { $_.Decrypt() } #and shorter forms Get-ChildItem –Path C:\temp\2170 | ForEach Encrypt Get-ChildItem –Path C:\temp\2170 | ForEach Decrypt Get-ChildItem –Path C:\temp\2170 | % Encrypt Get-ChildItem –Path C:\temp\2170 | % Decrypt #DO NOT START IT! #Get-EventLog –List | Where Log –eq 'System' | ForEach Clear #Advanced Syntax Get-ChildItem –Path C:\temp\2170 -File | ForEach-Object –Process { $PSItem.Encrypt() } Get-ChildItem –Path C:\temp\2170 -File | ForEach-Object –Process { $PSItem.Decrypt() } #genearte randoms 1..10 | ForEach-Object { Get-Random -Maximum 7 } #short form 1..10 | % { Get-Random } #full form 1..10 | ForEach-Object { Get-Random -Maximum $_ } #setting properties mkdir Get-ItemProperty –Path C:\temp\2170\* | ForEach-Object –Process { Set-ItemProperty –Path $PSItem.PSPath -Name IsReadOnly –Value $true } #check it Get-ChildItem C:\temp\2170\* | Select Name,IsreadOnly #deselect it Get-ItemProperty –Path C:\temp\2170\* | ForEach-Object –Process { Set-ItemProperty –Path $PSItem.PSPath -Name IsReadOnly –Value $false } #print your custom header/footer Get-Process | ForEach-Object –Begin { Get-Date | Out-File Procs.txt } –Process { $PSItem.Name | Out-File Procs.txt –Append } notepad Procs.txt Get-Process | ForEach-Object –Begin { Get-Date | Out-File Procs.txt } –Process { $PSItem.Name | Out-File Procs.txt –Append } -End { notepad Procs.txt}