EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
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.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

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

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

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

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
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 Login

Forgot Password?

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

🚀 Limited Time Offer! - ENROLL NOW