1

My powershell acts very strangely when I try to make a function. To demonstrate, Here is a basic function that, I dunno, calculates the quadratic formula:

  1 function Get-Quadratic {
  2
  3 [CmdletBinding()]
  4
  5 param (
  6         [Parameter(Position = 0, Mandatory = $true)]
  7         [int32]$a
  8         [Parameter(Position = 1, Mandatory = $true)]
  9         [int32]$b
 10         [Parameter(Position = 2, Mandatory = $true)]
 11         [int32]$c
 12 )
 13
 14 Write-Output $a + " " + $b + " " + $c
 15 }

And if you were to try loading this in with . .\quadratic.ps1, you get:

At C:\Users\(me)\Desktop\Cur\playground\quadratic.ps1:7 char:11
+     [int32]$a
+              ~
Missing ')' in function parameter list.
At C:\Users\(me)\Desktop\Cur\playground\quadratic.ps1:1 char:24
+ function Get-Quadratic {
+                        ~
Missing closing '}' in statement block or type definition.
At C:\Users\(me)\Desktop\Cur\playground\quadratic.ps1:12 char:1
+ )
+ ~
Unexpected token ')' in expression or statement.
At C:\Users\(me)\Desktop\Cur\playground\quadratic.ps1:15 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : MissingEndParenthesisInFunctionParameterList

I have followed tutorials down to the pixel when trying to make functions, but my powershell doesn't seem to like even the most basic commands. If it helps, my version is

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      19041  1320
  • 1
    You are missing the commas to separate each parameter – Abraham Zinala Jan 05 '22 at 23:43
  • 1
    Thanks, @Abraham - that is indeed the _primary_ problem: parameter declarations must be `,`-separated. The linked duplicate explains the _secondary_ problem with `Write-Output $a + " " + $b + " " + $c`. – mklement0 Jan 05 '22 at 23:45
  • 1
    @Abraham, given the two distinct problems in the question, I've decided to reopen it. – mklement0 Jan 05 '22 at 23:55

1 Answers1

2

Abraham Zinala provided the crucial pointer with respect to your code's primary problem:

  • The individual parameter declarations inside a param(...) block must be ,-separated.

  • While the conceptual about_Functions does state this requirement, it may not be obvious, given that in other contexts (@(...), $(...) and @{ ... }) separating elements by newlines alone is sufficient. In fact, there is an existing feature request to make the use of , optional - see GitHub issue #8957.

The secondary problem is that Write-Output $a + " " + $b + " " + $c won't work as you expect:

  • Expressions - such as string concatenation with the + operator in your case - require enclosure in (...) in order for their result to be passed as a single command argument - see this answer.
mklement0
  • 382,024
  • 64
  • 607
  • 775