Coming soon - Get a detailed view of why an account is flagged as spam!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

9
Add function to parent scope
Post Body

Hi r/PowerShell

I have a main script that runs continuously (ParentScope.ps1) and periodically invokes another script (ChildScope.ps1) with Invoke-Expression. The first time it does this, it initializes some things, and loads some functions with dot sourcing another file (Load-Functions.ps1).

ParentScope:

foreach ($n in (0..1)) {

    Invoke-Expression -Command .\\ChildScope.ps1

}

ChildScope:

if ($n -eq 0) {

    Write-Verbose "dot source Load-Functions.ps1" -Verbose

    . ".\Load-Functions.ps1"

}
else {

    Write-Verbose "Trying to use function My-Function" -Verbose
    My-Function

}

Load-Functions:

Function My-Function {

    "Hello!"

}

Write-Verbose ("Dot Sourced My-Function") -Verbose

Since Invoke-Expression always created a new scope, the function My-Function isn't available anymore when I try to run it the second time.

How can I add the function to the parent scope? I'm aware that I could just dot source the function in ParentScope.ps1 but I don't want to do that.

Thanks

Author
Account Strength
90%
Account Age
15 years
Verified Email
Yes
Verified Flair
No
Total Karma
4,545
Link Karma
3,347
Comment Karma
1,198
Profile updated: 2 days ago
Posts updated: 10 months ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
6 years ago