Constant Functions

by Nov 30, 2020

In PowerShell, you can write-protect functions. When you do, a function cannot be changed, overwritten or removed anymore during a running PowerShell session. While there may be no apparent use case for this, here is the technique:

$code = 
{
    param
    (
        [string]
        [Parameter(Mandatory)]
        $SomeParameter
    )
    
    "I have received $SomeParameter and could now process it..."
}

$null = New-Item -Path function:Invoke-Something -Options Constant,AllScope -Value $code

# run the function like this
Invoke-Something -SomeParameter "My Data"

Since the function is constant now, trying to redefine it will fail:

# you can no longer overwrite the function
# the following code raises an exception now
function Invoke-Something
{
    # some new code
}

The only way to get rid of the function is to restart your PowerShell session. A more useful scenario may be constant variables: by storing important data in write-protected variables, you can ensure that they cannot be changed by accident or on purpose. This line defines a write-protected variable $testserver1 with some content:

Set-Variable -Name testserver1 -Value server1 -Option Constant, AllScope 


Twitter This Tip! ReTweet this Tip!