0
0
PowerShellscripting~20 mins

Function definition in PowerShell - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PowerShell Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
What is the output of this PowerShell function call?
Consider this PowerShell function definition and call:
function Get-Square {
  param($number)
  return $number * $number
}

Get-Square 4
PowerShell
function Get-Square {
  param($number)
  return $number * $number
}

Get-Square 4
A16
B4
CError: Missing return statement
D8
Attempts:
2 left
💡 Hint
Think about what multiplying a number by itself means.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a PowerShell function with two parameters?
Select the correct syntax for a PowerShell function named 'Add-Numbers' that takes two parameters and returns their sum.
Afunction Add-Numbers { param($a, $b) return $a + $b }
Bfunction Add-Numbers($a, $b) { return $a + $b }
Cfunction Add-Numbers { $a, $b param; return $a + $b }
Dfunction Add-Numbers { param $a $b; return $a + $b }
Attempts:
2 left
💡 Hint
Remember the param block syntax inside a function.
🔧 Debug
advanced
2:00remaining
Why does this PowerShell function fail to return the expected value?
Look at this function and its call:
function Multiply {
  param($x, $y)
  $result = $x * $y
}

Multiply 3 5
PowerShell
function Multiply {
  param($x, $y)
  $result = $x * $y
}

Multiply 3 5
AThe parameters are not defined correctly; they need types.
BThe function does not have a return statement, so it returns nothing.
CThe multiplication operator '*' is invalid in PowerShell.
DThe function name 'Multiply' is a reserved keyword.
Attempts:
2 left
💡 Hint
Think about what PowerShell functions output by default.
🚀 Application
advanced
2:00remaining
What is the output of this PowerShell function with default parameter?
Given this function and call:
function Greet {
  param($name = 'Friend')
  "Hello, $name!"
}

Greet
PowerShell
function Greet {
  param($name = 'Friend')
  "Hello, $name!"
}

Greet
AError: Missing argument for parameter 'name'
BHello, $name!
CHello, !
DHello, Friend!
Attempts:
2 left
💡 Hint
What happens if you call a function without giving a value for a parameter with a default?
🧠 Conceptual
expert
2:00remaining
What is the value of $result after running this PowerShell script?
Analyze this script:
function Test-Output {
  param($val)
  if ($val -gt 10) { return 'High' }
  'Low'
}

$result = Test-Output 5
PowerShell
function Test-Output {
  param($val)
  if ($val -gt 10) { return 'High' }
  'Low'
}

$result = Test-Output 5
$result
A$null
B'High'
C'Low'
D5
Attempts:
2 left
💡 Hint
Consider what happens when the if condition is false and the function reaches the last line.