PowerShell: Познать за 9 часов

Содержание

Слайд 2

Немного истории

Немного истории

Слайд 3

Command.com with a batch-files Windows Script Host (cscript.exe) JScript and VBScript,

Command.com with a batch-files
Windows Script Host (cscript.exe) JScript and VBScript,
Monad, aka

Microsoft Shell or MSH
April 25, 2006 Microsoft formally announced that Monad had been renamed to Windows PowerShell
January, 2007 Windows PowerShell 1.0
August, 2009 Windows PowerShell 2.0
October, 2012 Windows PowerShell 3.0
October, 2013 Windows PowerShell 4.0

PowerShell и её предшественники

Слайд 4

Язык высокого уровня Базируется на .NET Командлеты является специализированными классами .NET

Язык высокого уровня
Базируется на .NET
Командлеты является специализированными классами .NET
Возможность пользоваться конвейером
Расширенная

система типов (Extended Type System, ETS), базирующаяся на .NET

Зачем использовать PowerShell

Слайд 5

Единственное мощное средство в Windows 2008 (2012) Server Core Выполнение рутинных

Единственное мощное средство в Windows 2008 (2012) Server Core
Выполнение рутинных

задач (автоматизация, множественные операции)
Доступ к огромному кол-ву задач для системного администратора
Поддержка во всех новых серверных продуктах Microsoft
Использование в Logon scripts
Windows Server поддерживает GPO для настроек PowerShell
Можно использовать в WinPe environment

Возможности PowerShell

Слайд 6

http://msdn.microsoft.com/ru-ru/library/cc281945(v=sql.105).aspx http://ru.wikipedia.org/wiki/Windows_PowerShell http://stackoverflow.com (Ответы на многие вопросы) http://blogs.msdn.com/b/powershell/ http://www.computerperformance.co.uk/powershell/ http://thepowershellguy.com/blogs/posh/default.aspx Ресурсы по PowerShell в Сети

http://msdn.microsoft.com/ru-ru/library/cc281945(v=sql.105).aspx
http://ru.wikipedia.org/wiki/Windows_PowerShell
http://stackoverflow.com (Ответы на многие вопросы)
http://blogs.msdn.com/b/powershell/
http://www.computerperformance.co.uk/powershell/
http://thepowershellguy.com/blogs/posh/default.aspx

Ресурсы по PowerShell в Сети

Слайд 7

PowerShell в книгах

PowerShell в книгах

Слайд 8

PowerShell в книгах

PowerShell в книгах

Слайд 9

PowerShell в книгах

PowerShell в книгах

Слайд 10

PowerShell в книгах

PowerShell в книгах

Слайд 11

PowerShell в книгах

PowerShell в книгах

Слайд 12

Verb-Noun Get-Command Set-ADUser Add-Computer Remove-EventLog … Правила именования Commandlets

Verb-Noun
Get-Command
Set-ADUser
Add-Computer
Remove-EventLog

Правила именования Commandlets

Слайд 13

powershell[.exe] [-PSConsoleFile FileName | -Version VersionNumber ] [-NoLogo] [-NoExit] [-NoProfile] [-NonInteractive]

powershell[.exe] [-PSConsoleFile FileName | -Version VersionNumber ]
[-NoLogo] [-NoExit] [-NoProfile] [-NonInteractive]

[-Sta]
[-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
[-WindowsStyle Style] [-EncodedCommand Base64EncodedCommand]
[-File ScriptFilePath] [-ExecutionPolicy PolicySetting ]
[-Command CommandText ]
powershell –nologo –noprofile –command get-process
powershell –noexit –command get-process
powershell –command {get-service; get-process}
powershell –nologo –noprofile –file c:\scripts\run_all.ps1

О параметрах PowerShell

Слайд 14

Рабочая среда PowerShell PowerShell_ISE

Рабочая среда

PowerShell

PowerShell_ISE

Слайд 15

Варианты её настройки

Варианты её настройки

Слайд 16

Варианты её настройки

Варианты её настройки

Слайд 17

if ($host.name -eq "ConsoleHost") { $size=New-Object System.Management.Automation.Host.Size(120,80); $host.ui.rawui.WindowSize=$size } $myHostWin =

if ($host.name -eq "ConsoleHost") {
$size=New-Object System.Management.Automation.Host.Size(120,80);
$host.ui.rawui.WindowSize=$size
}
$myHostWin = $host.ui.rawui
$myHostWin.ForegroundColor = "Blue"
$myHostWin.BackgroundColor

= "Yellow"
$myHostWin.WindowTitle = "Working Script"

Небольшая настройка под себя

Слайд 18

Запускаем Powershell, затем PowerShell_ISE Знакомство

Запускаем Powershell, затем PowerShell_ISE

Знакомство

Слайд 19

ExecutionPolicy

ExecutionPolicy

Слайд 20

PS> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned PS> Get-ExecutionPolicy RemoteSigned PS> Изменение ExecutionPolicy

PS> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
PS> Get-ExecutionPolicy
RemoteSigned
PS>

Изменение ExecutionPolicy

Слайд 21

1. Aliases PowerShell looks for alternate built-in or profile-defined aliases for

1. Aliases PowerShell looks for alternate built-in or profile-defined aliases for


the associated command name. If an alias is found, the command to which
the alias is mapped is run.
2. Functions PowerShell looks for built-in or profile-defined functions with
the command name. If a function is found, the function is executed
3. Cmdlets or language keywords PowerShell looks for built-in cmdlets or
language keywords with the command name. If a cmdlet or language keyword
is found, the appropriate action is taken.
4. Scripts PowerShell looks for scripts with the .ps1 extension. If a PowerShell
script is found, the script is executed.
5. External commands and files PowerShell looks for external commands,
non-PowerShell scripts, and utilities with the command name. If an external
command or utility is found in a directory specified by the PATH environment
variable, the appropriate action is taken. If you enter a file name, PowerShell
uses file associations to determine whether a helper application is available
to open the file.

Execution order

Слайд 22

PS> 1kb 1024 PS> 1mb 1048576 PS> 1gb 1073741824 PS> (1024*1024)/1MB

PS> 1kb
1024
PS> 1mb
1048576
PS> 1gb
1073741824
PS> (1024*1024)/1MB
1

Использование GB, MB, и KB

Слайд 23

Общие параметры для всех CmdLet

Общие параметры для всех CmdLet

Слайд 24

A pipeline is a method of passing data from one command

A pipeline is a method of passing data from one command

to another.
Get-Process | Where-Object {$_.Handles -gt 500} | Sort Handles | Format-Table
Get-Process | Get-Member
Get-Help about_pipeline

Конвейер

Слайд 25

Пару слов про Aliases Aliases

Пару слов про Aliases

Aliases

Слайд 26

Get-Module Modules

Get-Module

Modules

Слайд 27

dir dir | sort Length -Descending dir | sort Length -Descending

dir
dir | sort Length -Descending
dir | sort Length -Descending |

select -first 1
dir –Recurse | sort Length -Descending | select -first 3
dir –Recurse | sort Length -Descending | select -first 10 | Sort Name

Примеры

Слайд 28

Основные команды Read-Host – read data from host Import-Csv – import

Основные команды
Read-Host – read data from host
Import-Csv – import data from

CSV format
Import-CliXml – import data from XML format
Get-Content – get content of file
Clear-Content – clear the file content without file deletion
Add-Content - append data to a text file

Ввод Input

Слайд 29

Out-* —cmdlets that send the objects or formatting records to a

Out-* —cmdlets that send the objects or formatting records to a

specific destination
Write-*—cmdlets that write data to a specific destination
Format-* —cmdlets that convert the objects into formatting records and write them by default to the screen
Export-* —cmdlets that export data to a file
For example: Write-Host –backgroundcolor yellow –foregroundcolor black "This is text!"
Get-Command Out-*

Вывод Output

Слайд 30

For –foregroundcolor and –backgroudcolor the next colors can be used: Black

For –foregroundcolor and –backgroudcolor the next colors can be used:
Black
DarkBlue
DarkGreen
DarkCyan
DarkRed
DarkMagenta
DarkYellow
Gray
DarkGray
Blue
Green
Cyan
Red
Magenta
Yellow
White

Colors

Слайд 31

Вывод Output (Часть команд)

Вывод Output (Часть команд)

Слайд 32

Нужно спросить имя пользователя и вывести его на экран жёлтым цветом

Нужно спросить имя пользователя и вывести его на экран жёлтым цветом
Нужно

считать их текстового файла информацию и вывести её на экран
Нужно получить текстовую строку с клавиатуры и записать её в файл

Пробуем ввод-вывод

Слайд 33

$a = 1 $a | Get-Member TypeName: System.Int32 … $b =

$a = 1
$a | Get-Member TypeName: System.Int32

$b = "1"
$b |

Get-Member
TypeName: System.String

$a = $a * 2.35
$a | Get-Member
TypeName: System.Double

Переменные

Слайд 34

$a = 1; $b = “1”; $c = “abc”; $d =

$a = 1;
$b = “1”;
$c = “abc”;
$d = $a / $b;
$e

= $a + $b;
$f = $c + $a
$g = $a + $c

Как PowerShell конвертирует между типами

Слайд 35

Get-ChildItem variable: (Yes. It’s a drive) Get-Help … About_Automatic_variables —variables created

Get-ChildItem variable: (Yes. It’s a drive)
Get-Help …
About_Automatic_variables —variables created and maintained by

PowerShell
About_Environment_variables —Windows environment variables as used in batch files
About_Preference_variables—variables that customize PowerShell (v2 only)
About_Shell_variables (v1) or About_variables (v2)

Переменные. Помощь по переменным.

Слайд 36

It represents the current object coming down the pipeline Get-ChildItem "c:\temp"

It represents the current object coming down the pipeline
Get-ChildItem "c:\temp" |

Where {$_.Length -gt 1MB}
Get-Process | Sort CPU
Get-Process | Where {$_.CPU -gt 100}
Get-Service | Where {$_.Status –eq ‘stopped’}

Переменные. $_

Слайд 37

$a = 1,2,3,4,5 $b = 1..5 $c = "a","b","c","d","e" $a =

$a = 1,2,3,4,5
$b = 1..5
$c = "a","b","c","d","e"
$a = @(1,2,3,4,5)
$a = @()
for($i=1;$i-le5;$i++){$a

+= $i}
Array values can be accessed by the element number (index), which starts at 0, so the third element in our first example is $a[2] .

Переменные. Массивы.

Слайд 38

Операторы сравнения

Операторы сравнения

Слайд 39

8 –eq 4 $a = “3”; $b =3; $a –eq $b;

8 –eq 4
$a = “3”;
$b =3;
$a –eq $b;
$a

–gt $b;
$a –ne $b;

Пробуем операторы сравнения

Слайд 40

Get-ChildItem "C:\Temp" | Where{!$_.PsIsContainer} | ForEach-Object { if ($_.Length -gt 1MB)

Get-ChildItem "C:\Temp" | Where{!$_.PsIsContainer} |
ForEach-Object {
if ($_.Length -gt 1MB)

{
Remove-Item $_.Fullname -WhatIf
}
elseif ($_.Length -gt 0.5MB){
Write-Host $_.Name, $_.Length, `
" will be removed if more space required" `
-ForegroundColor Yellow
}
else{
if ($_.Length -gt 0.25MB){
Write-Host $_.Name, $_.Length, `
" will be removed in third wave" `
-ForegroundColor Blue
}
}
}

Сравнения. Организация ветвлений. if

Слайд 41

$files = Get-ChildItem "C:\Temp" | Where {!$_.PsIsContainer} foreach ($file in $files){

$files = Get-ChildItem "C:\Temp" |
Where {!$_.PsIsContainer}
foreach ($file in $files){


switch ($file.Length){
{$_ -gt 1MB}{Write-Host $file.Name, $file.Length `
-ForegroundColor Red; break}
{$_ -gt 0.5MB}{Write-Host $file.Name, $file.Length `
-ForegroundColor Magenta; break}
{$_ -ge 0.25MB}{Write-Host $file.Name, $file.Length `
-ForegroundColor Cyan; break}
#default {Write-Host $file.Name, $file.Length}
}
}

Сравнения. Организация ветвлений. switch

Слайд 42

Foreach-Object cmdlet Foreach loop For loop Do loop While loop Циклы

Foreach-Object cmdlet
Foreach loop
For loop
Do loop
While loop

Циклы

Слайд 43

for ($i = 0; $i -lt somevalue; $i++) { } Циклы For

for ($i = 0; $i -lt somevalue; $i++) {
< PowerShell

code>
}

Циклы For

Слайд 44

Циклы Foreach-Object $Out1 = @" $count files are smaller than 1MB

Циклы Foreach-Object

$Out1 = @"
$count files are smaller than 1MB and

occupy $total_size bytes
"@
$Out2 = @"
$count_big files are bigger than 1MB and occupy $total_size_big bytes
"@
Get-ChildItem "c:\Temp" |
where {!$_.PSIsContainer} | ForEach-Object `
-Begin {
$count = 0
$total_size = 0
$count_big = 0
$total_size_big = 0
} `

-Process {
if ($_.Length -gt 1MB) {
$total_size_big += $_.Length
$count_big ++
}
else {
$total_size += $_.Length
$count ++
}
} `
-End {
Write-Host $out1
Write-Host $out2
}

Слайд 45

Use the following syntax for a foreach loop: foreach ($item in

Use the following syntax for a foreach loop:
foreach ($item in $collection_of_items)

{
< PowerShell code>
}
dir "c:\test" | ?{!$_.PSIsContainer} |
% {if ($_.LastAccessTime -lt ((Get-Date).AddDays(-10)))
{rm $($_.Fullname) -wh} }

Циклы Foreach

Слайд 46

$date = (Get-Date).Adddays(-10) $files = Get-ChildItem "c:\Temp" | Where{!$_.PSIsContainer} foreach($file in

$date = (Get-Date).Adddays(-10)
$files = Get-ChildItem "c:\Temp" | Where{!$_.PSIsContainer}
foreach($file in $files){

if ($file.LastAccessTime -lt $date){
Remove-Item -Path $file.FullName -WhatIf
}
}
Get-ChildItem "c:\Temp" | Where{!$_.PSIsContainer}
Try it. In the pipeline, we start with Get-ChildItem producing a directory listing of the C:\Temp folder.
That’s piped into a Where-Object filter that looks to see whether the object is a container (a folder). Only objects that aren’t folders are passed.

Циклы Foreach

Слайд 47

while ( ) { } Циклы While

while () {
< PowerShell code>
}

Циклы While

Слайд 48

$data = 1..57 $j = 1 while ($j -le 10){ $qqq

$data = 1..57
$j = 1
while ($j -le 10){
$qqq =

"C:\TEMP\PS\111\"
$foldername = "Testfolder_$j"
New-Item -Name "$qqq$foldername" -ItemType directory
$j++
for ($i=0; $i -le 10; $i++){
$filename = "file_$i.txt“
Set-Content "$qqq$foldername\$filename" -Value $data
}
}

Циклы While

Слайд 49

do { } until ( ) do { } while ( ) Циклы Do

do {
< PowerShell code>
} until ()
do {
< PowerShell code>
}

while ()

Циклы Do

Слайд 50

$i = 1 do { $name = "Testfolder_$i" New-Item -ItemType directory

$i = 1
do {
$name = "Testfolder_$i"
New-Item -ItemType directory -Name

$name
$i++
}
while ($i -le 10)
Or just change the last line to the new one:
until ($i -gt 10)

Циклы Do

Слайд 51

Get-Help Get-Command Get-Member Get-PSDrive 4 ваших лучших друга

Get-Help
Get-Command
Get-Member
Get-PSDrive

4 ваших лучших друга

Слайд 52

Get-Help get-service | get-member -membertype *property Получение помощи (Get-Help)

Get-Help
get-service | get-member -membertype *property

Получение помощи (Get-Help)

Слайд 53

Get-Command Get-Command ipconfig.exe | Format-List Get-Command *process Get-Command -Module ActiveDirectory |

Get-Command
Get-Command ipconfig.exe | Format-List
Get-Command *process
Get-Command -Module ActiveDirectory | Sort verb, noun
Get-Command

Get-Process -Syntax

Получение списка команд (Get-Command)

Слайд 54

Get-Help Get-Member Get-Process c* | Get-Member Get-Process c* | Get-Member -MemberType

Get-Help Get-Member
Get-Process c* | Get-Member
Get-Process c* | Get-Member -MemberType Property |


Format-Wide -Column 2

Получение списка членов (Get-Member)

Слайд 55

Get-Help about Get-Help -detailed Get-Help -full Get-Help -examples Get-Help -online Get-Help about_topic_name Расширенное получение помощи

Get-Help about
Get-Help -detailed
Get-Help -full
Get-Help -examples
Get-Help -online
Get-Help about_topic_name

Расширенное

получение помощи
Слайд 56

Single line comments: # Multiline comments: Основы

Single line comments:
#
Multiline comments: <# … #>

Основы

Слайд 57

function Name { param( [type]$ParameterA = default_value, [type]$ParameterB = default_value )

function Name {
param(
[type]$ParameterA = default_value,
[type]$ParameterB = default_value
)

begin {< PowerShell code> }
process {< PowerShell code> }
end {< PowerShell code> }
}
function new-file {
param ($number, $foldername)
for ($i=0; $i -le $number; $i++){
$name = "$foldername-file-$i.txt"
Set-Content -Path "$foldername\$name" -Value $data
}
}

Написание собственных функций

Слайд 58

$data = 1..57 $i = 1 while ($i -le 10) {

$data = 1..57
$i = 1
while ($i -le 10) {
$name

= "Testfolder_$i"
New-Item -ItemType directory -Name $name
new-file $i $name
$i++
}

Написание собственных функций. Использование.

Слайд 59

Scope defines how scripts and functions work with variables. When PowerShell

Scope defines how scripts and functions work with variables. When PowerShell

starts, it defines a top-level or global scope. When a script, script block, or function is started, a new scope is defined.
Global variables
Script variables
Function variables
Get-help about_scope

Scope

Слайд 60

PS> $env:psmodulepath -split ";" C:\Users\Alex\Documents\WindowsPowerShell\Modules C:\Windows\system32\WindowsPowerShell\v1.0\Modules\ PS> Get-Module -ListAvailable ModuleType Name

PS> $env:psmodulepath -split ";"
C:\Users\Alex\Documents\WindowsPowerShell\Modules
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
PS> Get-Module -ListAvailable
ModuleType Name ExportedCommands
---------- ---- ----------------
Manifest FileFunctions

{}
Script MathFunctions {}
Import-Module | Get-Module -ListAvailable

Оснастки (Modules) [PSSnapin - obsolete]

Слайд 61

Рабочие примеры

Рабочие примеры

Слайд 62

Based on 02.ps1 Show process list as a Table Show by

Based on 02.ps1
Show process list as a Table
Show by Grouping processes

in Table
Advanced grouping

Практика

Слайд 63

function get-ms { $ie = New-Object -ComObject InternetExplorer.Application $ie.Navigate("http://www.microsoft.com/") while ($ie.busy)

function get-ms {
$ie = New-Object -ComObject InternetExplorer.Application
$ie.Navigate("http://www.microsoft.com/")
while ($ie.busy) { Start-Sleep -seconds

1 }
$ie.Visible = $true
}

COM-объекты. Доступ.

Слайд 64

Рабочие примеры

Рабочие примеры

Слайд 65

Based on 04.ps1 Add new menu point, that route us to

Based on 04.ps1
Add new menu point, that route us to the

site http://blogs.msdn.com/b/powershell/
Making a default action, when correct menu point has not been selected, or user mistakes.
Change previous script that it will looping while we won’t want to stop it from our menu.

Практика

Слайд 66

Get-WmiObject -Class Win32_ComputerSystem | Format-List Name, SystemType, NumberOfProcessors Get-WmiObject -Class Win32_Processor

Get-WmiObject -Class Win32_ComputerSystem |
Format-List Name, SystemType, NumberOfProcessors
Get-WmiObject -Class Win32_Processor |


Format-List Manufacturer, Name, Description, ProcessorID, AddressWidth, DataWidth, Family, MaxClockSpeed -ComputerName parametr allow you to get such information from any computers in your network provided that you have a correct credentials.

WMI-объекты. Введение.

Слайд 67

Get-WMIObject –list Returning a long list Get-WmiObject -List *OperatingSystem* Either option

Get-WMIObject –list Returning a long list
Get-WmiObject -List *OperatingSystem*
Either option will return

a list of the classes containing OperatingSystem in their names.
Get-WMIObject –class Win32_OperatingSystem
Get-WMIObject -Class Win32_OperatingSystem | Get-Member

WMI-объекты. Понимание.

Слайд 68

PS> $t = Get-WMIObject -Class Win32_OperatingSystem | Select LastBootUpTime >> PS>

PS> $t = Get-WMIObject -Class Win32_OperatingSystem | Select LastBootUpTime
>>
PS> $t


LastBootUpTime
--------------
20070406072653.500000+060
PS> Get-WMIObject -Class Win32_OperatingSystem -property LastBootUpTime | foreach {
[System.Management.ManagementDateTimeConverter]::ToDateTime($_.LastBootUpTime)}
06 January 2012 07:26:53

WMI-объекты. Использование.

Слайд 69

Two different ways, doing the same. Using [WMIClass] is a shortcut

Two different ways, doing the same.
Using [WMIClass] is a shortcut for

using New-Object :
$x = New-Object -TypeName System.Management.ManagementClass -ArgumentList "Win32_Process"
$x | Get-Member
$x.Create("notepad.exe") Invoke-WmiMethod -Path win32_Process.Handle=5500 –Name Terminate
Invoke-WmiMethod -Class Win32_Process -Name Create`
-ArgumentList "notepad.exe"

WMI-объекты. Использование.

Слайд 70

Рабочие примеры

Рабочие примеры

Слайд 71

Obtaining a Process list (07.ps1) Make it friendly Make it more

Obtaining a Process list (07.ps1)
Make it friendly
Make it more friendly
Changing sort

order for analyze features
Continuously monitoring processes on computer
Continuously monitoring selected process only

Практика

Слайд 72

.NET VERSIONS PowerShell v1 needs . NET 2.0. PowerShell v2 needs

.NET VERSIONS PowerShell v1 needs . NET 2.0. PowerShell v2 needs

. NET 2.0 apart from some features that require . NET 3.5 SP1 . Unless you need multiple versions of .NET loaded, just load . NET 3.5 SP 1, as it also contains . NET 2.0.
.NET Class library:
http://msdn.microsoft.com/en-us/library/ms229335.aspx
$rand = New-Object -TypeName System.Random -ArgumentList 42
Alternative way:
$rand2 = [System.Random](42)

Интеграция с .NET Введение.

Слайд 73

PS> [System.Math]::Sqrt(16) 4 PS> [System.Math]::Pi 3.14159265358979 Интеграция с .NET Примеры.

PS> [System.Math]::Sqrt(16)
4
PS> [System.Math]::Pi
3.14159265358979

Интеграция с .NET Примеры.

Слайд 74

[System.math] | get-member –Static Name MemberType Definition ---- ---------- ---------- Acos

[System.math] | get-member –Static
Name MemberType Definition
---- ---------- ----------
Acos

Method static double Acos(double d)
Asin Method static double Asin(double d)
Atan Method static double Atan(double d)
BigMul Method static long BigMul(int a, int b)

Интеграция с .NET Исследование.

Слайд 75

Рабочие примеры

Рабочие примеры

Слайд 76

Converting everything to string (09.ps1) Converting numbers Converting dates Converting times Complex converting Практика

Converting everything to string (09.ps1)
Converting numbers
Converting dates
Converting times
Complex converting

Практика

Слайд 77

Write-Host, Write-Warning, Write-Error Read-Host, Measure-Command Понятие отладки, базовые рекомендации

Write-Host, Write-Warning, Write-Error
Read-Host, Measure-Command

Понятие отладки, базовые рекомендации

Слайд 78

$sb = { Get-ChildItem c:\*.* } Measure-Command -Expression $sb Output should

$sb = {
Get-ChildItem c:\*.*
}
Measure-Command -Expression $sb
Output should be like that:
Days :

0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 71
Ticks : 719155
TotalDays : 8,32355324074074E-07
TotalHours : 1,99765277777778E-05
TotalMinutes : 0,00119859166666667
TotalSeconds : 0,0719155
TotalMilliseconds : 71,9155
Replace Measure-Command with Invoke-Command and you’ll get
the output.

Понятие отладки, базовые рекомендации

Слайд 79

At last: Write-Progress (-Activity, -Status, -PercentComplete, -CurrentOperation) Find top 100 biggest

At last: Write-Progress (-Activity, -Status, -PercentComplete, -CurrentOperation)
Find top 100 biggest files (10.ps1)
More

informative output
Show files, their lengths, counting numbers

Примеры решения задач

Слайд 80

Find all *.tmp or anything else extension files from the root

Find all *.tmp or anything else extension files from the root

of the disk, count it size, show it, separated by the folders with its count. (11.ps1)
Performing fake-deletion founded files and show deleted files.
Performing fake-deletion files found and show deletion progress using progress bar, by folders.

Практика

Слайд 81

Obtaining OS version for a group of computers. (12.ps1) Make all

Obtaining OS version for a group of computers. (12.ps1)
Make all above

and export to Excel-compatible format
Export only fields selected
Get-Process to .CSV
Get-Process to .HTML

Автоматизация простых рутинных задач с помощью PowerShell

Слайд 82

Read the help files—there’s a mass of good information, especially in

Read the help files—there’s a mass of good information, especially in
the

examples.
In PowerShell v3, set up a schedule to update help on a regular basis.
Set your execution policy to at least RemoteSigned.
Use the pipeline—PowerShell is designed for pipeline usage. If you apply coding styles from older scripting languages, you’ll lose a lot of functionality and create work for yourself.
Give variables meaningful names, such as $computer rather than $x.
Avoid variables with spaces or special symbols in their names, such as
${computername}.
Never set $ErrorActionPreference (or $VerbosePreference or any other
“preference” variable) globally in the shell or in a script or function. Instead,
use parameters, such as a cmdlet’s –ErrorAction parameter or a function’s
-Verbose parameter, to set the preference on an as-needed basis.

Best Practices (PowerShell general best practices)

Слайд 83

Avoid enumerating collections—using ForEach-Object or the ForEach scripting construct—unless there’s no

Avoid enumerating collections—using ForEach-Object or the ForEach scripting construct—unless there’s no

other way to accomplish your task.
Use single quotes unless you explicitly need the variable-replacement and expression-evaluation capabilities of double quotes. If you’re working with SQL
Server databases, remember that they use single quotes for strings.
String substitution (or multiplication) is much easier than string concatenation.
Use the built-in constants—PowerShell understands KB, MB, GB, TB, and PB.
Avoid using native .NET classes and methods unless there’s no cmdlet alternative.
Be careful with code downloads from the internet and always double-check what the code is doing—your environment may be different enough from the author’s that you’ll encounter problems.
Filter early and format late. Restrict the data set as soon as possible, but don’t format the data until you’re just about to display.

Best Practices (PowerShell general best practices)

Слайд 84

Ping computer via PowerShell (13.ps1) Pinging group of computers Restart service

Ping computer via PowerShell (13.ps1)
Pinging group of computers
Restart service
Another way

to restart service

Примеры из реальной жизни Wintel IS