Say I have MyScript.ps1:
[cmdletbinding()]
param (
[Parameter(Mandatory=$true)]
[string] $MyInput
)
function Show-Input {
param ([string] $Incoming)
Write-Output $Incoming
}
function Save-TheWorld {
#ToDo
}
Write-Host (Show-Input $MyInput)
Is it possible to dot source the functions only somehow? The problem is that if the script above is dot sourced, it executes the whole thing…
Is my best option to use Get-Content and parse out the functions and use Invoke-Expression…? Or is there a way to access PowerShell’s parser programmatically? I see this might be possible with PSv3 using [System.Management.Automation.Language.Parser]::ParseInput but this isn’t an option because it has to work on PSv2.
The reason why I’m asking is that i’m trying out the Pester PowerShell unit testing framework and the way it runs tests on functions is by dot sourcing the file with the functions in the test fixture. The test fixture looks like this:
MyScript.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. "$here\$sut"
Describe "Show-Input" {
It "Verifies input 'Hello' is equal to output 'Hello'" {
$output = Show-Input "Hello"
$output.should.be("Hello")
}
}
Note — if you find this answer helpful please upvote jonZ’s answer as I wouldn’t of been able to come up with this if it weren’t for his helpful answer.
I created this function extractor function based on the script @jonZ linked to. This uses
[System.Management.Automation.PsParser]::Tokenizeto traverse all tokens in the input script and parses out functions into function info objects and returns all function info objects as an array. Each object looks like this:The text property is a string array and can be written to temporary file and dot sourced in or combined into a string using a newline and imported using
Invoke-Expression.Only the function text is extracted so if a line has multiple statements such as:
Get-Process ; function foo () {only the part relevant to the function will be extracted.