How to write PowerShell code part 2 (Using function)

Posted by ybbest on YBBest See other posts from YBBest or by ybbest
Published on Sun, 13 May 2012 03:44:13 +0000 Indexed on 2012/06/22 3:26 UTC
Read the original article Hit count: 241

Filed under: Error when finding categories...

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


© YBBest or respective owner