Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7923705
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T17:24:20+00:00 2026-06-03T17:24:20+00:00

Say I have MyScript.ps1 : [cmdletbinding()] param ( [Parameter(Mandatory=$true)] [string] $MyInput ) function Show-Input

  • 0

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")
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T17:24:21+00:00Added an answer on June 3, 2026 at 5:24 pm

    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]::Tokenize to 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:

    Start       : 99
    Stop        : 182
    StartLine   : 7
    Name        : Show-Input
    StopLine    : 10
    StartColumn : 5
    StopColumn  : 1
    Text        : {function Show-Input {,     param ([string] $Incoming),     Write-Output $Incoming, }}
    

    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.

    function Get-Functions {
        param (
            [Parameter(Mandatory=$true)]
            [System.IO.FileInfo] $File
        )
    
        try {
            $content = Get-Content $File
            $PSTokens = [System.Management.Automation.PsParser]::Tokenize($content, [ref] $null)
    
            $functions = @()
    
            #Traverse tokens.
            for ($i = 0; $i -lt $PSTokens.Count; $i++) {
                if($PSTokens[$i].Type -eq  'Keyword' -and $PSTokens[$i].Content -eq 'Function' ) {
                    $fxStart = $PSTokens[$i].Start
                    $fxStartLine = $PSTokens[$i].StartLine
                    $fxStartCol = $PSTokens[$i].StartColumn
    
                    #Skip to the function name.
                    while (-not ($PSTokens[$i].Type -eq  'CommandArgument')) {$i++}
                    $functionName = $PSTokens[$i].Content
    
                    #Skip to the start of the function body.
                    while (-not ($PSTokens[$i].Type -eq 'GroupStart') -and -not ($PSTokens[$i].Content -eq '{')) {$i++ }
    
                    #Skip to the closing brace.
                    $startCount = 1 
                    while ($startCount -gt 0) { $i++ 
                        if ($PSTokens[$i].Type -eq 'GroupStart' -and $PSTokens[$i].Content -eq '{') {$startCount++}
                        if ($PSTokens[$i].Type -eq 'GroupEnd'   -and $PSTokens[$i].Content -eq '}') {$startCount--}
                    }
    
                    $fxStop = $PSTokens[$i].Start
                    $fxStopLine = $PSTokens[$i].StartLine
                    $fxStopCol = $PSTokens[$i].StartColumn
    
                    #Extract function text. Handle 1 line functions.
                    $fxText = $content[($fxStartLine -1)..($fxStopLine -1)]
                    $origLine = $fxText[0]
                    $fxText[0] = $fxText[0].Substring(($fxStartCol -1), $fxText[0].Length - ($fxStartCol -1))
                    if ($fxText[0] -eq $fxText[-1]) {
                        $fxText[-1] = $fxText[-1].Substring(0, ($fxStopCol - ($origLine.Length - $fxText[0].Length)))
                    } else {
                        $fxText[-1] = $fxText[-1].Substring(0, ($fxStopCol))
                    }
    
                    $fxInfo = New-Object -TypeName PsObject -Property @{
                        Name = $functionName
                        Start = $fxStart
                        StartLine = $fxStartLine
                        StartColumn = $fxStartCol
                        Stop = $fxStop
                        StopLine = $fxStopLine
                        StopColumn = $fxStopCol
                        Text = $fxText
                    }
                    $functions += $fxInfo
                }
            }
            return $functions
        } catch {
            throw "Failed in parse file '{0}'. The error was '{1}'." -f $File, $_
        }
    }
    
    # Dumping to file and dot sourcing:
    Get-Functions -File C:\MyScript.ps1 | Select -ExpandProperty Text | Out-File C:\fxs.ps1
    . C:\fxs.ps1
    Show-Input "hi"
    
    #Or import without dumping to file:
    
    Get-Functions -File  C:\MyScript.ps1 | % { 
        $_.Text -join [Environment]::NewLine | Invoke-Expression
    }
    Show-Input "hi"
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Say I have an input consisting of 30 numbers, and I want the 1st,
Say I have a file at the URL http://mywebsite.example/myscript.txt that contains a script: #!/bin/bash
I have a vb script (say myScript.vbs) which is used to monitor a file
Say I have a batch file C:\myscript.bat , how can I add a toolbar
Let's say I have a function abc() that will handle the logic related to
Lets say have this immutable record type: public class Record { public Record(int x,
Let's say have something like: SELECT energy_produced, energy_consumed, timestamp1 AS timestamp FROM ( SELECT
Say I have this method public void test(IList<AvaliableFeaturesVm> vm) { } I have this
Say I have the following generic class: public class Foo<T extends Bar> { //
Say I have a method that returns this. Vector[ (PkgLine, Tree) ]() I want

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.