Reputation: 431
I have an Advanced Function with a number of helper functions in a .ps1 script file.
How do organize my functions so I can call AdvFunc from the command line and not break the ability of AdvFunc to use the helper functions?
Abbreviated contents of script.ps1:
Function AdvFunc {
[cmdletbinding(DefaultParameterSetName='Scheduled')]
Param (
[Parameter(ValueFromPipeline=$true, ParameterSetName='Scheduled')]$SomeValue
)
Begin {
$value = Helper1 $stuff
}
Process {
# do stuff
}
End {
# call Helper2
}
}
Helper1 {
Param ($stuff)
# do stuff
Return $valueForAdvFunc
}
Helper2 {
# do other stuff
}
# Entry Point
$collection | AdvFunc
script.ps1 is currently launched by a scheduler and processes pre-defined $collection as expected.
The problem is I need to call AdvFunc from the command like with a different parameter set. I've add the AdHoc
Parameter Set below. This will be used to send a different collection to AdvFunc. As I understand things, this means the first lines of script.ps1 will now need to be:
Param (
[Parameter(ValueFromPipeline=$true, ParameterSetName='Scheduled')]$SomeValue,
[Parameter(ParameterSetName='AdHoc')][string]$OtherValue1,
[Parameter(ParameterSetName='AdHoc')][string]$OtherValue2
)
Obviously this means the helper functions can no longer be in the same .ps1 file.
Does this mean I will now need 3 script files, each dot-sourcing the other as needed?
Should I use: script.ps1 (containing only AdvFunc), helpers.ps1 (containing the several helper functions), and collection.ps1 (with only $collection being piped to script.ps1) ?
Are there any alternatives?
Upvotes: 0
Views: 113
Reputation: 431
Proposed solution: Use a launcher script that sources script.ps1. All functions (AdvFunc and all helper functions) reside in script.ps1.
# launcher.ps1
[cmdletbinding(DefaultParameterSetName='Scheduled')]
Param (
[Parameter(ParameterSetName='AdHoc', Mandatory=$true)][ValidateNotNullOrEmpty()][string]$Param1,
[Parameter(ParameterSetName='AdHoc', Mandatory=$true)][ValidateNotNullOrEmpty()][string]$Param2,
[Parameter(ParameterSetName='AdHoc', Mandatory=$true)][ValidateNotNullOrEmpty()][string]$Param3
)
. .\script.ps1
if ($PSBoundParameters.ContainsKey('param1')) {
AdvFunc -Param1 $Param1 -Param2 $Param2 -Param3 $Param3
}
else {
$collection | AdvFunc
}
The idea is to accommodate either no parameter (sending $collection
to AdvFunc) or a full 'AdHoc' set of parameters (sending the command-line defined collection to AdvFunc). The empty 'Scheduled' Parameter Set may not be necessary to accommodate the no parameter option.
Upvotes: 1