Andrew Ducker
Andrew Ducker

Reputation: 5490

How do I put a function into a Powershell script file that I want to be able to call directly?

If I have a powershell script file that I want to be able to call directly, called Find-MyThing how do I add a function into it for it to use?

Basically, I want to write a file like this:

Param(
[Parameter(ValueFromPipeline=$true)]
  $ThingReference)

process{
     $intermediateValue =  DoSomeProcessing($ThingReference)
     $finalValue = DoSomeMoreProcessing($intermediateValue)
     return $finalValue
}

Function DoSomeProcessing($thing){...}

Function DoSomeMoreProcessing($thing){...}

But Powershell doesn't like me having a separate functions in the file. I can wrap up the main processing in a function, but then there's no way to actually call it from outside the file.

Is this possible? Or should I be approaching things entirely differently?

Upvotes: 2

Views: 4254

Answers (1)

Andrew Ducker
Andrew Ducker

Reputation: 5490

Found it!

I can put the functions in the begin block, and that defines them for use later!

Param(
  [Parameter(ValueFromPipeline=$true)]
  $ThingReference)

begin{
Function DoSomeProcessing($thing){...}

Function DoSomeMoreProcessing($thing){...}
}


process{
     $intermediateValue =  DoSomeProcessing($ThingReference)
     $finalValue = DoSomeMoreProcessing($intermediateValue)
     return $finalValue
}

Upvotes: 4

Related Questions