Search code examples
powershellpowershell-2.0

Is there a way to make certain functions "private" in a PowerShell script?


When my shell starts, I load an external script that has a few functions I use to test things. Something like:

# Include Service Test Tools
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
. $scriptPath\SvcTest.ps1

In SvcTest.ps1, I have two functions:

function isURI ([string] $address)
{
   ($address -as [System.URI]).AbsoluteURI -ne $null
}

As well as:

function Test-Service ([string] $url)
{
   if (-Not (isURI($url)))
   {
      Write-Host "Invalid URL: $url"
      return
   }

   # Blah blah blah, implementation not important
}

The isURI function is basically just a utility function that allows Test-Service and perhaps other functions validate URIs. However, when I start my shell, I see that isURI is a function loaded globally. I can even type isURI http://www.google.com from the command line and get back True.

My Question: Is there a way to make isURI private, so that only functions within SvcTest.ps1 can use it, while still allowing Test-Service to be global? Basically, I'm looking for a way to use property encapsulation within PowerShell scripts.


Solution

  • It sounds to me like you're asking for functionality that's available by creating a module.

    Modules let you encapsulate code and export only desired aliases and/or functions. A module manifest is not strictly required; if you don't use a manifest, you can use Export-ModuleMember to specify what members you want exported from the module.

    See the help about_Modules about topic for more information.