EDUCBA

EDUCBA

MENUMENU
  • Blog
  • Free Courses
  • All Courses
  • All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell scriptblock

PowerShell scriptblock

Priya Pedamkar
Article byPriya Pedamkar

Updated March 3, 2023

PowerShell scriptblock

Introduction to PowerShell scriptblock

The following article provides an outline for PowerShell scriptblock. A collection of code or statements that are enclosed with in a {} is known as a scriptblock. It can also be considered as an expression. This makes it easier for the developers to segment the code into various divisions and the same code can be used in various places with ease. It is like a function, but scriptblock doesn’t have a name. We can consider scriptblock as an anonymous function. The main advantage of the scriptblock is that it is easily portable. scriptblock like a function can accept input parameters and a return value.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax of PowerShell scriptblock

A scriptblock is defined as follows:

{
//statement1
//statement2
//statement3
// statement 4
// statement 5
}

The output of the cmdlets inside the scriptblock is returned either as a single object or as an array.

The param keyword is used to denote the input parameters for the scriptblock and return keyword denotes the return value. Once the return line is reached, the control is exited from the scriptblock

{
Param([type]$Parameter1 [,[type]$Parameter2])
//statement1
//statement2
//statement3
//statement 4
//statement 5
Return
}

A scriptblock is an object of .net framework type System.Management.Automation.ScriptBlock. Certain cmdlets have script block as a parameter.

Example:

Code:

Invoke-Command -ScriptBlock { Get-Command }

Output:

PowerShell scriptblock 1

Difference Between Function and scriptblock

The main difference between a function and a scriptblock is that a function can’t be assigned to a variable whereas a scriptblock can be assigned as a value to a variable. scriptblock are easily portable and hence should be used wisely.

Example:

Function declaration and calling.

Code:

Function test
{
Write-host “test function”
Write-host “No parameters to the function”
}

Calling the function.

Code:

Test
Now lets see how to define and call a script block
$var={write-host “Example of script block” }
$var
& $var

If $var is called the below output is displayed.

Output:

If $var is called

To call a script block & symbol must be used.

Passing Parameter to scriptblock

Code:

Write-Host "example of passing parameters to scrpit block"
$ip= { Write-Host "my name is:$name" }
$name= 'vignesh'
$username = { Write-Host "my name is $($args[0])..." }

Output:

Passing Parameter

Example #1:

Code:

Invoke-Command -ScriptBlock {
param(
$age = "12")
Write-Host "Age is $age" -ForegroundColor Green
}
Invoke-Command -ScriptBlock {
param(
$empid = "123")
Write-Host "emp id is $empid" -ForegroundColor Yellow
} -ArgumentList "Bad"

Output:

PowerShell scriptblock 4

Lets’ say a variable is called inside a scriptblock, the variables value is changed outside the scriptblock then it is changed inside the scriptblock. This is called setting by reference. If the value doesn’t need to be changed GetNewClosure() method has to be used.

Example #2:

Code:

write-Host " example of reference"
>$a=1
$b=2
$c=3
$d=$a+$b+$c
$sb= {"sum is $d"}
Write-Host "Using closure"
write-Host " example of reference"
$a1=1
$b2=2
$c3=3
$e=$a1+$b2+$c3
$sb1= {"sum is $e"}.GetNewClosure()

Output:

PowerShell scriptblock 5

Begin Process and End

Like a function, Begin process and End can be added to a scriptblock. The begin block is used to define variables, path etc. The process block contains the code for manipulation. End block is cleaning up the code.

Example #1:

Code:

$test = {
begin { '[Begin  ] welcome to the demo' }
process { "[age] $_" }
end { Write-Output '[End    ] completed' }
}
22, 33, 44 | & $test

Output:

welcome to the demo

Example #2:

Code:

Write-Host "Example of simple script block with invoke command"
Invoke-Command -ScriptBlock { Get-Date }
Write-Host "Example of creating and calling a simple script block"
$test={write-host “Example of defining and calling script  block” }
& $test
Write-Host "Script block is called above"
Write-Host "example of passing parameters to scrpit block"
$ip= { Write-Host "my name is:$name" }
$name= "suriya"
Write-Host "&$ip"
$username = { Write-Host "my name is $($args[0])..." }
& $username 'nandhini'
Write-Host "Script block with param is executed"
Write-Host "example of script block with param keyword"
Invoke-Command -ScriptBlock {
param(
$height = "5.2")
Write-Host "height is $height" -ForegroundColor Green
}
Invoke-Command -ScriptBlock {
param(
$design = "manager")
Write-Host "designation id is $design" -ForegroundColor Yellow
} -ArgumentList "manager"
write-Host " example of calling by reference"
$age=10
$boy=24
$csa=36
$dsa=$age+$boy+$csa
$sb= {"sum is $dsa"}
Write-Host "total &$dsa"
Write-Host "Using closure method"
write-Host " example of reference"
$a1=1
$b2=2
$c3=3
$e=$a1+$b2+$c3
$sb1= {"sum is $e"}.GetNewClosure()
$inputs = {
begin { '[Begin  ] welcome to the demo of script block' }
process { "[dob] $_" }
end { Write-Output '[End    ] finished' }
}
2020, 2033, 2044 | & $inputs

Output:

PowerShell scriptblock 7

Using Delay-Bind in scriptblock

When a parameter accepts input either as a value or as a property name then delay binding can be used on that parameter. The piped object can be referenced inside the scriptblock using the variable $_. This is helpful in executing complex cmdlets where this allows for one object to produce other parameters. Parameter names must be explicitly specified while using delay binding The parameter shouldn’t be untyped or scriptblock or object type. If delay binding is used without entering pipeline input an error will be thrown.

Conclusion – PowerShell scriptblock

Thus in this article we saw detail about script block, defining a script block, adding and passing parameters to the script block. It also showed with appropriate examples on how to define and call a script block. The article also contained various other relevant examples related to scriptblock. We also saw about delay binding in scriptblock and its use.

Recommended Articles

This is a guide to PowerShell scriptblock. Here we discuss the introduction, difference between function and scriptblock, passing parameter to scriptblock, begin process and end and using Delay-Bind in scriptblock. You may also have a look at the following articles to learn more –

  1. Else If in PowerShell
  2. PowerShell Send Mail
  3. PowerShell Get-Service
  4. PowerShell String Replace
MICROSOFT POWER BI Course Bundle - 8 Courses in 1
34+ Hours of HD Videos
8 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
CYBER SECURITY & ETHICAL HACKING Course Bundle - 13 Courses in 1 | 3 Mock Tests
64+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
MICROSOFT AZURE Course Bundle - 15 Courses in 1 | 12 Mock Tests
62+ Hour of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
KALI LINUX Course Bundle - 6 Courses in 1
20+ Hours of HD Videos
6 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
Primary Sidebar
Popular Course in this category
WINDOWS POWERSHELL Course Bundle - 7 Courses in 1
 19+ Hours of HD Videos
7 Courses
Verifiable Certificate of Completion
  Lifetime Access
4.5
Price

View Course
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more