0% found this document useful (0 votes)
47 views47 pages

Scripts and Command Line: Additional Shell Techniques, Tools, and Building Blocks

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 47

Scripts and Command Line

Additional Shell Techniques, Tools, and Building Blocks

SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Homework Progress

as of 16:45
2
Previous Week
Quick overview
What We Covered
 Application Servers
 Internet Information Services
 Microsoft SQL Server
 Putting it all together

4
This Module (M7)
Topics
Table of Contents

1. Working in the Shell


2. Tools and Building Blocks
3. Script Creation Process

6
Lab Infrastructure

7
The End is Near 

THIS MODULE
AND

ONE GO
MORE
TO
8
Scoring for Windows System Administration

TEST
40 pts.
TEAM
PLAY
K
OR
EW
M
HO

PRACTICE
BONUS EXAM
EVALUATION
10 pts. CRITERIA 60 pts.

9
Practice (Remote)

▪ Install and configure few machines


▪ Connect them in a certain way
▪ Install and configure a set of services
▪ Create set of users and groups
▪ Set the appropriate permissions
▪ Write a script that does what requested
▪ Additional tasks as per the exam requirements
10
Test (Remote)

30 20 10 11

minutes single-choice multi-choice


questions questions
Test Your Knowledge

Practice (exam-like) questions:


https://zahariev.pro/events/wsa-2020-02

12
Work in the Shell
Know Your Console
Getting Help
 Our indispensable source is Get-Help
 Many modifiers and one to combine them -ShowWindow
 We can use Get-Member to examine an object
 Or Get-Command -Noun Topic, to get list of related commands
 If wondering what actions are there, then use Get-Verb
 When installing new modules always use Update-Help
 Of course we can use on-line sources, but we should be careful
14
Aliases
 Instead of typing long commands we can shorten them
 There are some pre-built aliases - Get-Alias or just alias
 We can create our own with New-Alias
 Or we can alter existing one with Set-Alias
 Load or save aliases with Import-Alias and Export-Alias
 Unless actions are taken, they live only in our session
 We can sore them in our profile folder $Home\Documents
 Or system-wide in $PsHome
15
Common Commands
 Special system aliases make our life easier
 They mimic common CMD.exe and UNIX shell commands
 Among them we can find
 dir and ls to examine folder’s content
 cd, chdir, md, mkdir, rd, rmdir to change, add, or remove folder
 cat and type to explore file’s content
 ps to get list of running process and others

16
Environment Variables (CMD Shell)
 Before PowerShell there was CMD Shell and it is still there
 There are plenty of existing and well-known commands there
 We can examine its environment by executing set
 Variables are referenced by %VARIABLE%
 Include %PATH%, %COMPUTERNAME%, %USERNAME%, etc.
 Their value can be seen with echo

17
Environment Variables (PowerShell)
 PowerShell is de-facto a standard for the last several years
 Its environment can be explored with Get-Variable
 Of course we can define our own variables with New-Variable
 Alter (Set-Variable) or clear value (Clear-Variable) of existing
 And finally dispose variables with Remove-Variable
 We can use PowerShell variables by name $Variable
 We can use CMD variables with $env:VARIABLE
18
Redirect Output
 Some commands have internal export functions
 Alternative option is the output redirection
 This one history > C:\Temp\history.txt will save session history
 Of course we can use special commands like
 Out-File or Export-CSV
 And we can export to a visual list Out-GridView or ogv
 Screen and file at the same time - Tee-Object or just tee
19
Files and Folders
 We can create new files or folders with New-Item
 Additionally we can copy, move, rename, and delete items
 Clear-Content clears contents of a file
 Get-Item returns the item itself
 And Get-ChildItems returns its children (level 1)
 We can even add -Recurse to get other levels as well

20
PowerShell Profiles
 Added aliases, functions, and variables are not persistent
 To retain changes, we must put them in our profile
 Profile for all users and all shells (hosts)
%windir%\system32\WindowsPowerShell\v1.0\profile.ps1
 Profile for all users, but only to the Microsoft.PowerShell shell
%windir%\system32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1
 Profile for the current user, but affects all shells
%UserProfile%\My Documents\WindowsPowerShell\profile.ps1
 Profile for the current user and the Microsoft.PowerShell shell
%UserProfile%\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
21
Practice: Work in the Shell
Live Demonstration in Class
Tools and Building Blocks
PowerShell ISE
 Powerful development environment
 Productivity improvements
 Section outlining for readability
 Breakpoints for debugging
 Available only for Desktop Experience enabled installations
 Can work simultaneously with multiple source files
 Supports more than one PowerShell session local or remote
https://docs.microsoft.com/en-us/powershell/scripting/core-powershell/ise/keyboard-shortcuts-for-the-windows-powershell-ise?view=powershell-5.1 24
PowerShell Script Building Blocks
#
Comments # colors.ps1
#

Local Variable $color = "blue"

Flow Control if ($color -Eq "red") {


write "red is the color"
} else {
Command write "$color is not red"
}
25
Comments
 Single line
# One line comment
...
# and yet another one
 Multiline
# First line of short multiline comment
# Second line of short multiline comment
...
<#
1-st line of long multiline comment
...
N-th line of long multiline comment
#>
26
Variables and Data Types
 Variable is a named storage for information
 Some of the supported common data types
 [datetime] - date or time
 [string] - string of characters
 [int] - 32-bit integer
 [double] - double-precision floating number
[int]$choice = 5
 If not specified, a variable can change its type on-the-fly
27
Flow Control
 If-Then-Else structure
$limit = 50
$speed = 110
if ($speed -GT $limit) { "You are driving too fast" }
else { "You are a good driver" }
 Switch structure
$color = 2 GT (greater than)
GE (greater than or equal)
LT (less than)
switch ($color) { LE (less than or equal)
1 {"The color is red"} EQ (equal)
2 {"The color is blue"} NE (not equal)
default {"The color is black"} LIKE (match wildcard)
} NOTLIKE (does not match wildcard)
28
Repetitive Tasks
 For (repeat while the condition is true)
for ($i = 1; $i -LE 5; $i++) { ... }

 While (repeat while the condition is true)


$i = 1
while ($i -LE 5) { ... $i++ }
 Do While (repeat while the condition is true)
$i = 1
do { ... $i++ } while ($i -LE 5)
 Do Until (repeat while the condition is NOT true)
$i = 1
do { ... $i++ } until ($i -GT 5)
29
User Interaction
 Get user input
$choice = Read-Host -Prompt "Would you like to continue (Y/N)?"

 Write information back


Write-Host "Your choice is $choice"

 Write conditionally
Write-Verbose "### Here we do this and that"
...
PS C:\> ./script.ps1 -Verbose
...
### Here we do this and that
...
30
Practice: Tools and Building Blocks
Live Demonstration in Class
Script Creation Process
From Start to Finish
Ranges and Arrays
 Ranges are sequence of numeric values
 Single range 1..10
 Combined ranges 1..20 + 40..50
 Arrays are groups of values, can be single- or multi-dimensional
 Implicit declaration - $MyArray = 1, 2, 3, 4, 5
 Range declaration - $MyArray = (1..5)
 Strongly typed - [int[]] $MyArray = (1..5)

33
Iterate Over Ranges and Arrays
 ForEach-Object or for short ForEach
 It can iterate over ranges, arrays, and file contents
 Two usage formats
...
10..20 | ForEach {"192.168.1.$_"}
...
$nodes = (10..20)
ForEach ($node in $nodes) {
"192.168.1.$node"
}
...
34
Goal and Self-Restrictions
 Start with a clear idea of what you would like to achieve
 Don’t even start if
 You will use the end-result one time
 There is an easier way, do it, even on a regular basis
 Always bear in mind the ROI
 Resist the temptation to go big since the very beginning
 Start small, with baby-steps. It is easier to debug if you like
35
Approach

 Break the end-task on simple steps

 Code one step at a time

 Test each individual step. Test often

 Write scripts with the other guy in mind

 Very often the other guy, it is you after a while

36
Good Practices

 Comment (document) what you are doing

 Put comment even after each section end

 Declare variable types explicitly

 Structure your code for readability. Make it pretty 

37
Help Sections
 .SYNOPSIS <#

.SYNOPSIS

 .DESCRIPTION Simple PowerShell script skeleton with help template

.DESCRIPTION
 .PARAMETER <Name> This script is a very simple representation of how a
typical PowerShell routine with help should look like.

 .EXAMPLE .EXAMPLE
./Script.ps1

 .NOTES .NOTES
Put some notes here.

 .LINK .LINK
http://some.internet-domain.com

#>

# TODO: Place your code bellow


38
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comment_based_help?view=powershell-5.1
Sourcing vs Execution
 Execute a script in its own environment
.\Script.ps1
...
C:\Scripts\Script.ps1

 Source a script to make it part of another environment


 In a session
. .\Script.ps1

 In another script
. "C:\Scripts\Script.ps1"
39
Practice: Script Creation Process
Live Demonstration in Class
Summary

 …
  Not
…everything can be or should be done (easily) on
command line
  Currently
… there are many scripting options
 For the last several years PowerShell is the way to go
 Scripts can include individual commands and logic
 Scripts are used to encapsulate and automate set of related
tasks

41
Resources

 …
 …
• Official PowerShell Documentation
 …
https://docs.microsoft.com/en-us/powershell/
• PowerShell Community
https://powershell.org/
• PowerShell E-Books
https://powershell.org/ebooks/
• Hey, Scripting Guy!
https://blogs.technet.microsoft.com/heyscriptingguy/

42
Questions?
SoftUni Diamond Partners
SoftUni Organizational Partners
License
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license

46
Trainings @ Software University (SoftUni)
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg
 Software University Foundation
 http://softuni.foundation
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg

You might also like