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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 |
#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} |