[SOLVED] What does script keyword mean in Powershell 5: Function script:Set-Variables

Issue

I have come across this "script" keyword in Function script:Set-Variables{}

Any idea why it is being used?

Function script:Set-Variables {
$PerTraceArr = @()
$script:ASNOwnerArr = @()
$ASNOwnerObj = New-Object PSObject
$ASNOwnerObj | Add-Member NoteProperty "ASN"("AS0")
$ASNOwnerObj | Add-Member NoteProperty "ASN Owner"("EvilCorp")
$ASNOwnerArr += $ASNOwnerObj #Add some values so the array isn't empty when first checked.
$script:i = 0
$script:x = 0
$script:z = 0
$script:WHOIS = ".origin.asn.cymru.com"
$script:ASNWHOIS = ".asn.cymru.com"
} #End Set-Variables

Thanks!

Solution

To paraphrase the docs on scopes, the "script" scope restricts the visibility of your variable or function to the code that runs from the same script (including "child" scopes). It’s similar to the concept of protected variables in other OOP languages.

Here, it was likely used to prevent you from using an "internal" function used somewhere else in the script. When it is used in a variable, it is often used to prevent tampering with variables you’ve defined somewhere else, or to prevent you from viewing/tampering with internal variables.

However, note that using the "script" scope doesn’t work as expected when you dot-source a script since dot-sourcing loads everything into your current scope, therefore the script scope is the scope you’re in when you dot-source.

Answered By – anto418

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published.