Docsity

PowerShell for Beginners, Lecture notes of Operating Systems

Partial preview of the text

Download PowerShell for Beginners and more Lecture notes Operating Systems in PDF only on Docsity!

PowerShell for

Beginners

BY ALEX RODRICK

Introduction

Sometimes my friends and colleagues used to ask me from where they can start learning PowerShell to which I never had a good answer. Even if I could come up with some points, they always found it difficult to search for the content which they can understand easily. Another challenge they faced was the order in which they should read the topics.

Keeping myself in place of a beginner, I have written this eBook in a way which could be easily understood. I have also added some practice questions that can help in understanding the actual concept behind the various topics, the answers for which can be found at the end.

I hope this guide can help all levels up-level this skill. After following this eBook I hope you will not consider yourself a beginner!

I have also mentioned some tips from my personal experience. I hope you have found them helpful. If

I like to thank my mentor Vikas Sukhija who not only helped me understanding PowerShell but also promoted me to learn it.

Contents

Introduction ....................................................................................................................................... About the Author ...............................................................................................................................

  • Introduction .......................................................................................................................................
  • About the Author ...............................................................................................................................
    1. How to Use This eBook ................................................................................................................
    1. Variable ......................................................................................................................................
    1. Data Types in PowerShell.............................................................................................................
    1. Arrays.........................................................................................................................................
    1. Hashtable ...................................................................................................................................
    1. Wildcards
    1. Pipeline or pipe “|”
    1. Format List, Format Table, Select/Select-Object
    1. Read-Host and Write-Host
    1. If/Then..................................................................................................................................
    1. Where/Where-Object or short form ‘?’
    1. Loops....................................................................................................................................
    • 12.1. ForEach() or short form ‘%’ loop
    • 12.2. For Loop.....................................................................................................................
    • 12.3. While Loop.................................................................................................................
    • 12.4. Do While Loop............................................................................................................
    • 12.5. Do Until Loop
    1. Switch
    1. Functions
    1. Connecting to O365
    1. Tips:
    1. Answers to Practice questions:

1. How to Use This eBook

This eBook contains all the essential information that is required for a beginner to start writing their own scripts. To fully utilize the eBook, please go through each chapter one by one. The topics have been explained using an example so that one can easily understand. A small practice question is available after the topic so that you can try out what you have learnt and if any assistance is required, the answers can be found at the end of the eBook.

What is PowerShell? In the modern world, everyone is striving towards automation. For an Administrator, performing same repetitive tasks can become monotonous which in turn not only reduces the efficiency but can also leads to errors. PowerShell is an interactive command line tool through which you can automate such mundane tasks. You can execute programs known as ‘script (saved as .ps1 file)’ which contains various cmdlets for the respective task.

What is a cmdlet? A cmdlet is simply a command through which you can perform an action. The two most helpful cmdlets that everyone should be aware of are:

  • Get-Command
  • Get-Help

Using the cmdlet ‘Get-Command’, you can find all the available cmdlets even if you do not know the exact cmdlet. For example, you want to restart a service from PowerShell, but you do not know the cmdlet. Although you can assume that it may contain the word ‘service’. In the below screenshot, you found all the available cmdlets that contain the word ‘service’ and therefore, found the cmdlet to restart a service.

PowerShell vs PowerShell ISE

Now you know how you can execute a program or a cmdlet in PowerShell but where should you write a program. You can do it in PowerShell ISE.

2. Variable

Any character that has a symbol ‘$’ in front of it becomes a variable. A variable comes in play when you need to store a value so that you can make use of it later in the script.eg You have 2 values ‘10’ and ‘4’ and you must perform 3 functions on it, like addition, subtraction, multiplication. So, there are 2 ways to perform this task (a) 10+4, 10-4, 10* (b) $a = 10 $b = 4 $a + $b $a - $b $a * $b

3. Data Types in PowerShell

There are different data types in PowerShell that include integers, floating point values, strings, Booleans, and datetime values which are like what you use in our daily life. The GetType method returns the current data type of the given variable.

Variables may be converted from one type to another by explicit conversion.

  • Integer: It is of the type ‘whole number’. Any decimal value is rounded off.
  • Floating Point: The value is of decimal type.
  • String: As the name suggests, it is used for storing letters and characters.
  • Boolean: This value can be either True or False. If it is existing, then it is True otherwise it’ll be False.
  • DateTime: As the name suggests, it is of the type of date and time.

5. Hashtable

A more advanced form of array, known as a hashtable, is assigned with squiggly brackets prefaced by the ‘@’ sign. While arrays are typically (but not always) used to contain similar data, hashtables are better suited for related (rather than similar) data. Individual items within a hashtable are named rather than assigned a numerical index, eg $user=@{FirstName="John"; LastName="Smith"; MiddleInitial="J"; Age=40} Items within a hashtable are easily accessed using the variable and the key name. eg $user.LastName will return the value ”Smith”.

To easily understand hashtables, you can relate it to the following example. As per the below example, you have a table in which the first column contains as “FirstName”, the second column contains the “LastName”, the third column contains the “MiddleInitial” and the fourth column contains the “Age”.

FirstName LastName MiddleInitial Age John Smith D 40 Joe Parker L 32

Gary Smith N 25

Now if you store the above table in a hashtable “$user”, then in order to call the first column you would have to run the command “$user.FirstName” and it will list out all the first names in column 1.

Practice 2: Create 2 hashtables as below and the third hashtable should be calculated as (DaysWorked * SalaryPerDay).

Hashtable 1 Hashtable 2 Hashtable 3 Name DaysWorked Name SalaryPerDay Name Salary John 12 John 100 John 1200 Joe 20 Joe 120 Joe 2400 Mary 18 Mary 150 Mary 2700

In case of queries, please check the answer section.

6. Wildcards

Wildcards are something which you can use to match partial values instead of exact values. The ‘*’ wildcard will match zero or more characters. The ‘?’ wildcard will match a single character.

In the first case, you are checking for the exact service with the name “ALG”. In the second case, you want to find out the services whose name starts with “App”, therefore you added wildcard “*” at the

8. Format List, Format Table, Select/Select-Object

Sometimes when you execute a command, all the information may not show up directly. To retrieve all the information, you can make use of ‘format-list’ or ‘fl’ in short.

In the example, you can see that when you run ‘Get-Date’ command, all information does not show up. To get all the details, you first executed the command ‘Get-Date’ followed by the pipeline operator ‘|’ which takes the output of the preceding command, followed by FL which ‘lists’ all the information.

When you do a ‘Format-List’, you get the default view which shows a certain set of attributes. If you would like to view all the attributes, then add the wildcard ‘*’ after ‘Format-List’ to view all of them. Example,

Now, there could be a case where there are lots of attributes, but you only need to view the attributes that contains a word, example ‘Name’. Then instead of manually searching through all the attributes, we can quickly do so in the following way.

  • ‘Sort-Object’ or ‘Sort’: Data becomes quite easy to view when it is sorted. To sort data, you can make use of this parameter. Example, if you want to sort data based on an attribute, you can do it as below.

Using FT and FL, you can only display the data/information, but it cannot be used to capture the information provided by the command. To use the information provided by a command, you need to make use of ‘Select or Select-Object’

In this example, you can see that if you want to capture only specific details about a command, you can make use of ‘Select’. The ‘Get-Service’ command provides a lot of info or parameters and if you want to capture only specific parameters then you can mention them with ‘Select’.

9. Read-Host and Write-Host

If you are writing a script that requires an input from the user then you can make use of the cmdlet ‘Read-Host’. Using this cmdlet, you can ask a question, for which the user can input any answer. This answer can then be saved in a variable which can be further used in the script.

Comparison Operators

The following operators are all Case-Insensitive by default:

"-eq" Equal "-ne" Not equal "-ge" Greater than or equal "-gt" Greater than "-lt" Less than "-le" Less than or equal "-like" Wildcard comparison "-notlike" Wildcard comparison "-match" Regular expression comparison "-notmatch" Regular expression comparison "-replace" Replace operator "-contains" Containment operator "-notcontains" Containment operator "-shl" Shift bits left (PowerShell 3.0) "-shr" Shift bits right – preserves sign for signed values.(PowerShell 3.0) "-in" Like –contains, but with the operands reversed.(PowerShell 3.0) "-notin" Like –notcontains, but with the operands reversed.(PowerShell 3.0)

To perform a Case-Sensitive comparison just prefix any of the above with "c" eg -ceq for case-sensitive Equals or -creplace for case-sensitive replace. Comparison of types:

"-is" Is of a type "-isnot" Is not of a type "-as" As a type, no error if conversion fails Logical Operators:

"-and" Logical And "-or" Logical Or "-not" logical not "!" logical not

Example, let us find the status of the service ‘Spooler’ and give the output as ‘Service is Good’ if it is in the ‘Running’ state and as ‘Service is Bad’ if it is in Stopped state.

Before starting let us validate the current status first.

Let us understand what is happening in the background.

i. In line 1, the status of the service ‘Spooler’ is saved in the variable $service. Please note that you are only saving 1 attribute ‘Status’ using ‘Select’ instead of saving all attributes. ii. In line 3, the ‘if’ condition is checking whether the status attribute in variable $service is equal to value “Running” which you know is the same. Therefore, the execution goes to line 5 and the output is displayed as ‘Service is Good’.