Home > PowerShell > How to write PowerShell code part 2 (Using function)

How to write PowerShell code part 2 (Using function)

In the last post, I have showed you how to use external configuration file in your PowerShell script. In this post, I will show you how to create PowerShell function and call external PowerShell script.You can download the script here.

1. In the original script, I create the site directly using New-SPSite command. I will refactor it so that I will create a new function to create the site using New-SPSite. The PowerShell function is quite similar to a C# method. You put your function parameters in () and separate each parameter by a comma (,). Then you put your method body in {}.

function add ([int] $num1 , [int] $num2){
$total=$num1+$num2
#Return $total
$total
}

2. The difference is you do not need semi-colon (;) at the end of each statement and when calling the method you do not need comma (,) to separate each parameter.

function add ([int] $num1 , [int] $num2){
$total=$num1+$num2

#Return $total
$total
}

#Calling the function
[int] $num1=3
[int] $num2=4
$d= add $num1 $num2
Write-Host $d

3. If you like to return anything from the function, you just need to type in the object you like to return, not need to type return .e.g. $ObjectToReturn not return $ObjectToReturn

 

How to write PowerShell code part 1
How to write PowerShell code part 2
How to write PowerShell code part 3
How to write PowerShell code part 4

Advertisements
Categories: PowerShell Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: