I'm writing a script that I'd like to use PowerShell's CmdletBinding() with. Is there a way to define functions in the script? When I try, PowerShell complains about "Unexpected toke 'function' in expression or statement"
Here's a simplified example of what I'm trying to do.
[CmdletBinding()]
param(
[String]
$Value
)
BEGIN {
f("Begin")
}
PROCESS {
f("Process:" + $Value)
}
END {
f("End")
}
Function f() {
param([String]$m)
Write-Host $m
}
In my case, writing a module is wasted overhead. The functions only need to be available to this one script. I don't want to have to mess with the module path or the script location. I just want to run a script with functions defined in it.
You use
begin
,process
, andend
blocks when your code is supposed to process pipeline input. Thebegin
block is for pre-processing and runs a single time before processing of the input starts. Theend
block is for post-processing and runs a single time after processing of the input is completed. If you want to call a function anywhere other than theend
block you define it in thebegin
block (re-defining it over and over again in theprocess
block would be a waste of resources, even if you didn't use it in thebegin
block).Quoting from
about_Functions
:If your code doesn't process pipeline input you can drop
begin
,process
, andend
blocks entirely and put everything in the script body:Edit: If you want to put the definition of
f
at the end of your script you need to define the rest of your code as a worker/main/whatever function and call that function at the end of your script, e.g.: