scripting in windows environments - kszk.sch.bme.hu · •cmd.exe – windows nt •cscript.exe /...
TRANSCRIPT
About Me
• MSc Student @ BUTE (BME)
• Member of KSZK since 2011
• Relevant certifications:
2016.04.03. Gergő Ládi ([email protected]) 2
Outline
• What is PowerShell? • Versions
• Features
• Scripting in PowerShell • PowerShell 101: cmdlets, aliases, comments, variables, (using) operators, control structures, working with files
• Advanced scripting: functions of your own, custom aliases, using .NET classes, loading dynamic code PSProviders & PSDrives, remoting, package management
2016.04.03. Gergő Ládi ([email protected]) 3
CLIs in 2016 :O ?!
2016.04.03. Gergő Ládi ([email protected])
CLIs in 2016 :O ?!
• One might be tempted to think that Command Line Interfaces are a thing of the past…
• Both GUIs and CLIs have their own strengths and weaknesses • CLIs are more efficient, …
• Less RAM, CPU, disk usage • Operations usually take less time to perform • Possibility of automation
• … but have a steeper learning curve • Unusual, confusing at first • Tens (hundreds) of commands with different syntaxes • Feedback: less, later
2016.04.03. Gergő Ládi ([email protected]) 5
What is PowerShell?
2016.04.03. Gergő Ládi ([email protected])
A bit of history
• COMMAND.COM – MS-DOS
• cmd.exe – Windows NT
• cscript.exe / wscript.exe – Windows 98
• Monad (2002) -> Windows PowerShell
• 1.0 (2006) – XP SP2, Server 2003, Vista, (WS 2008) • 2.0 (2009) – Windows 7, Windows Server 2008 R2
• 3.0 (2011) – Windows 8, Windows Server 2012
• 4.0 (2013) – Windows 8.1, Windows Server 2012 R2
• 5.0 (2015) – Windows 10, Windows Server 2016
2016.04.03. Gergő Ládi ([email protected]) 7
Notable features
• Object oriented (1.0)
• Modular (2.0)
• PowerShell Remoting (2.0, 3.0)
• Integrated Scripting Environment (2.0, 3.0)
• Supports debugging (breakpoints) (2.0)
• Asynchronous operations (2.0)
• Transactions (2.0)
• Desired State Configuration support (4.0, 5.0)
• Package management support (5.0)
• Syntax highlighting inside the command line (5.0)
2016.04.03. Gergő Ládi ([email protected]) 8
Where is PowerShell used?
• Windows client operating systems • App-V
• Windows server operating systems • Active Directory
• Microsoft Exchange
• Skype for Business (formerly Lync)
• Computer viruses • CryptoWall, POSHCODER
2016.04.03. Gergő Ládi ([email protected]) 9
PowerShell 101
2016.04.03. Gergő Ládi ([email protected])
PS 101 - Cmdlets
• Cmdlet: a command that performs operations • Not a separate executable
• May take input from the pipeline and may have an input parameter list
• Has the form Verb-Noun • Get-Help
• Get-Help Get-Command
• Get-Help Get-ChildItem –Examples
• Remove-Item C:\Windows\notepad.exe -WhatIf
• Get-ChildItem -File -Path "C:\Windows" | Select-Object Name, Length | Sort-Object -Descending Length
2016.04.03. Gergő Ládi ([email protected]) 11
PS 101 - Aliases
• Alias: a shortcut that invokes a different command (usually one of a longer name) • gci, ls, dir -> Get-ChildItem
• del, rm -> Remove-Item
• cat, gc -> Get-Content
• gh, man -> Get-Help
• To list all available aliases • Get-Alias
2016.04.03. Gergő Ládi ([email protected]) 12
PS 101 - Comments
• Comment: line(s) that are not meant to be interpreted by the parser, but convey information to the (other) programmers • # This is a comment. • <# This is a multi-line comment #>
• Get-Help Get-ChildItem # This is an in-line comment.
2016.04.03. Gergő Ládi ([email protected]) 13
PS 101 - Variables
• Variable: a language construct that can be used to store values • Must begin with the $ sign, e.g. $MyVariable
• Working with variables • $Name = "Jonathan" # String
• $Age = 42 # Integer
• $Hobbies = @("Eating", "Sleeping", "F......") # Array • $John = @{ Name = $Name; Age = $Age; Hobbies = $Hobbies } # Hash
• $UserDirContents = Get-ChildItem -Path "C:\Users\$Name"
2016.04.03. Gergő Ládi ([email protected]) 14
PS 101 - Variables
• Working with variables (cont'd) • Write-Host "$Name is $Age years old." # Will be substituted
• Write-Host '$Name is $Age years old.' # Won't be substituted
• Write-Host "Next year, he'll be $($Age + 1)" # In-line eval.
• Write-Host "$($John.Name) is a nice guy." # Accessing a member
• write-host "$NAME FOR PRESIDENT!" # Cmdlet and variable names are case-INsensitive
2016.04.03. Gergő Ládi ([email protected]) 15
PS 101 – Operators
• -lt, -le, -gt, -ge : <, <=, >, >=
• -eq, -ne : ==, !=
• -band, -bor, -bxor, -bnot : bitwise operators
• -contains, -notcontains
• -like, -notlike, -match, -notmatch
2016.04.03. Gergő Ládi ([email protected]) 16
PS 101 – Using operators
• Using comparison operators • $Age -lt 18
• $Name -eq "jonathan"
• $Name -ceq "jonathan"
• $Hobbies -contains "Eating"
• $Name -like "Jo?ath*"
• "1970.01.01. Epoch" -match "\d{4}\.[0-9]{1,2}\.\d{1,2}\. [a-zA-Z]*"
2016.04.03. Gergő Ládi ([email protected]) 17
PS 101 - Control structures
• Control structure: a structure that analyses state information and changes the execution path based on this • If, If-Else, If-ElseIf-Else, For, ForEach, While, …
• Examples If ($John.Age -lt 18) {
Write-Host "John is under 18!" } ElseIf ($John.Age -eq 18) { Write-Host "John is exactly 18!" } Else { Write-Host "John is over 18! }
2016.04.03. Gergő Ládi ([email protected]) 18
PS 101 - Control structures
For ($i = 0; $i -lt 60; ++$i) {
Write-Host $i
Start-Sleep –Milliseconds 100
}
ForEach ($Hobby in $Hobbies) {
Write-Host "John likes $Hobby"
}
2016.04.03. Gergő Ládi ([email protected]) 19
PS 101 - Control structures
Write-Host "Starting countdown!"
$i = 10
While ($i –gt 0) {
Write-Host ($i--)
Start-Sleep -Milliseconds 100
}
Write-Host "Done."
2016.04.03. Gergő Ládi ([email protected]) 20
PS 101 – Working with files
• $Hobbies | Out-File "JohnsHobbies.txt"
• $Contents = Get-Content JohnsHobbies.txt # Quotes can be omitted
• $UserDirContents | Export-Csv JohnsFiles.csv
• $ImportedData = Import-Csv JohnsFiles.csv
2016.04.03. Gergő Ládi ([email protected]) 21
PowerShell 201
2016.04.03. Gergő Ládi ([email protected])
PS 201 – Functions of your own
• Function: a block of code that can be called multiple times Function Touch-File($File) { If (Test-Path -Path $File) { (Get-ChildItem -Path $File).LastWriteTime = [System.DateTime]::Now } Else { New-Item -Path $File | Out-Null } }
2016.04.03. Gergő Ládi ([email protected]) 23
PS 201 – Aliases, $PROFILE
• New-Alias -Name touch -Value Touch-File
• touch MyFile.txt # is equivalent to Touch-File –File MyFile.txt
• $PROFILE: a script that is executed each time a shell is opened • Add custom function declarations and aliases here to make them permanent
2016.04.03. Gergő Ládi ([email protected]) 24
PS 201 – Using .NET classes
• It is possible to use any BCL classes from the respective .NET Framework version
• You can also load classes from an external assembly
• … or compile code on-the-fly
• $Date = [System.DateTime]::Now
2016.04.03. Gergő Ládi ([email protected]) 25
PS 201 – Using .NET classes
$TcpClient = New-Object System.Net.Sockets.TcpClient
$TcpClient.Connect("max.sch.bme.hu", 25)
$TcpClient.ReceiveTimeout = 5000
$Buffer = New-Object Byte[] 1024
$Recvd = $TcpClient.Client.Receive($Buffer)
Write-Host ([System.Text.Encoding]::ASCII).GetString($Buffer, 0, $Recvd)
2016.04.03. Gergő Ládi ([email protected]) 26
PS 201 – Using .NET classes
$DataToSend = "EHLO" + [Environment]::NewLine
$Buffer = [System.Text.Encoding]::ASCII.GetBytes($DataToSend) $TcpClient.Client.Send($Buffer) | Out-Null
$Buffer = New-Object Byte[] 1024
$Recvd = $TcpClient.Client.Receive($Buffer)
Write-Host ([System.Text.Encoding]::ASCII).GetString($Buffer, 0, $Recvd)
$TcpClient.Close()
2016.04.03. Gergő Ládi ([email protected]) 27
PS 201 – Loading dynamic code
$MyDynamicCode = @"
namespace MyNamespace {
public static class MyClass {
public static int MyFunction(int i){
return 42 – 2*i;
}
}
}
"@
Add-Type –TypeDefinition $MyDynamicCode –Language Csharp
[MyNamespace.MyClass]::MyFunction(10) # Returns 22
2016.04.03. Gergő Ládi ([email protected]) 28
PS 201 – PSProviders & PSDrives
• Get-PSProvider
• Get-PSDrive
• cd Variable:
• ls
• cd HKCU:
• New-Item -Name "MyKey" -ItemType DWORD -Value 42
2016.04.03. Gergő Ládi ([email protected]) 29
PS 201 – PowerShell remoting
• Enter-PSSession -ComputerName remoteapp
• whoami
• hostname
2016.04.03. Gergő Ládi ([email protected]) 30
PS 201 – Package management
• Install-Package -Provider bootstrap chocolatey
• Get-PackageProvider -Name chocolatey
• Install-Package vlc
2016.04.03. Gergő Ládi ([email protected]) 31
Recommended homework
• Write a PowerShell script that calculates the size of each user's home folder then writes the results to a file, sorted by the total size occupied. Home folders having a size of less than 10 MBs should not appear on the list.
• Write a PowerShell function that takes a web site URL as a parameter and returns a list of all external JavaScript files on that site.
2016.04.03. Gergő Ládi ([email protected]) 32
Sources
• Mastering PowerShell (Dr. Tobias Weltner)
• Windows PowerShell 3.0 Step by Step (Ed Wilson)
• PowerShell Magazine (http://www.powershellmagazine.com)
• Microsoft Developer Network (https://msdn.microsoft.com/en-us/default.aspx)
• Wikipedia (https://en.wikipedia.org)
2016.04.03. Gergő Ládi ([email protected]) 33
Thank you for your attention!
2016.04.03. Gergő Ládi ([email protected])
Q & A
2016.04.03. Gergő Ládi ([email protected])