PowerShell: Познать за 9 часофф
Немного истории
PowerShell и её предшественники
Зачем использовать PowerShell
Возможности PowerShell
Ресурсы по PowerShell в Сети
PowerShell в книгах
PowerShell в книгах
PowerShell в книгах
PowerShell в книгах
PowerShell в книгах
Правила именования Commandlets
О параметрах PowerShell
Рабочая среда
Варианты её настройки
Варианты её настройки
Небольшая настройка под себя
Знакомство
ExecutionPolicy
Изменение ExecutionPolicy
Execution order
Использование GB, MB, и KB
Общие параметры для всех CmdLet
Конвейер
Aliases
Modules
Примеры
Ввод Input
Вывод Output
Colors
Вывод Output (Часть команд)
Пробуем ввод-вывод
Переменные
Как PowerShell конвертирует между типами
Переменные. Помощь по переменным.
Переменные. $_
Переменные. Массивы.
Операторы сравнения
Пробуем операторы сравнения
Сравнения. Организация ветвлений. if
Сравнения. Организация ветвлений. switch
Циклы
Циклы For
Циклы Foreach-Object
Циклы Foreach
Циклы Foreach
Циклы While
Циклы While
Циклы Do
Циклы Do
4 ваших лучших друга
Получение помощи (Get-Help)
Получение списка команд (Get-Command)
Получение списка членов (Get-Member)
Расширенное получение помощи
Основы
Написание собственных функций
Написание собственных функций. Использование.
Scope
Оснастки (Modules) [PSSnapin - obsolete]
Рабочие примеры
Практика
COM-объекты. Доступ.
Рабочие примеры
Практика
WMI-объекты. Введение.
WMI-объекты. Понимание.
WMI-объекты. Использование.
WMI-объекты. Использование.
Рабочие примеры
Практика
Интеграция с .NET Введение.
Интеграция с .NET Примеры.
Интеграция с .NET Исследование.
Рабочие примеры
Практика
Понятие отладки, базовые рекомендации
Понятие отладки, базовые рекомендации
Примеры решения задач
Практика
Автоматизация простых рутинных задач с помощью PowerShell
Best Practices (PowerShell general best practices)
Best Practices (PowerShell general best practices)
Примеры из реальной жизни Wintel IS
Итоговая лабораторная работа
1.53M

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

1. PowerShell: Познать за 9 часофф

Будут рассмотрены общие темы по работе в PS,
направленные на осознание возможностей PS и
получения базовых знаний в плане его применения

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

Язык
Год
создания
Комментарии
REXX
1979 - 1982 Restructured Extended Executor. Author:
Mike Cowlishaw of IBM. In his own time.
BASIC
1964
Author: John George Kemeny and Thomas
Eugene Kurtz.
Python
1989
Conceived: 1980, implementation: 1989 by
Guido van Rossum
Perl
1987
Practical Extraction and Reporting Language.
By Larry Wall.

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

1.
2.
3.
4.
5.
6.
7.
8.
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

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

Язык высокого уровня
Базируется на .NET
Командлеты является специализированными
классами .NET
Возможность пользоваться конвейером
Расширенная система типов (Extended Type System,
ETS), базирующаяся на .NET

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

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

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

http://msdn.microsoft.com/ru-ru/library/cc281945(v=sq
l.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

7. PowerShell в книгах

8. PowerShell в книгах

9. PowerShell в книгах

10. PowerShell в книгах

11. PowerShell в книгах

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

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

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

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

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

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 = $host.ui.rawui
$myHostWin.ForegroundColor = "Blue"
$myHostWin.BackgroundColor = "Yellow"
$myHostWin.WindowTitle = "Working Script"

18. Знакомство

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

19. ExecutionPolicy

Значение
Описание
Restricted
Значение по-умолчанию. Не даёт запускать скрипт
профиля и никакие скрипты вообще
AllSigned
Все скрипты профиля и обычные скрипты должны
быть подписаны цифровой подписью из доверенного
центра это также распространяется на скрипты,
запускаемые локально
RemoteSigned
Все скрипты профиля и обычные скрипты должны
быть подписаны цифровой подписью. Это также
распространяется на скрипты из сетевых ресурсов
(Network shares)
Unrestricted
Могут быть запущены любые скрипты
Bypass
Ничего не блокируется, никаких запросов и ошибок
Undefined
Удаляет текущую Execution Policy, не трогает
назначенную через GPO.

20. Изменение ExecutionPolicy

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

21. Execution order

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.

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

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

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

Parameter
Meaning
-Debug
Displays detailed information useful to programmers.
-ErrorAction
Indicates how the cmdlet responds to a nonterminating error.
Possible values are SilentlyContinue , Continue , Inquire, Stop.
-ErrorVariable
Stores information about errors in the specified variable.
-OutBuffer
Determines the number of objects to store before sending them
onto the pipe-line. This is usually omitted, which means that
objects are sent onto the pipe-line immediately.
-OutVariable
Stores error messages in the specified variable.
-Verbose
Displays detailed information about the operation.
-WhatIf
If present, this parameter caт uses PowerShell to output a list of
statements indicating what would’ve happened if the command
had been executed, without executing the
command.
-Confirm
Prompts the user for confirmation before performing any action.
Get-Help about_CommonParameters

24. Конвейер

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

26. Modules

Get-Module

27. Примеры

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. Ввод Input

Основные команды
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

29. Вывод Output

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-*

30. Colors

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

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

Name
Purposes
Out-File
Sends output to a file. Data can be appended to a file.
Out-Null
Deletes output rather than displaying it. Use it to suppress messages, for
instance when loading .NET assemblies.
Out-Printer
Sends output to the default printer, or an alternative printer if specified. It doesn’t format the data so use only for
simple text documents.
Out-String
Sends objects to the host as strings.
Write-Host
Writes output to screen. Can change colors of text.
Format-Table
Formats the data into a table and displays on screen.
Format-List
Formats the data into a list and displays on screen.
Format-Wide
Formats objects as a wide table that displays only one property in multi column format of each object. Default
column count = 2
Export-Csv
Exports objects to a CSV file. Data can’t be appended to a file.
Export-CliXML
Exports objects to an XML file.
command > [path]filename
Sends the output of the first command to be the
input of the second command
command >> [path]filename
Appends output to the named file if it exists or
creates the file and then writes to it.

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

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

33. Переменные

$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. Как PowerShell конвертирует между типами

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

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

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" | 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 = @(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. Операторы сравнения

Operator
Meaning
-eq
Equal to. Returns true if both sides are equal.
8 -eq 8 , "me" -eq "you"
-ne
Not equal to. Returns true if the two objects are different.
8 -eq 8, "me" -eq "you"
-gt
Greater than. Returns true if left side is greater than right
side. 8 -gt 7
-ge
Greater than or equal. Returns true if left side is greater t han
or equal to right side. 8 -ge 7, 8 -ge
-lt
Less than. Returns true if left side is less than or equal to
right side. 7 -lt 8
-le
Less than or equal to. Returns true if left side less than or
equal to right side. 7 -le 8, 8 -le 8

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

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

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

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
}
}
}

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

$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}
}
}

42. Циклы

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

43. Циклы For

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

44. Циклы 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. Циклы Foreach

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} }

46. Циклы Foreach

$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.

47. Циклы While

while (<condition>) {
< PowerShell code>
}

48. Циклы While

$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
}
}

49. Циклы Do

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

50. Циклы Do

$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)

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

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

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

Get-Help <Cmdlet-Name>
get-service | get-member -membertype *property

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

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

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

Get-Help Get-Member
Get-Process c* | Get-Member
Get-Process c* | Get-Member -MemberType Property |
Format-Wide -Column 2

55. Расширенное получение помощи

Get-Help about
Get-Help <Command-Name> -detailed
Get-Help <Command-Name> -full
Get-Help <Command-Name> -examples
Get-Help <Command-Name> -online
Get-Help about_topic_name

56. Основы

Single line comments:
#
Multiline comments:
<#

#>

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

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) {
$name = "Testfolder_$i"
New-Item -ItemType directory -Name $name
new-file $i $name
$i++
}

59. Scope

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

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

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

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

Script name
Description
02.ps1
Get services on computers
03.ps1
Rename files using mask
0301.ps1
Analyzing module presence

62. Практика

Based on 02.ps1
1. Show process list as a Table
2. Show by Grouping processes in Table
3. Advanced grouping

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

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
}

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

Script Name
Description
04.ps1
Manipulating IE COM Object
0404.ps1
Manipulating Excel COM Object

65. Практика

Based on 04.ps1
1. Add new menu point, that route us to the site
http://blogs.msdn.com/b/powershell/
2. Making a default action, when correct menu point
has not been selected, or user mistakes.
3. Change previous script that it will looping while we
won’t want to stop it from our menu.

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

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.

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

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

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

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($_.LastBoo
tUpTime)}
06 January 2012 07:26:53

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

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"

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

Script Name
Description
05.ps1
Another way to obtain LastBootupTime
0501.ps1
Obtain System.TimeSpan object
0502.ps1
Use System.TimeSpan to show UpTime in human-friendly view
06.ps1
Obtain OS Version simple
0601.ps1
Small report about computer and its OS Version
0602.ps1
Twist around Performance counters

71. Практика

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 Введение.

.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)

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

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

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

[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)

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

Script Name
Description
08.ps1
Get current date and time using .NET
0801.ps1
Get logical drive list using .NET
0802.ps1
Pinging using .NET
0803.ps1
Pinging a group of objects using .NET
0804.ps1
Using TCPIP Client to connect to the specified ports using .NET

76. Практика

1.
2.
3.
4.
5.
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
Parameter
Description
-Debug
Displays detailed information useful to programmers.
-Verbose
Displays detailed information about the operation.
-WhatIf
If present, this parameter causes PowerShell to output a list of statements
indicating what would’ve happened if the command had been executed,
without executing the command.
-Confirm
Prompts the user for confirmation before performing any action.

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

$sb = {
Get-ChildItem c:\*.*
}
Measure-Command -Expression $sb
Output should be like that:
:0
Days
:0
Hours
Minutes
:0
Seconds
:0
Milliseconds : 71
: 719155
Ticks
TotalDays
: 8,32355324074074E-07
: 1,99765277777778E-05
TotalHours
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 files (10.ps1)
More informative output
Show files, their lengths, counting numbers

80. Практика

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. Автоматизация простых рутинных задач с помощью PowerShell

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

82. Best Practices (PowerShell general best practices)

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.

83. Best Practices (PowerShell general best practices)

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.

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

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

85. Итоговая лабораторная работа

#Create a PS script, that show us a FullName and
Length properties for a files in a directory, that we
can choose. Directories need to be scanned
recursively.
Get uptime for computers, given from input file
Find error in the next command. Correct it and run.
Get-Process -Name svc | Format-Table -auto | select
Name
English     Русский Rules