2

Is there an option to change the default variable scope to private for a script? E.g. via PSDefaultParameterValues?

I don't like that variables are used from parent when they are note defined in the current scope.

Set-PSDebug -strict
$a = 5
function foo() {
    Write-Host $a
    $a = 8
    Write-Host $a
}
foo
$a

This will output 5, 8, 5

Currently I have to prefix every variable with 'private:'. This will output "The variable '$private:a' cannot be retrieved because it has not been set.", 8, 5

Everything as expected but it looks ugly.

Set-PSDebug -strict
$private:a = 5
function foo() {
    Write-Host $private:a
    $private:a = 8
    Write-Host $private:a
}
foo
$private:a

1 Answer 1

1

I dont think you can globaly modify this behaviour, from get-help about_scope

Unless you explicitly make the items private, the items in the parent scope are available to the child scope. However, items that you create and change in the child scope do not affect the parent scope, unless you explicitly specify the scope when you create the items.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.