Skip to content

Instantly share code, notes, and snippets.

@mattheyan
Last active December 12, 2015 01:58
Show Gist options
  • Select an option

  • Save mattheyan/4694747 to your computer and use it in GitHub Desktop.

Select an option

Save mattheyan/4694747 to your computer and use it in GitHub Desktop.
Private variables for a PowerShell script
# 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
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