Skip to content

Instantly share code, notes, and snippets.

@nathanchere
Last active March 5, 2024 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanchere/ef6a798f807a45a72b1b8e9eefcbe5f7 to your computer and use it in GitHub Desktop.
Save nathanchere/ef6a798f807a45a72b1b8e9eefcbe5f7 to your computer and use it in GitHub Desktop.
Determining if you are in the main script or being run/imported from another script
Import-Module ./common.psm1
Write-Host "This is a.ps1!"
./b.ps1
If(IsMain()){
Write-Host "This is a protected part of a.ps1"
}
Import-Module ./common.psm1
Write-Host "This is b.ps1!"
If(IsMain()){
Write-Host "This is a protected part of b.ps1"
}
function IsMain() {
# (Get-Variable MyInvocation -Scope 0).Value.PSCommandPath -Eq (Get-Variable MyInvocation -Scope 2).Value.InvocationName
(Get-Variable MyInvocation -Scope Local).Value.PSCommandPath -Eq (Get-Variable MyInvocation -Scope Global).Value.InvocationName
}
Export-ModuleMember -Function 'IsMain'
> ./a.ps1
This is a.ps1!
This is b.ps1!
This is a protected part of a.ps1
> ./b.ps1
This is b.ps1!
This is a protected part of b.ps1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment