Last active
December 12, 2015 01:58
-
-
Save mattheyan/4694747 to your computer and use it in GitHub Desktop.
Private variables for a PowerShell 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
| # Source the script | |
| PS> . .\Private-Variable.ps1 | |
| # Set foo variable | |
| PS> Set-Foo (New-Object System.Object) | |
| # Get the value | |
| PS> Get-Foo | |
| Name Value | |
| ---- ----- | |
| Foo System.Object | |
| # Try to access the value directly | |
| PS> Get-Variable -Name "Foo" | |
| Get-Variable : Cannot access the variable '$Foo' because it is a private variable | |
| # Source the script again | |
| PS> . .\Private-Variable.ps1 | |
| # Get the value again | |
| PS> Get-Foo | |
| Name Value | |
| ---- ----- | |
| Foo System.Object |
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 Get-Foo | |
| { | |
| Get-Variable -Name "Foo" -Scope "global" -ErrorAction Ignore | |
| } | |
| function Set-Foo | |
| { | |
| if (Get-Variable -Name "Foo" -Scope "global" -ErrorAction Ignore) { | |
| throw "Foo is already defined!" | |
| } | |
| else { | |
| Set-Variable -Name "Foo" -Value $args[0] -Scope "global" -Visibility Private | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment