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

Нажмите для полного просмотра!
PowerShell: Познать за 9 часов, слайд №1PowerShell: Познать за 9 часов, слайд №2PowerShell: Познать за 9 часов, слайд №3PowerShell: Познать за 9 часов, слайд №4PowerShell: Познать за 9 часов, слайд №5PowerShell: Познать за 9 часов, слайд №6PowerShell: Познать за 9 часов, слайд №7PowerShell: Познать за 9 часов, слайд №8PowerShell: Познать за 9 часов, слайд №9PowerShell: Познать за 9 часов, слайд №10PowerShell: Познать за 9 часов, слайд №11PowerShell: Познать за 9 часов, слайд №12PowerShell: Познать за 9 часов, слайд №13PowerShell: Познать за 9 часов, слайд №14PowerShell: Познать за 9 часов, слайд №15PowerShell: Познать за 9 часов, слайд №16PowerShell: Познать за 9 часов, слайд №17PowerShell: Познать за 9 часов, слайд №18PowerShell: Познать за 9 часов, слайд №19PowerShell: Познать за 9 часов, слайд №20PowerShell: Познать за 9 часов, слайд №21PowerShell: Познать за 9 часов, слайд №22PowerShell: Познать за 9 часов, слайд №23PowerShell: Познать за 9 часов, слайд №24PowerShell: Познать за 9 часов, слайд №25PowerShell: Познать за 9 часов, слайд №26PowerShell: Познать за 9 часов, слайд №27PowerShell: Познать за 9 часов, слайд №28PowerShell: Познать за 9 часов, слайд №29PowerShell: Познать за 9 часов, слайд №30PowerShell: Познать за 9 часов, слайд №31PowerShell: Познать за 9 часов, слайд №32PowerShell: Познать за 9 часов, слайд №33PowerShell: Познать за 9 часов, слайд №34PowerShell: Познать за 9 часов, слайд №35PowerShell: Познать за 9 часов, слайд №36PowerShell: Познать за 9 часов, слайд №37PowerShell: Познать за 9 часов, слайд №38PowerShell: Познать за 9 часов, слайд №39PowerShell: Познать за 9 часов, слайд №40PowerShell: Познать за 9 часов, слайд №41PowerShell: Познать за 9 часов, слайд №42PowerShell: Познать за 9 часов, слайд №43PowerShell: Познать за 9 часов, слайд №44PowerShell: Познать за 9 часов, слайд №45PowerShell: Познать за 9 часов, слайд №46PowerShell: Познать за 9 часов, слайд №47PowerShell: Познать за 9 часов, слайд №48PowerShell: Познать за 9 часов, слайд №49PowerShell: Познать за 9 часов, слайд №50PowerShell: Познать за 9 часов, слайд №51PowerShell: Познать за 9 часов, слайд №52PowerShell: Познать за 9 часов, слайд №53PowerShell: Познать за 9 часов, слайд №54PowerShell: Познать за 9 часов, слайд №55PowerShell: Познать за 9 часов, слайд №56PowerShell: Познать за 9 часов, слайд №57PowerShell: Познать за 9 часов, слайд №58PowerShell: Познать за 9 часов, слайд №59PowerShell: Познать за 9 часов, слайд №60PowerShell: Познать за 9 часов, слайд №61PowerShell: Познать за 9 часов, слайд №62PowerShell: Познать за 9 часов, слайд №63PowerShell: Познать за 9 часов, слайд №64PowerShell: Познать за 9 часов, слайд №65PowerShell: Познать за 9 часов, слайд №66PowerShell: Познать за 9 часов, слайд №67PowerShell: Познать за 9 часов, слайд №68PowerShell: Познать за 9 часов, слайд №69PowerShell: Познать за 9 часов, слайд №70PowerShell: Познать за 9 часов, слайд №71PowerShell: Познать за 9 часов, слайд №72PowerShell: Познать за 9 часов, слайд №73PowerShell: Познать за 9 часов, слайд №74PowerShell: Познать за 9 часов, слайд №75PowerShell: Познать за 9 часов, слайд №76PowerShell: Познать за 9 часов, слайд №77PowerShell: Познать за 9 часов, слайд №78PowerShell: Познать за 9 часов, слайд №79PowerShell: Познать за 9 часов, слайд №80PowerShell: Познать за 9 часов, слайд №81PowerShell: Познать за 9 часов, слайд №82PowerShell: Познать за 9 часов, слайд №83PowerShell: Познать за 9 часов, слайд №84PowerShell: Познать за 9 часов, слайд №85

Содержание

Вы можете ознакомиться и скачать презентацию на тему PowerShell: Познать за 9 часов. Доклад-сообщение содержит 85 слайдов. Презентации для любого класса можно скачать бесплатно. Если материал и наш сайт презентаций Mypresentation Вам понравились – поделитесь им с друзьями с помощью социальных кнопок и добавьте в закладки в своем браузере.

Слайды и текст этой презентации


Слайд 1





PowerShell: Познать за 9 часофф
Будут рассмотрены общие темы по работе в PS, направленные на осознание возможностей PS и получения базовых знаний в плане его применения
Описание слайда:
PowerShell: Познать за 9 часофф Будут рассмотрены общие темы по работе в PS, направленные на осознание возможностей PS и получения базовых знаний в плане его применения

Слайд 2





Немного истории
Описание слайда:
Немного истории

Слайд 3





PowerShell и её предшественники
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 и её предшественники 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
Описание слайда:
Зачем использовать PowerShell Язык высокого уровня Базируется на .NET Командлеты является специализированными классами .NET Возможность пользоваться конвейером Расширенная система типов (Extended Type System, ETS), базирующаяся на .NET

Слайд 5





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

Слайд 7





PowerShell в книгах
Описание слайда:
PowerShell в книгах

Слайд 8





PowerShell в книгах
Описание слайда:
PowerShell в книгах

Слайд 9





PowerShell в книгах
Описание слайда:
PowerShell в книгах

Слайд 10





PowerShell в книгах
Описание слайда:
PowerShell в книгах

Слайд 11





PowerShell в книгах
Описание слайда:
PowerShell в книгах

Слайд 12





Правила именования Commandlets
Verb-Noun
Get-Command
Set-ADUser
Add-Computer
Remove-EventLog
…
Описание слайда:
Правила именования 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
Описание слайда:
О параметрах 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

Слайд 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"
Описание слайда:
Небольшая настройка под себя 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





Изменение ExecutionPolicy
PS> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
PS> Get-ExecutionPolicy
RemoteSigned
PS>
Описание слайда:
Изменение 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.
Описание слайда:
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
Описание слайда:
Использование GB, MB, и KB PS> 1kb 1024 PS> 1mb 1048576 PS> 1gb 1073741824 PS> (1024*1024)/1MB 1

Слайд 23





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

Слайд 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
Описание слайда:
Конвейер 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





Modules
Get-Module
Описание слайда:
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
Описание слайда:
Примеры 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
Описание слайда:
Ввод 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-*
Описание слайда:
Вывод 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
Описание слайда:
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 (Часть команд)
Описание слайда:
Вывод 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
Описание слайда:
Переменные $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
Описание слайда:
Как 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)
Описание слайда:
Переменные. Помощь по переменным. 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’}
Описание слайда:
Переменные. $_ 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] .
Описание слайда:
Переменные. Массивы. $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; 
$a –gt $b; 
$a –ne $b;
Описание слайда:
Пробуем операторы сравнения 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
        }
    }                                                                
}
Описание слайда:
Сравнения. Организация ветвлений. 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}    
    }
}
Описание слайда:
Сравнения. Организация ветвлений. 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
Описание слайда:
Циклы Foreach-Object cmdlet Foreach loop For loop Do loop While loop

Слайд 43





Циклы
For
for ($i = 0; $i -lt somevalue; $i++) {
    < PowerShell code>
}
Описание слайда:
Циклы 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 
 } `
Описание слайда:
Циклы 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 } `

Слайд 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} }
Описание слайда:
Циклы 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.
Описание слайда:
Циклы 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>
}
Описание слайда:
Циклы 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
    }                   
}
Описание слайда:
Циклы 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>)
Описание слайда:
Циклы 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)
Описание слайда:
Циклы 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
Описание слайда:
4 ваших лучших друга Get-Help Get-Command Get-Member Get-PSDrive

Слайд 52





Получение помощи
(Get-Help)
Get-Help <Cmdlet-Name>
get-service | get-member -membertype *property
Описание слайда:
Получение помощи (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
Описание слайда:
Получение списка команд (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
Описание слайда:
Получение списка членов (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
Описание слайда:
Расширенное получение помощи 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:
 <# 
…
#>
Описание слайда:
Основы 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 
    }
}
Описание слайда:
Написание собственных функций 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++
}
Описание слайда:
Написание собственных функций. Использование. $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
Описание слайда:
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
Описание слайда:
Оснастки (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





Рабочие примеры
Описание слайда:
Рабочие примеры

Слайд 62





Практика
Based on 02.ps1
Show process list as a Table
Show by Grouping processes in Table
Advanced grouping
Описание слайда:
Практика Based on 02.ps1 Show process list as a Table Show by Grouping processes in Table 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
}
Описание слайда:
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





Рабочие примеры
Описание слайда:
Рабочие примеры

Слайд 65





Практика
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.
Описание слайда:
Практика 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





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.
Описание слайда:
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
Описание слайда:
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($_.LastBootUpTime)} 
06 January 2012 07:26:53
Описание слайда:
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($_.LastBootUpTime)} 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"
Описание слайда:
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





Рабочие примеры
Описание слайда:
Рабочие примеры

Слайд 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
Описание слайда:
Практика 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)
Описание слайда:
Интеграция с .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
Описание слайда:
Интеграция с .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)
…
Описание слайда:
Интеграция с .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





Рабочие примеры
Описание слайда:
Рабочие примеры

Слайд 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 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.
Описание слайда:
Понятие отладки, базовые рекомендации $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 files (10.ps1)
More informative output
Show files, their lengths, counting numbers
Описание слайда:
Примеры решения задач 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.
Описание слайда:
Практика 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
Описание слайда:
Автоматизация простых рутинных задач с помощью 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.
Описание слайда:
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.
Описание слайда:
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
Описание слайда:
Примеры из реальной жизни 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
Описание слайда:
Итоговая лабораторная работа #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



Похожие презентации
Mypresentation.ru
Загрузить презентацию