Question:
Is it possible in Powershell to dot-source or re-use somehow script functions without it being executed? I’m trying to reuse the functions of a script, without executing the script itself. I could factor out the functions into a functions only file but I’m trying to avoid doing that.
Example dot-sourced file:
1 2 3 4 5 6 7 |
function doA { Write-Host "DoAMethod" } Write-Host "reuseme.ps1 main." |
Example consuming file:
1 2 3 4 5 |
. ".\reuseme.ps1" Write-Host "consume.ps1 main." doA |
Execution results:
1 2 3 4 |
reuseme.ps1 main. consume.ps1 main. DoAMethod |
Desired result:
1 2 3 |
consume.ps1 main. DoAMethod |
Answer:
You have to execute the function definitions to make them available. There is no way around it.
You could try throwing the PowerShell parser at the file and only executing function definitions and nothing else, but I guess the far easier approach would be to structure your reusable portions as modules or simply as scripts that don’t do anything besides declaring functions.
For the record, a rough test script that would do exactly that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
$file = 'foo.ps1' $tokens = @() $errors = @() $result = [System.Management.Automation.Language.Parser]::ParseFile($file, [ref]$tokens, [ref]$errors) $tokens | %{$s=''; $braces = 0}{ if ($_.TokenFlags -eq 'Keyword' -and $_.Kind -eq 'Function') { $inFunction = $true } if ($inFunction) { $s += $_.Text + ' ' } if ($_.TokenFlags -eq 'ParseModeInvariant' -and $_.Kind -eq 'LCurly') { $braces++ } if ($_.TokenFlags -eq 'ParseModeInvariant' -and $_.Kind -eq 'RCurly') { $braces-- if ($braces -eq 0) { $inFunction = $false; } } if (!$inFunction -and $s -ne '') { $s $s = '' } } | iex |
You will have problems if functions declared in the script reference script parameters (as the parameter block of the script isn’t included). And there are probably a whole host of other problems that can occur that I cannot think of right now. My best advice is still to distinguish between reusable library scripts and scripts intended to be invoked.