PowerShell: Познать за 9 часов презентация

Содержание

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

Слайд 1PowerShell: Познать за 9 часофф
Будут рассмотрены общие темы по работе в

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

Слайд 2Немного истории


Слайд 3Command.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
Возможность пользоваться конвейером
Расширенная

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

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


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

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

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


Слайд 6http://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 в Сети


Слайд 7PowerShell в книгах


Слайд 8
PowerShell в книгах


Слайд 9
PowerShell в книгах


Слайд 10
PowerShell в книгах


Слайд 11
PowerShell в книгах


Слайд 12Verb-Noun

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

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


Слайд 13powershell[.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


Слайд 15Варианты её настройки


Слайд 16Варианты её настройки


Слайд 17if ($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
Знакомство


Слайд 19ExecutionPolicy


Слайд 20PS> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
PS> Get-ExecutionPolicy
RemoteSigned
PS>
Изменение ExecutionPolicy


Слайд 211. 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


Слайд 22PS> 1kb
1024
PS> 1mb
1048576
PS> 1gb
1073741824
PS> (1024*1024)/1MB
1
Использование GB, MB, и KB


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


Слайд 24A 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


Слайд 26Get-Module
Modules


Слайд 27dir
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 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


Слайд 29Out-* —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


Слайд 30For –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 (Часть команд)


Слайд 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$a = 1;
$b = “1”;
$c = “abc”;

$d = $a / $b;
$e

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

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


Слайд 35Get-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)

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


Слайд 36It 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Операторы сравнения


Слайд 398 –eq 4
$a = “3”;
$b =3;
$a –eq $b;
$a

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

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


Слайд 40Get-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){
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


Слайд 42Foreach-Object cmdlet
Foreach loop
For loop
Do loop
While loop
Циклы


Слайд 43for ($i = 0; $i -lt somevalue; $i++) {

PowerShell code>
}

Циклы For


Слайд 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
}


Слайд 45Use 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 $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


Слайд 47while () {
< PowerShell code>
}

Циклы While


Слайд 48$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


Слайд 49do {
< PowerShell code>
} until ()

do {

PowerShell code>
} while ()

Циклы Do


Слайд 50$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


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


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


Слайд 53Get-Command
Get-Command ipconfig.exe | Format-List
Get-Command *process
Get-Command -Module ActiveDirectory | Sort verb, noun
Get-Command

Get-Process -Syntax

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


Слайд 54Get-Help Get-Member
Get-Process c* | Get-Member
Get-Process c* | Get-Member -MemberType Property |


Format-Wide -Column 2

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


Слайд 55Get-Help about
Get-Help -detailed
Get-Help -full
Get-Help -examples
Get-Help -online
Get-Help about_topic_name
Расширенное

получение помощи

Слайд 56Single line comments:
#
Multiline comments:
Основы


Слайд 57function 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++
}

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


Слайд 59Scope 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


Слайд 60PS> $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Рабочие примеры


Слайд 62Based on 02.ps1
Show process list as a Table
Show by Grouping processes

in Table
Advanced grouping

Практика


Слайд 63function 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Рабочие примеры


Слайд 65Based 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.

Практика


Слайд 66Get-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-объекты. Введение.


Слайд 67Get-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-объекты. Понимание.


Слайд 68PS> $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-объекты. Использование.


Слайд 69Two 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Рабочие примеры


Слайд 71Obtaining 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 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 Введение.


Слайд 73PS> [System.Math]::Sqrt(16)
4

PS> [System.Math]::Pi
3.14159265358979

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


Слайд 74[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Рабочие примеры


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


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


Слайд 78$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.

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


Слайд 79At last: Write-Progress (-Activity, -Status, -PercentComplete, -CurrentOperation)
Find top 100 biggest files (10.ps1)
More

informative output
Show files, their lengths, counting numbers

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


Слайд 80Find 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.

Практика


Слайд 81Obtaining 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


Слайд 82Read 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)


Слайд 83Avoid 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)


Слайд 84Ping computer via PowerShell (13.ps1)
Pinging group of computers
Restart service
Another way

to restart service

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


Слайд 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

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


Обратная связь

Если не удалось найти и скачать презентацию, Вы можете заказать его на нашем сайте. Мы постараемся найти нужный Вам материал и отправим по электронной почте. Не стесняйтесь обращаться к нам, если у вас возникли вопросы или пожелания:

Email: Нажмите что бы посмотреть 

Что такое ThePresentation.ru?

Это сайт презентаций, докладов, проектов, шаблонов в формате PowerPoint. Мы помогаем школьникам, студентам, учителям, преподавателям хранить и обмениваться учебными материалами с другими пользователями.


Для правообладателей

Яндекс.Метрика