I have been trying to make a function for hours to only run if it's run by the script and not the terminal.
I have a Profile.ps1 in C:\Users\Alexander\Documents\PowerShell\Profile.ps1
that is run on every terminal instance. Like a linux .bashrc file.
In my Profile.ps1
file I have this.
# Get PowerShell Profile Path
$pwsh = [System.Environment]::GetFolderPath("MyDocuments") + "\powershell"
# Dot source the internal functions I only want to be able to access via script and not terminal.
. $pwsh\internal\funcs.ps1
And inside $pwsh\internal\funcs.ps1
file I have this.
function MyPrivateFunction {
Write-Host "Hello"
}
I have tried using $MyInvocation.CommandOrigin
and it works as expected.
function MyPrivateFunction {
if ($MyInvocation.CommandOrigin -eq "Runspace") {
return
}
Write-Host "Hello"
}
When I start a new terminal the string "Hello"
is written to the screen.
And if I invoke the command MyPrivateFunction like this:
PS C:\Users\Alexander> MyPrivateFunction
It works and returns nothing.
But the problem I have is I don't want to write the if statement in all of the functions.
It would be a lot of code repetition, and wouldn't be good at all.
If I make a function like this in funcs.ps1
:
function Get-Origin {
if ($MyInvocation.CommandOrigin -eq "Runspace") {
Exit
}
}
function MyPrivateFunction {
Get-Origin
Write-Host "Hello"
}
It doesn't work. Because when I call MyPrivateFunction
it returns as Internal
because it gets called by the MyPrivateFunction
function.
So even if you type MyPrivateFunction directly in the terminal it would still be treated as internal
and still print "Hello"
.
And I only want it to run if it's ran by the script.
Kinda like pythons: python if __name__ == __main__
.
I have also tried using .psm1 modules but it will still print Hello
.
I have tried using a .psm1 module
to import the function but it will still print Hello
due to being in the same scope I would guess.
The only solution I have is writing the if ($MyInvocation.CommandOrigin -eq "Runspace")
on every function but I don't think that's a viable option due to a lot of code repetition.
There has to be something better than this.
I also think that this question is unique and has not been asked before. Because I have searched and tried the answer to use PowerShell modules
but it doesn't function in the way I want it to be.
What I expect it to do is to only allow to run the MyPrivateFunction
in the script and not via powershell terminal.
It's in there due to using dot sourcing the funcs.ps1
file.
One way maybe could work is to run a python script and do everything in there but that would be another procedure.