Learn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdf

ClapperboardCinemaPV 246 views 46 slides Dec 10, 2022
Slide 1
Slide 1 of 46
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46

About This Presentation

https://www.news.itentertainment.org/learn-powershell-scripting-tutorial-full-course

powershell scripting tutorial in hindi
useful powershell scripts
powershell projects for beginners
best way to learn powershell


Slide Content

1
Learn Powershell
Scripting Tutorial Full
Course

1.Basics of Powershell
2.Unit Testing with Pester

PowershellBasics
•What is Powershell?
✓It is a simple and powerful scripting language created by Microsoft
✓It is built on the .NET framework.
✓Powerful tool for Automation and designed especially for the system
administrators.
✓It is an object based
✓The commands in the Windows PowerShell are calledcmdlets, which allow
you to manage the computer from the command line
✓Its analogue in Linux OS is called as a Bash scripting

✓WhyusePowerShell?
✓Itisbothascriptinglanguageandacommand-lineShell.
✓Itcaninteractwithadifferentnumberoftechnologies.
✓WindowsPowerShellallowscompleteaccesstoallthetypesinthe.NET
framework.
✓PowerShellisobject-based.
✓ManyinterfacesofGUIthatMicrosoftdesignedforitsvariousproductsare
frontendinterfacestoPowerShell.
✓ItismoresecurethanrunningVBScriptorotherscriptinglanguages.
✓Itallowsperformingrepetitivetasksmoreefficientlybycombiningmultiple
commandsandbywritingscripts.Suppose,asystemadministratorwantsto
createhundredsofactivedirectoryusers,hecanachievethiswiththehelpof
onlysomePowerShellcmdletsplacedinascript.
✓Manycomplexandtime-consumingconfigurationsandtaskscanbedoneina
secondwithsimplecmdletsofPowerShell.
PowershellBasics

HowtostarttheWindowsPowerShell
PowerShellisavailableinallthelatestversionofWindows.WeneedtostartPowerShellbyfollowingthegivensteps:
1.SearchfortheWindowsPowerShell.SelectandClick.
PowerShell Window.
PowershellBasics

PowershellBasics
WindowsPowerShellISE
TheMicrosoftWindowsPowerShellISEisagraphicaluser
interface-basedapplicationandadefaulteditorforWindows
PowerShell.ISEstandsfortheIntegratedScripting
Environment.Itisaninterfaceinwhichwecanruncommands
andwrite,test,anddebugPowerShellscriptswithoutwriting
allthecommandsinthecommand-lineinterface.
TheIntegratedScriptingEnvironment(ISE)providestab
completion,multilineediting,syntaxcoloring,context-
sensitivehelp,selectiveexecution,andsupportforright-to-
leftlanguages.

PowershellBasics
TheISEwindowofPowerShellconsistsoffollowingthreepanes:
✓ScriptPane:Thispaneallowstheuserstocreateandrunthe
scripts.Ausercaneasilyopen,edit,andruntheexistingscriptsin
thescriptpane.
✓OutputPane:Thispanedisplaystheoutputsofthescriptsand
thecommandswhicharerunbyyou.Youcanalsoclearandcopy
thecontentsintheOutputpane.
✓CommandPane:Thispaneallowstheuserstowritethe
commands.Youcaneasilyexecutethesingleormultiple-line
commandinthecommandpane.

PowershellBasics
EnablePowerShellScripts
WhenwestartthePowerShellinacomputersystem,thedefaultexecutionpolicydoes
notallowustoexecuteorrunthescripts.
TherearefourdifferenttypesofexecutionpolicyinPowerShell:
✓Restricted:Inthispolicy,noscriptisexecuted.
✓RemoteSigned:Inthispolicy,onlythosescriptsarerun,whicharedownloadedfromtheInternet,
andthesemustbesignedbythetrustedpublisher.
✓Unrestricted:AllthescriptsofWindowsPowerShellarerun.
✓AllSigned:Onlythosescriptscanberun,whicharesignedbyatrustedpublisher
Example:Set-ExecutionPolicyUnrestricted

PowershellBasics
RunaPowerShellscript
ToexecutethePowerShellscriptfromthecommandline,followthegivensteps:
1)TypetheWindowsPowerShellinthestartmenuandthenopenitbyclickingonaresult.
2)Now,executethescriptbytypingthefullpathtothescriptsuchas(C:\demo\sample.ps1)
orifitisincurrentdirectory,typethefilenamefollowedbyabackslash.
CreateandRunaPowerShellScript
1.Usinganyeditorlikenotepad,Visualstudiocodeetc.
2.PowershellISE

PowershellBasics
WhatisPowerShellCmdlet?
Acmdlet'pronouncedasacommand-lets'isalightweightcommandwhichisusedinthePowerShellenvironment.
ThesearethespecialcommandsinthePowerShellenvironmentwhichimplementsthespecialfunctions.
Thecmdletsfollowa'verb-noun'pattern,suchas'set-childItem'.
Get-Process Thiscmdletgetstheprocesseswhicharerunningonlocalorremotecomputers.
Get-Service Thiscmdletgetstheservicesonlocalorremotecomputers.
Get-History Thiscmdletdisplaysalistofcommandswhichareenteredduringthecurrentsession.
Restart-computer ThiscmdletisusedtorestarttheWindowsoperatingsystemonlocalandremotecomputers.
Restart-Service Thiscmdletstopsandstartsoneormoreservices.
Get-Date
Thiscmdletisusedtogetthecurrentdateandtime.
Send-MailMessage Thiscmdletisusedtosendane-mailmessage.
Set-Date Thiscmdletchangesthetimeofthesystem.

PowershellBasics
Running Powershellcommands and check help /Details for the commands
E.g.
Get-Help : -Displays ‘how-to’ information for commands similar man in the unixcommand
Get-Help -Name Get-Command –Detailed
man –Name Get-Command –Detailed
Get-Help -Name Get-Command -ShowWindow
Get-Help –Name *DNS*
Get-Help Process
Get-Command –noun “Time”
Get-Module –Listavailable

PowershellBasics
Pipelining in PowerShell
Return all the services which are Stopped
Get-Service | where-object status -eq "Stopped"
A pipeline isa series of commands connected by pipeline operators( | ) . Each pipeline operator sends the results
of the preceding command to the next command. The output of the first command can be sent for processing as input
to the second command. And that output can be sent to yet another command
Syntax : Command-1 | Command-2 | Command-3
Return all the text file which the size is lessthan1000 kb and in Order or the file
size
Get-ChildItem-Path *.txt |
Where-Object {$_.length -gt1000} |
Sort-Object -Property length |
Format-Table -Property name, length
Return IPv4 Address from the Ipconfig
ipconfig.exe | Select-String-Pattern'IPv4'

PowershellBasics
Creating Variables
What is a Variable?
A “container” that holds PowerShell “things”.Variables are Placeholders.
Use the $ to reference it in PowerShell
E.g.$Name= “Powershell”
$a= 5
$b= Get-Process | Select-Object -First $a
$b
$name= “Bangalore”
"Hello, Welcome to $name."
Tee-Object
Get expression result AND save to a variable
Get-Process ls* | Tee -Variable p

PowershellBasics
PowershellData Types

PowershellBasics
PowerShellOperators
Operators are the building blocks of the Windows PowerShell. An operator is a character that can be used in the
commands or expressions. It tells the compiler or interpreter to perform the specific operations and produce the final
result.
1.ArithmeticOperators:
add(+),subtract(-),multiply(*),ordivide(/)
2.AssignmentOperators
=(Assignmentoperator)
+=(AdditionAssignmentoperator)
-=(SubtractionAssignmentoperator)
*=(MultiplicationAssignmentoperator)
/=(DivisionAssignmentoperator)
%=(ModulusAssignmentoperator)
++(IncrementOperator)
--(DecrementOperator)
E.g.
$a=10+20
$b=$a/5

PowershellBasics
PowerShellOperators
Operators are the building blocks of the Windows PowerShell. An operator is a character that can be used in the
commands or expressions. It tells the compiler or interpreter to perform the specific operations and produce the final
result.
3.ComparisonOperators
-eq(Equal)
-ne(NotEqual)
-gt(Greaterthan)
-ge(GreaterthanorEqualto)
-lt(Lessthan)
-le(LessthanorEqualto)
-like
-notlike
4.LogicalOperators
-and(LogicalAND)
-or(LogicalOR)
-xor(LogicalXOR)
-not(LogicalNOT)
!(SameasLogicalNOT)
E.g.
5–gt2
$a=10
$b=5
$a–gt5
$b–le$a
$name–eq“Accenture”
"foo" –like "f*“
"bar" –notlike"B*
$a –gt10 –AND $a –le 50
$a –eq 10 –OR $a –eq 50

PowershellBasics
PowerShellOperatorsCont..
1.RedirectionOperators
TheRedirectionoperatorsareusedinPowerShelltoredirecttheoutputfromthePowerShell
consoletotextfiles.
1.>
Thisoperatorisusedtosendthespecifiedstreamtothespecifiedtextfile.Thefollowing
statementisthesyntaxtousethisoperator
Syntax:Commandn>Filename
E.g.Get-childitem>YourFile.txt
2.>>
Thisoperatorisusedtoappendthespecifiedstreamtothespecifiedtextfile.
Thefollowingstatementisthesyntaxtousethisoperator:
Syntax:Commandn>>Filename
E.g.Get-help>>k.txt

PowershellBasics
1.SplitandJoinOperators
TheSplitandJoinoperatorsareusedinPowerShelltodivideandcombinethesubstrings.
-JoinOperator
The-JoinoperatorisusedinPowerShellto
combinethesetofstringsintoasinglestring.
Thestringsarecombinedinthesameorderin
whichtheyappearinthecommand.
E.g.-Join"windows","Operating","System"
Thefollowingtwostatementsarethesyntax
tousetheJoinoperator:
-Join<String>
<String>-Join<Delimiter>
-SplitOperator
The-SplitoperatorisusedinPowerShelltodividetheoneor
morestringsintothesubstrings.
Syntax:
1.-Split<String>
2.-Split(<String[]>)
3.<String>-Split <Delimiter> [,<Maxsubstrings>
[,"<Options>"]]
1.<String>-Split{<ScriptBlock>}[,<Max-substrings>]
E.g.
$a="abcdefgh"
-split$a

PowershellBasics
Using Arrays and Hashtables
A data structure that is designed to store a collection of items. The items can be the same type or different
types.
Any comma-separated list is an array
Initializinganemptyarray
We can initialize an empty array by using the
following syntax:
$a = 3,5,9
@arrayName = @()
Array

PowershellBasics
Using Arrays and Hashtables
ManipulationofanArray
Wecanchangethevalueofspecificindexvalueinanarrayby
specifyingthenameofthearrayandtheindexnumberof
valuetochange.
$p[2]=20
$a = 3,5,9
AccessingArrayElements
YoucandisplayallthevaluesofanarrayonthePowerShellconsoleby
typingthenameofanarrayfollowedbyadollar($)sign.
$por$p[1]or$p[2..5]

PowershellBasics
PowerShellHasttable
ThePowerShellHashtableisadatastructurethatstoresoneormorekey/valuepairs.Itisalsoknownasthe
dictionaryoranassociativearray.Thehashtablenameisthekey
Syntax:$variable_name=@{<key1>=<value1>;<key2>=<value2>;.....;<keyN>=<valueN>;}
Thefollowingstatementisthesyntaxtocreateanordereddictionary:
$variable_name=[ordered]@{<key1>=<value1>;<key2>=<value2>;.....;<keyN>=<valueN>;}
$variablename=@{}
$student=@{name="Abhay";Course="BCA";Age=19}
DisplayaHashtable
$Student

PowershellBasics
Controlling the flow of PowerShell Functions
IF .. ELSE Statement
When we need to execute the block of statements only when the specified condition is true, use anIf
statement.
f(test_expression)
{
Statement-1
Statement-2.......
Statement-N
}
else
{
Statement-1
Statement-2.......
Statement-N
}
$a=15
$c=$a%2
if($c -eq 0)
{
echo "The number is even"
} else
{
echo "The number is Odd"
}

PowershellBasics
Switch Statement Syntax
# Syntax
Switch (<expression>) {
<condition1> { <code> }
<condition2> { <code> }
<condition3> { <code> }
}
# Variable
$number = 3
# Example Syntax
Switch ($number) {
5 { Write-Host "Number equals 5" }
10 { Write-Host "Number equals 10" }
20 { Write-Host "Number equals 20" }
Default { Write-Host "Number is not equal to 5, 10, or 20"}
}

PowershellBasics
Do-WhileLoop
TheDo-Whileloopisaloopingstructureinwhichaconditionisevaluatedafterexecutingthestatements.Thisloopis
alsoknownastheexit-controlledloop
Syntax
ThefollowingblockshowsthesyntaxofDo-whileloop:
Do
{
Statement-1
Statement-2
Statement-N
}while(test_expression)
$i=1
do
{
echo $i
$i=$i+1
} while($i -le 10)

PowershellBasics
Whileloop
Itisanentry-controlledloop.Thisloopexecutesthestatementsinacodeofblockwhenaspecificconditionevaluatesto
True.
SyntaxofWhileloop
while(test_expression)
{
Statement-1
Statement-2
Statement-N
}
while($count-le5)
{
echo$count
$count+=1
}

PowershellBasics
ForLoop
TheForloopisalsoknownasa'For'statementinaPowerShell.Thisloopexecutesthestatementsinacodeofblock
whenaspecificconditionevaluatestoTrue.Thisloopismostlyusedtoretrievethevaluesofanarray.
SyntaxofForloop
for(<Initialization>;<ConditionorTest_expression>;<Repeat>)
{
Statement-1
Statement-2
Statement-N
}
Examples
for($x=1;$x-lt10;$x=$x+1)
{
echo$x
}

PowershellBasics
ForEachloop
TheForeachisakeywordwhichisusedforloopingoveranarrayoracollectionofobjects,strings,numbers,etc.
Mainly,thisloopisusedinthosesituationswhereweneedtoworkwithoneobjectatatime.
Syntax
Foreach($<item>in$<collection>)
{
Statement-1
Statement-2
Statement-N
}
$Array=1,2,3,4,5,6,7,8,9,10
foreach($numberin$Array)
{
echo$number
}

Powershell
Functions ,
Exception Handling,
Unit Testing with Pester

PowershellBasics
PowerShellFunctions
•AfunctionisalistofPowerShellstatementswhosenameisassignedbytheuser
•FunctionsarethebuildingblockofPowershellscripts
•Reusablethroughoutthescript,whenweneedtousethesamecodeinmorethanonescript,thenweuse
aPowerShellfunction
•Cancontainvariables,parameters,statementsandalsocancallotherfunctions
•Whenweexecuteafunction,wetypethenameofafunction.
FunctionswithArgumentsandParameters
Argument
•Argumentsarenotspecifiedwithinafunction
•Argumentsaresimplypopulatedbypassingvaluestofunctionatthepointofexcuction
•ValuesareretrievedbyusingID
Parameter:
•AParameterisavaribaledefinedinafunciton
•Parametershaveproperties
•ParameterscanbeMandatoryoroptional..

PowershellBasics
Syntax
function<name>[([type]$parameter1[,[type]$parameter2])]
{
param([type]$parameter1[,[type]$parameter2])
dynamicparam{<statementlist>}
begin{<statementlist>}
process{<statementlist>}
end{<statementlist>}
}

PowershellBasics
#Create Function without Arguments
FunctionFind-SquareRoot()
{
$number=Read-Host“Enter any positive Number “
$number=[convert]::ToInt32($number)
return$number*$number
}
Find-SquareRoot
#Creating Function with Arguments
FunctionFind-SquareRoot()
{
$number1=$args[0]
$number2=$args[1]
$result=[convert]::ToInt32($number1) *
[convert]::ToInt32($number2)
return$result
}
Find-SquareRoot252

PowershellBasics
#Create function with Variable
FunctionFind-SquareRoot($num)
{
$number=[convert]::ToInt32($num)
return$number*$number
}
Find-SquareRoot20
#Create function with Variable
functionadd([int]$num1,[int]$num2)
{
$c=$num1+$num2
echo$c
}
#invoking Function
Add 1 2

PowershellBasics
#Creating Function with Parameter
FunctionFind-Capital()
{
Param(
[Parameter(Mandatory=$true)]
[string]$Country
)
if($Country-eq"India")
{
Write-Host"The Capital of $Countryis New Delhi"-ForegroundColor Green
}
else
{
Write-Host"Sorry, Capital not Found!!" -ForegroundColor Red
}
}
Find-Capital-Country"India"

PowershellBasics
Comment PowerShell Scripts
Single-Line PowerShell Comments Begins with the number/hash character (#).
Everything on the same line after it is ignored by PowerShell Block Comments / Multiline Comments Comment
blocks in PowerShell begin with "<#" and end with "#>“

PowershellBasics
Exception Handling in Powershell
An Exception is like an event that is created when normal error handling can not deal with the issue.
Trying to divide a number by zero or running out of memory are examples of something that will
create an exception
To create our own exception event, we throw an exception with the throw keyword.
function Do-Something
{
throw "Bad thing happened"
}

PowershellBasics
Exception Handling in Powershell
Try/Catch
The way exception handling works in PowerShell (and many other languages) is that you first try a
section of code and if it throws an error, you can catch it
Syntax :
try
{
Do-Something
}
catch
{
Write-Output "Something threw an exception"
}
Finally
{
# Execute the final block
}
try
{
Do-Something -ErrorActionStop
}
catch
{
Write-Output "Something threw an exception or used Write-
Error"
}

PowershellBasics
Exception Handling in Powershell
Catching typed exceptions
You can be selective with the exceptions that you catch.
Exceptions have a typeand you can specify the type of exception you want to catch.
try
{
Do-Something -Path $path
}
catch [System.IO.FileNotFoundException]
{
Write-Output "Could not find $path"
}
catch [System.IO.IOException]
{
Write-Output "IO error with the file: $path"
}

Unit Testing with Pester

PowershellUnit Testing with Pester
PowerShell own a Unit testing framework. Its name isPester, it’s the ubiquitous test and mock framework for
PowerShell. It’s a Domain Definition Language and a set of tools to run unit and acceptance test.
Installing Pester
Even if Pester is now installed by default on Windows 10, it’s better to update it to the latest version (now in
4.8.x, soon in 5.x).
Pester can be installed on Windows PowerShell (even on old version) and on PowerShell Core
Install-module -name Pester
You may need to use the force parameter if another is already installed
Install-ModulePester-Force–SkipPublisherCheck
Update-ModulePester–Force
To verify whether the Pester Module Installed
Get-Module -Name Pester -ListAvailable

The basic
A test script starts with a Describe. Describe block create the
test container where you can put data and script to perform
your tests. Every variable created inside a describe block is
deleted at the end of execution of the block.
Describe {
# Test Code here
}
PowershellUnit Testing with Pester
Describe"test"{
It"true is not false" {
$true|Should-Be$true
}
}
Describe"Test Calculate Method" {
Context"Adding Numbers"{
It"Should be 5"{
$result=Add-Number23
$result|Should-Be5
}
}
}

Tests inside a describe block can be grouped into a Context.
Context is also a container and every data or variable created
inside a context block is deleted at the end of the execution of
the context block
Context and Describe define a scope.
Describe -tag "SQL" -name "Sqk2017" {
# Scope Describe
Context "Context 1" {
# Test code Here
# Scope describe 1
}
Context "Context 2" {
# Test code Here
# Scope describe 2
}
}
Providing Context
Often aDescribeblock can contain many
tests. When there are quite a few, it can be
helpful to group related tests into blocks. This
is where theContextfunction comes into
play. You can think of aContextas a sub-
Describe, it will provide an extra level in the
output.
PowershellUnit Testing with Pester

Describe'Grouping using Context'{
Context'Test Group 1 Boolean Tests'{
It'Should be true'{$true|Should-Be$true}
It'Should be true'{$true|Should-BeTrue}
It'Should be false'{$false|Should-Be$false}
It'Should be false'{$false|Should-BeFalse}
}
Context'Test Group 2 -Negative Assertions'{
It'Should not be true'{$false|Should-Not-BeTrue}
It'Should be false'{$true|Should-Not-Be$false}
}
Context'Test Group 3 -Calculations'{
It'$x Should be 42'{
$x=42*1
$x|Should-Be42
}
It'Should be greater than or equal to 33'{
$y=3*11
$y|Should-BeGreaterOrEqual33
}
It'Should with a calculated value'{
$y=3
($y*11)|Should-BeGreaterThan30
}
}
Context'Test Group 4 -String tests'{
$testValue='ArcaneCode'
# Test using a Like (not case senstive)
It"Testing to see if $testValuehas arcane"{
$testValue|Should-BeLike"arcane*"
}
# Test using cLike(case sensitive)
It"Testing to see if $testValuehas Arcane"{
$testValue|Should-BeLikeExactly"Arcane*"
}
}
Context'Test Group 5 -Array Tests'{
$myArray='ArcaneCode','http://arcanecode.red','http://arcanecode.me'
It'Should contain ArcaneCode'{
$myArray|Should-Contain'ArcaneCode'
}
It'Should have 3 items'{
$myArray|Should-HaveCount3
}
}
}
PowershellUnit Testing with Pester

It Block
To create a test with Pester we simply use
the keyword It. The It blocks contain the test
script. This script should throw an exception.
It blocks need to have an explicit description
It "return the name of something" and a
script block. The description must be unique
in the scope (Describe or Context).
Itdescription can be static or dynamically
created (ie: you can use a variable as
description as long asthe description is
unique)
There are several assertions:
Assertions Descriptions
Be Compare the 2 objects
BeExactly Compare the 2 objects in case sensitive mode
BeGreaterThan The object must be greater than the value
BeGreaterOrEqual The object must be greater or equal than the value
BeIn test if the object is in array
BeLessThan The object must be less than the value
BeLessOrEqual The object must be less or equal than the value
BeLike Perform a -li comparaison
BeLikeExactly Perform a case sensitive -li comparaison
BeOfType Test the type of the value like the -is operator
BeTrue Check if the value is true
BeFalse Check if the value is false
HaveCount The array/collection must have the specified ammountof value
Contain The array/collection must contain the value, like the -contains operator
Exist test if the object exist in a psprovider(file, registry, ...)
FileContentMatch Regex comparaisonin a text file
FileContentMatchExactlyCase sensitive regex comparaisonin a text file
FileContentMatchMultilineRegex comparaisonin a multiline text file
Match RegExComparaison
MatchExactly Case sensitive RegExComparaison
Throw Check if the ScriptBlockthrow an error
BeNullOrEmpty Checks if the values is null or an empty string
PowershellUnit Testing with Pester

write and run Pester tests
You can virtually run pester in any PowerShell file but by
convention, it’s recommended to use a file named
xxx.tests.ps1. One per PowerShell file in your solution. If you
have one file per function it mean one pester .tests.ps1.
You can place pester files in the same folder as your source
code or you can use a tests folder at the root of the repository.
Code Coverage
Code coverage measure the degree to which your code is
executed by your tests. The measure is expressed in a
percentage.
invoke-pester -script .\Calculate.Test.ps1 -CodeCoverage.\calculate.psm1
PowershellUnit Testing with Pester

BeforeAll{
# your function
function Get-Planet ([string]$Name='*')
{
$planets = @(
@{ Name = 'Mercury' }
@{ Name = 'Venus' }
@{ Name = 'Earth' }
@{ Name = 'Mars' }
@{ Name = 'Jupiter' }
@{ Name = 'Saturn' }
@{ Name = 'Uranus' }
@{ Name = 'Neptune' }
) | foreach { [PSCustomObject]$_ }
$planets | where { $_.Name -like $Name }
}
}
# Pester tests
Describe 'Get-Planet' {
It "Given no parameters, it lists all 8 planets" {
$allPlanets= Get-Planet
$allPlanets.Count| Should -Be 8
}
Context "Filtering by Name" {
It "Given valid -Name '<Filter>', it returns '<Expected>'" -TestCases@(
@{ Filter = 'Earth'; Expected = 'Earth' }
@{ Filter = 'ne*' ; Expected = 'Neptune' }
@{ Filter = 'ur*' ; Expected = 'Uranus' }
@{ Filter = 'm*' ; Expected = 'Mercury', 'Mars' }
) {
param ($Filter, $Expected)
$planets = Get-Planet -Name $Filter
$planets.Name| Should -Be $Expected
}
It "Given invalid parameter -Name 'Alpha Centauri', it returns `$null" {
$planets = Get-Planet -Name 'Alpha Centauri'
$planets | Should -Be $null
}
}
}
PowershellUnit Testing with Pester

PowershellReference
Unit testing in PowerShell, introduction to Pester -DEV Community
Run Pester tests on Azure Pipelines –Cloud Notes
GitHub -pester/Pester: Pester is the ubiquitous test and mock framework for PowerShell.
Quick Start | Pester (pester-docs.netlify.app)