EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

PowerShell scriptblock

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » PowerShell Tutorial » PowerShell scriptblock

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.

Syntax of PowerShell scriptblock

A scriptblock is defined as follows:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

{
//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”
}

Popular Course in this category
PowerShell Training (2 Courses, 1 Project)2 Online Courses | 1 Hands-on Project | 4+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (3,023 ratings)
Course Price

View Course

Related Courses
Shell Scripting Training (4 Courses, 1 Project)All in One Data Science Bundle (360+ Courses, 50+ projects)Data Visualization Training (15 Courses, 5+ Projects)

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

PowerShell Training (2 Courses, 1 Project)

2 Online Courses

1 Hands-on Project

4+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PowerShell Tutorial
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Rename Folder
    • PowerShell String Replace
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Get-ADUser
    • PowerShell Start-Process
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV 
    • PowerShell Export CSV
  • Basics
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Versions
    • How To Install PowerShell
    • How to Use PowerShell?
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Modules
    • Variable in PowerShell
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell vs PowerShell ISE
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
  • cmdlet
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • PowerShell Out-File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • 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

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

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

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

EDUCBA

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

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

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

Special Offer - PowerShell Training (2 Courses, 1 Project) Learn More