Last active
March 5, 2024 17:09
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Import-Module ./common.psm1 | |
Write-Host "This is a.ps1!" | |
./b.ps1 | |
If(IsMain()){ | |
Write-Host "This is a protected part of a.ps1" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Import-Module ./common.psm1 | |
Write-Host "This is b.ps1!" | |
If(IsMain()){ | |
Write-Host "This is a protected part of b.ps1" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> ./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