-
Notifications
You must be signed in to change notification settings - Fork 6
extending functions
Chase Florell edited this page Jun 10, 2015
·
3 revisions
On occasion, you might have the need to extend or change the behavior of one of the functions within poshBAR. If you're enhancing the existing functionality, it's highly recommended that you fork the repo, and submit a pull request. But if your changes are custom to your project, here is the recommended approach to extending/enhancing.
# First, move the existing function to a new location
If(Test-Path Function:\Invoke-SomeFunction) {
Copy Function:\Invoke-SomeFunction Function:\Invoke-SomeFunctionOriginal
}
# new function with same name as old function
function Invoke-SomeFunction ($myNewParam, $originalParam) {
# Do additional stuff with $myNewParam
# If Required
Invoke-SomeFunctionOld $originalParam
}
Export-ModuleMember Invoke-SomeFunction
And when you need to access it
Import-Module ‘path\to\poshBAR’
Import-Module ‘path\to\Invoke-SomeFunction’ # ensure its imported AFTER poshBAR
A practical example of this is how poshBAR enhanced the native Get-PfxCertificate
method to add support for passing in a password.
if(Test-Path Function:\Get-PfxCertificate){
Copy Function:\Get-PfxCertificate Function:\Get-PfxCertificateOriginal
}
function Get-PfxCertificate {
[CmdletBinding(DefaultParameterSetName='ByPath')]
param(
[Parameter(Position=0, Mandatory=$true, ParameterSetName='ByPath')] [string[]] $filePath,
[Parameter(Mandatory=$true, ParameterSetName='ByLiteralPath')] [string[]] $literalPath,
[Parameter(Position=1, ParameterSetName='ByPath')]
[Parameter(Position=1, ParameterSetName='ByLiteralPath')] [string] $password,
[Parameter(Position=2, ParameterSetName='ByPath')]
[Parameter(Position=2, ParameterSetName='ByLiteralPath')] [string]
[ValidateSet('DefaultKeySet','Exportable','MachineKeySet','PersistKeySet','UserKeySet','UserProtected')] $x509KeyStorageFlag = 'DefaultKeySet'
)
if($PsCmdlet.ParameterSetName -eq 'ByPath'){
$literalPath = Resolve-Path $filePath
}
if(!$password){
$cert = Get-PfxCertificateOriginal -literalPath $literalPath
} else {
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($literalPath, $password, $X509KeyStorageFlag)
}
return $cert
}
And now it can be used
Get-PfxCertificate 'C:\path\to\cert.pfx' 'password'