PowerShell 102

Functions are your Friends

Agenda

  • Why Functions?
  • Start with a Script  > Convert to Function
  • From Scratch
    • Syntax
    • Parameters

Why Functions

Cause they're awesome!

Why?

  • Easier Flow
  • Modular
  • Portable

When?

  • Anytime you open ISE
  • Anytime you open VSCode

PowerShell 101

Review - How to Find Functions!

Get-Command

get-command -CommandType function

Enter the 'Function Drive'

cd function:

To display the functions

dir function:  or   ls function:

Start with a Script

Conversion to a Function

Step 1

Find variables that change or prompt users for input; move first

Step 2

Find all hard-coded variables; move second

Step 3

Work with variables follows

Step 4

Output final result

Example: Calculator

Add Script

Example

$a = 4
$b = 5

$c = $a + $b

Write-Host $c

Add Script

Example + User Input

[int]$a = Read-Host -Prompt "A"
[int]$b = Read-Host -Prompt "B"

$message = "Your Result:"

$c = $a + $b

Write-Host $message $c

Add Script

Convert to 'Basic' Function

function Add([int]$a, [int]$b) {
    $message = "Your Result:"

    $c = $a + $b

    Write-Host $message $c
}
[int]$a = Read-Host -Prompt "A"
[int]$b = Read-Host -Prompt "B"

$message = "Your Result:"

$c = $a + $b

Write-Host $message $c

Add Script

But nothing happens!!!

function Add([int]$a, [int]$b) {
    $message = "Your Result:"

    $c = $a + $b

    Write-Host $message $c
}
[int]$a = Read-Host -prompt "A"
[int]$b = Read-Host -prompt "B"

Add $a $b

Syntax

Functions from Scratch

TechNet Article

Build a Better Function

SS64

Let's Build From Scratch

Example: Multiply

PowerShell 102

By Ken Maglio

PowerShell 102

Functions are your Friends

  • 722