29

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.

8
  • It sounds like you're asking for a module? Aug 4, 2014 at 17:04
  • Hmm, maybe? I'm reading about_scopes right now and it's a bit of help. I thought I could name my function script:isURI and it would change the scope. However, I can still reference isURI from the command line. Aug 4, 2014 at 17:07
  • If a function isn't exported from the module, it won't be visible in a child scope. See help about_Modules for more details. Aug 4, 2014 at 17:18
  • @Bill_Stewart - Yea looks like modules are the only way to do this. Everything in a script has to be at the same scope, otherwise functions can't depend on other functions. I'll go learn up on modules. Aug 4, 2014 at 17:20
  • @Bill_Stewart - Just got it working as a module, and it does exactly what I want (though you have to create a manifest and specify which functions to export). Can you add this as an answer so I can accept it? Aug 4, 2014 at 17:44

5 Answers 5

24

In fact, if you call a .ps1 file, by default any functions and variables declared within it are scoped privately within the script (this is referred to as "script scope"). Since you're seeing both functions defined globally, I infer that you're dot-sourcing SvcTest.ps1, i.e. invoking it like this

PS> . <path>\SvcTest.ps1

rather than calling it like this

PS> <path>\SvcTest.ps1

You have two options.

1. If your private function is only used by one other function in the script, you can declare the private function within the body of the function that uses it, and invoke the script by dot-sourcing it:

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

    if (-Not (isURI($url)))
    {
        Write-Host "Invalid URL: $url"
        return
    }

    # Blah blah blah, implementation not important
}

2. (ed. This option does not work powershell 7.3.4, it should either be removed or fixed, see comment) - If the private function is needed by more than one other function within the script (or even if not, this is an alternative to the above), explicitly declare global scope for any functions that you want defined globally, and then call the script rather than dot-sourcing it:

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


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

   # Blah blah blah, implementation not important
}

In either case, Test-Service will be defined in the global scope, and isURI will be restricted to the script scope.


* One thing that might confuse the issue here is that PowerShell only looks for executables in the path, not the current working directory, unless `.` has been added to the path (which is not the case by default). So, it's typical in PowerShell when invoking scripts in the working directory to precede the script name with `.\`. Don't confuse the `.` representing the working directory with the dot-sourcing operator. This calls a script:
PS> .\SvcTest.ps1

This dot-sources it:

PS> . .\SvcTest.ps1
1
  • 2
    2nd option does not work! Without dot-sourcing the internal function just fails to run. Tested on powershell v5 and v7: PS> .\SvcTest.ps1 PS> Test-Service "http://web.com" isURI : The term 'isURI' is not recognized as the name of a cmdlet, function, script file, or operable program. May 10 at 14:48
8

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.

0
5

If you want to use a private scope for your function, it is done like this in Powershell.

function Private:isURI ([string] $address)
{
   ($address -as [System.URI]).AbsoluteURI -ne $null
}
7
  • Doesn't work. I can still run isURI from the command line. I think because . TestSvc.ps1 adds everything to the current scope? Aug 4, 2014 at 17:08
  • 1
    Use & instead of . to avoid adding the functions to the global context.
    – EBGreen
    Aug 4, 2014 at 17:16
  • @EBGreen - I tried that (and then making Test-Service global). Then running Test-Service gives the error The term 'isURI' is not recognized as the name of a cmdlet Aug 4, 2014 at 17:17
  • couldn't you encapsulate that one-line verification inside your Test-Service function avoiding the need for the second private isURI function. Aug 4, 2014 at 17:25
  • 1
    @Mike The closest you'll get to that is modules
    – Cole9350
    Aug 4, 2014 at 17:32
1

Have you tried moving the isURI function to be a script, and then dot sourcing in your other functions instead of running it as a function?

isuri.ps1:

Param([string] $address)
($address -as [System.URI]).AbsoluteURI -ne $null

svctext.ps1:

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

   # Blah blah blah, implementation not important
}
1

I had a similar issue when creating a .psm1 module. If you use Export-ModuleMember (as Bill_Stewart suggests which is the accepted answer) for the "public" function you can expose your selected function(s). All other functions not exported are hidden publicly but can still be used by the module.

If you don't include the Export-Module statement in your module, all members are automatically exposed.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/export-modulemember?view=powershell-7.2[Export-ModuleMember][1]

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

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

   # Blah blah blah, implementation not important
}

# only expose Test-Service publicly
Export-ModuleMember -Function Test-Service

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.